How to add a TextView to a LinearLayout dynamically in Android? - android

I try to add a TextView to a LinearLayout dynamically such as in the following code, but it doesn't appear when I run the application?
setContentView(R.layout.advanced);
m_vwJokeLayout=(LinearLayout) this.findViewById(R.id.m_vwJokeLayout);
m_vwJokeEditText=(EditText) this.findViewById(R.id.m_vwJokeEditText);
m_vwJokeButton=(Button) this.findViewById(R.id.m_vwJokeButton);
TextView tv=new TextView(this);
tv.setText("test");
this.m_vwJokeLayout.addView(tv);
What's the problem?

LayoutParams lparams = new LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
TextView tv=new TextView(this);
tv.setLayoutParams(lparams);
tv.setText("test");
this.m_vwJokeLayout.addView(tv);
You can change lparams according to your needs

Here is a more general answer for future viewers of this question. The layout we will make is below:
Method 1: Add TextView to existing LinearLayout
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dynamic_linearlayout);
LinearLayout linearLayout = (LinearLayout) findViewById(R.id.ll_example);
// Add textview 1
TextView textView1 = new TextView(this);
textView1.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT));
textView1.setText("programmatically created TextView1");
textView1.setBackgroundColor(0xff66ff66); // hex color 0xAARRGGBB
textView1.setPadding(20, 20, 20, 20);// in pixels (left, top, right, bottom)
linearLayout.addView(textView1);
// Add textview 2
TextView textView2 = new TextView(this);
LayoutParams layoutParams = new LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT);
layoutParams.gravity = Gravity.RIGHT;
layoutParams.setMargins(10, 10, 10, 10); // (left, top, right, bottom)
textView2.setLayoutParams(layoutParams);
textView2.setText("programmatically created TextView2");
textView2.setTextSize(TypedValue.COMPLEX_UNIT_SP, 18);
textView2.setBackgroundColor(0xffffdbdb); // hex color 0xAARRGGBB
linearLayout.addView(textView2);
}
Note that for LayoutParams you must specify the kind of layout for the import, as in
import android.widget.LinearLayout.LayoutParams;
Otherwise you need to use LinearLayout.LayoutParams in the code.
Here is the xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/ll_example"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ff99ccff"
android:orientation="vertical" >
</LinearLayout>
Method 2: Create both LinearLayout and TextView programmatically
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// NOTE: setContentView is below, not here
// Create new LinearLayout
LinearLayout linearLayout = new LinearLayout(this);
linearLayout.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT));
linearLayout.setOrientation(LinearLayout.VERTICAL);
linearLayout.setBackgroundColor(0xff99ccff);
// Add textviews
TextView textView1 = new TextView(this);
textView1.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT));
textView1.setText("programmatically created TextView1");
textView1.setBackgroundColor(0xff66ff66); // hex color 0xAARRGGBB
textView1.setPadding(20, 20, 20, 20); // in pixels (left, top, right, bottom)
linearLayout.addView(textView1);
TextView textView2 = new TextView(this);
LayoutParams layoutParams = new LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT);
layoutParams.gravity = Gravity.RIGHT;
layoutParams.setMargins(10, 10, 10, 10); // (left, top, right, bottom)
textView2.setLayoutParams(layoutParams);
textView2.setText("programmatically created TextView2");
textView2.setTextSize(TypedValue.COMPLEX_UNIT_SP, 18);
textView2.setBackgroundColor(0xffffdbdb); // hex color 0xAARRGGBB
linearLayout.addView(textView2);
// Set context view
setContentView(linearLayout);
}
Method 3: Programmatically add one xml layout to another xml layout
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dynamic_linearlayout);
LayoutInflater inflater = (LayoutInflater) getApplicationContext().getSystemService(
Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.dynamic_linearlayout_item, null);
FrameLayout container = (FrameLayout) findViewById(R.id.flContainer);
container.addView(view);
}
Here is dynamic_linearlayout.xml:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/flContainer"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</FrameLayout>
And here is the dynamic_linearlayout_item.xml to add:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/ll_example"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ff99ccff"
android:orientation="vertical" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#ff66ff66"
android:padding="20px"
android:text="programmatically created TextView1" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#ffffdbdb"
android:layout_gravity="right"
android:layout_margin="10px"
android:textSize="18sp"
android:text="programmatically created TextView2" />
</LinearLayout>

I customized more #Suragch code. My output looks
I wrote a method to stop code redundancy.
public TextView createATextView(int layout_widh, int layout_height, int align,
String text, int fontSize, int margin, int padding) {
TextView textView_item_name = new TextView(this);
// LayoutParams layoutParams = new LayoutParams(
// LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
// layoutParams.gravity = Gravity.LEFT;
RelativeLayout.LayoutParams _params = new RelativeLayout.LayoutParams(
layout_widh, layout_height);
_params.setMargins(margin, margin, margin, margin);
_params.addRule(align);
textView_item_name.setLayoutParams(_params);
textView_item_name.setText(text);
textView_item_name.setTextSize(TypedValue.COMPLEX_UNIT_SP, fontSize);
textView_item_name.setTextColor(Color.parseColor("#000000"));
// textView1.setBackgroundColor(0xff66ff66); // hex color 0xAARRGGBB
textView_item_name.setPadding(padding, padding, padding, padding);
return textView_item_name;
}
It can be called like
createATextView(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT, RelativeLayout.ALIGN_PARENT_RIGHT,
subTotal.toString(), 20, 10, 20);
Now you can add this to a RelativeLayout dynamically. LinearLayout is also same, just add a orientation.
RelativeLayout primary_layout = new RelativeLayout(this);
LayoutParams layoutParam = new LayoutParams(LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT);
primary_layout.setLayoutParams(layoutParam);
// FOR LINEAR LAYOUT SET ORIENTATION
// primary_layout.setOrientation(LinearLayout.HORIZONTAL);
// FOR BACKGROUND COLOR
primary_layout.setBackgroundColor(0xff99ccff);
primary_layout.addView(createATextView(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT, RelativeLayout.ALIGN_LEFT, list[i],
20, 10, 20));
primary_layout.addView(createATextView(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT, RelativeLayout.ALIGN_PARENT_RIGHT,
subTotal.toString(), 20, 10, 20));

TextView rowTextView = (TextView)getLayoutInflater().inflate(R.layout.yourTextView, null);
rowTextView.setText(text);
layout.addView(rowTextView);
This is how I'm using this:
private List<Tag> tags = new ArrayList<>();
if(tags.isEmpty()){
Gson gson = new Gson();
Type listType = new TypeToken<List<Tag>>() {
}.getType();
tags = gson.fromJson(tour.getTagsJSONArray(), listType);
}
if (flowLayout != null) {
if(!tags.isEmpty()) {
Log.e(TAG, "setTags: "+ flowLayout.getChildCount() );
flowLayout.removeAllViews();
for (Tag tag : tags) {
FlowLayout.LayoutParams lparams = new FlowLayout.LayoutParams(FlowLayout.LayoutParams.WRAP_CONTENT, FlowLayout.LayoutParams.WRAP_CONTENT);
lparams.setMargins(PixelUtil.dpToPx(this, 0), PixelUtil.dpToPx(this, 5), PixelUtil.dpToPx(this, 10), PixelUtil.dpToPx(this, 5));// llp.setMargins(left, top, right, bottom);
TextView rowTextView = (TextView) getLayoutInflater().inflate(R.layout.tag, null);
rowTextView.setText(tag.getLabel());
rowTextView.setLayoutParams(lparams);
flowLayout.addView(rowTextView);
}
}
Log.e(TAG, "setTags: after "+ flowLayout.getChildCount() );
}
And this is my custom TextView named tag:
<?xml version="1.0" encoding="utf-8"?><TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="10dp"
android:textAllCaps="true"
fontPath="#string/font_light"
android:background="#drawable/tag_shape"
android:paddingLeft="11dp"
android:paddingTop="6dp"
android:paddingRight="11dp"
android:paddingBottom="6dp">
this is my tag_shape:
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<solid android:color="#f2f2f2" />
<corners android:radius="15dp" />
</shape>
efect:
In other place I'm adding textviews with language names from dialog with listview:

layout:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<LinearLayout
android:id="#+id/layoutTest"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
>
</LinearLayout>
</RelativeLayout>
class file:
setContentView(R.layout.layout_dynamic);
layoutTest=(LinearLayout)findViewById(R.id.layoutTest);
TextView textView = new TextView(getApplicationContext());
textView.setText("testDynamic textView");
layoutTest.addView(textView);

If you are using Linearlayout. its params should be "wrap_content" to add dynamic data in your layout xml. if you use match or fill parent then you cannot see the output.
It Should be like this.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content" android:layout_height="wrap_content">
<ListView
android:id="#+id/list"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</ListView>
</LinearLayout>

Related

TextView doesn't wrap text

I need dynamically create next xml:
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="2"
android:text="a lot of text will be here"
/>
<EditText
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="3"
/>
</LinearLayout>
and here is my code:
LinearLayout ll = new LinearLayout(getActivity());
ll.setLayoutParams(layoutLP);
TextView title = new TextView(getActivity());
title.setText("a lot of text will be here");
title.setLayoutParams(textLP);
EditText editText = new EditText(getActivity());
editText.setLayoutParams(ediLP);
editText.setSingleLine();
ll.addView(title);
ll.addView(editText);
layoutLP = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
layoutLP.gravity = Gravity.CENTER;
textLP = new LinearLayout.LayoutParams(
0, LinearLayout.LayoutParams.WRAP_CONTENT);
textLP.weight = 2;
textLP.gravity = Gravity.CENTER;
editLP = new LinearLayout.LayoutParams(
0, LinearLayout.LayoutParams.WRAP_CONTENT);
editLP.weight = 3;
editLP.gravity = Gravity.CENTER;
However, on device I get problem: text inside textView is not wrapped and partly covered by editText.
Why does this happen?
And here is how it must looks like:
Your Activity should be
LinearLayout linearLayout = (LinearLayout) findViewById(R.id.ll);
LinearLayout.LayoutParams layoutLP = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
layoutLP.gravity = Gravity.CENTER;
layoutLP.weight = 2;
LinearLayout linearLayout1 = new LinearLayout(this);
linearLayout.setLayoutParams(layoutLP);
linearLayout.setLayoutParams(layoutLP);
linearLayout.setOrientation(LinearLayout.HORIZONTAL);
LinearLayout.LayoutParams textLP = new LinearLayout.LayoutParams(
0, LinearLayout.LayoutParams.WRAP_CONTENT);
textLP.weight = 2;
textLP.gravity = Gravity.CENTER;
LinearLayout.LayoutParams editLP = new LinearLayout.LayoutParams(
0, LinearLayout.LayoutParams.WRAP_CONTENT);
editLP.weight = 3;
editLP.gravity = Gravity.CENTER;
// Add textview 1
TextView textView1 = new TextView(this);
textView1.setLayoutParams(textLP);
textView1.setText("programmatically created TextView1");
// textView1.setBackgroundColor(0xff66ff66); // hex color 0xAARRGGBB
textView1.setPadding(20, 20, 20, 20);// in pixels (left, top, right, bottom)
linearLayout1.addView(textView1);
// Add textview 1
EditText editText = new EditText(this);
editText.setLayoutParams(editLP);
editText.setHint("programmatically created TextView1");
// editText.setBackgroundColor(Color.GRAY); // hex color 0xAARRGGBB
editText.setPadding(20, 20, 20, 20);// in pixels (left, top, right, bottom)
linearLayout1.addView(editText);
linearLayout.addView(linearLayout1);
Your xml file should be:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:orientation="vertical"
android:layout_height="match_parent">
<LinearLayout android:id="#+id/ll"
android:layout_width="match_parent"
android:orientation="horizontal"
android:layout_height="match_parent">
</LinearLayout>
</LinearLayout>
Try your phone or a phone with similar dpi-resolution properties as yours on the AVD, see if it is the same problem. Maybe the resolution on your phone is the problem.

Issue with layout weight in Android LinearLayout

The way my program works is that I take user input for 3 items, create a horizontal LinearLayout programmatically with those three items. Then place that LinearLayout inside a RelativeLayout that is defined in XML.
User can keep adding these 3-item horizontal LLs to the bottom of the RelativeLayout, which acts as a list in this case.
I am specifying a weight in the setLayoutParams method for each TextView object
TextView quantityText = new TextView(MainActivity.this);
quantityText.setLayoutParams(new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT, 1f));
quantityText.setText("" + currentIngredientMeasurementQuantity);
TextView typeText = new TextView(MainActivity.this);
typeText.setLayoutParams(new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT, 1f));
typeText.setText(currentIngredientMeasurementType);
TextView nameText = new TextView(MainActivity.this);
nameText.setLayoutParams(new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT, 4f));
nameText.setText(currentIngredientName);
LinearLayout ll = new LinearLayout(MainActivity.this);
ll.setId(View.generateViewId());
RelativeLayout relativeLayout = (RelativeLayout) findViewById(R.id.ingredient_list_relativelayout);
RelativeLayout.LayoutParams relativeParams = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
//Find last member of RelativeLayout
View lastIngredient = (View) relativeLayout.getChildAt(totalIngredientQuantity - 1);
relativeParams.addRule(RelativeLayout.BELOW, lastIngredient.getId());
relativeParams.setMargins(0, 0, 0, 0);
ll.addView(quantityText);
ll.addView(typeText);
ll.addView(nameText);
relativeLayout.addView(ll, relativeParams);
The problem is, the TextViews aren't being displayed the way I'd like them to. I'd like each of the three items to line up vertically, like a proper list.
Instead, I get something like this. You can see that the length of the strings is somehow affecting the way the layout is stored/displayed.
I know it's a big block of code, but any help would be appreciated!
Try this:-
Create a custom layout insteadof creating controls as dynamically
custom.xml
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:weightSum="90">
<TextView
android:id="#+id/textview1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="30"
android:gravity="center"
android:text="text1"/>
<TextView
android:id="#+id/textview2"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:gravity="center"
android:layout_weight="30"
android:text="text2"/>
<TextView
android:id="#+id/textview3"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:gravity="center"
android:layout_weight="30"
android:text="text3"/>
</LinearLayout>
Add this view in RelativeLayout
View view = factory.inflate(R.layout.custom, null);
relativeLayout.addView(view);
You need to set the layout_width property to 0 for layout weight property to work well. I made a couple to changes to your code to make it work well for me.
Try this,
private void addNewRow(float currentIngredientMeasurementQuantity, String currentIngredientMeasurementType, String currentIngredientName) {
TextView quantityText = new TextView(MainActivity.this);
quantityText.setLayoutParams(new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.WRAP_CONTENT, 1f));
quantityText.setText("" + currentIngredientMeasurementQuantity);
TextView typeText = new TextView(MainActivity.this);
typeText.setLayoutParams(new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.WRAP_CONTENT, 1f));
typeText.setText(currentIngredientMeasurementType);
TextView nameText = new TextView(MainActivity.this);
nameText.setLayoutParams(new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.WRAP_CONTENT, 4f));
nameText.setText(currentIngredientName);
LinearLayout ll = new LinearLayout(MainActivity.this);
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.JELLY_BEAN) {
ll.setId(View.generateViewId());
} else {
ll.setId(totalIngredientQuantity);
}
RelativeLayout relativeLayout = (RelativeLayout) findViewById(R.id.ingredient_list_relativelayout);
RelativeLayout.LayoutParams relativeParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
//Find last member of RelativeLayout
View lastIngredient = (View) relativeLayout.getChildAt(totalIngredientQuantity - 1);
if (lastIngredient != null) {
relativeParams.addRule(RelativeLayout.BELOW, lastIngredient.getId());
relativeParams.setMargins(0, 0, 0, 0);
}
ll.addView(quantityText);
ll.addView(typeText);
ll.addView(nameText);
relativeLayout.addView(ll, relativeParams);
}
You have to set the Gravity to Left (or Start) on your TextViews before adding them to the LinearLayout, just like this:
LinearLayout.LayoutParams name_lp = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT
);
name_lp.gravity = Gravity.LEFT;
nameText.setLayoutParams(name_lp);
Try to tell your your Textviews to use all the available space they can get. So they will fill the whole LinearLayout.
Instead of WRAP_CONTENT use MATCH_PARENT or FILL_PARENT
In XML you could use 0dip like described here: In android layouts what is the effect/meaning of layout_height="0dip"
Another idea would be to use TableLayout or GridLayout http://developer.android.com/reference/android/widget/GridLayout.html
http://developer.android.com/reference/android/widget/TableLayout.html
Have Fun

Android LinearLayout in ScrollView

I tryning to get a LinearLayout in a ScrollView like this:
The greenspace should be wrap_content and the red one should take the remaining space.
But this is my Result:
This is my Code:
foreach(Ele el : elements) {}
LinearLayout layout = new LinearLayout(getActivity());
LayoutParams layout_parm = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
layout.setOrientation(LinearLayout.HORIZONTAL);
layout.setLayoutParams(layout_parm);
TextView tv = new TextView(getActivity());
tv.setLayoutParams( new LayoutParams(0, LayoutParams.WRAP_CONTENT, 1) );
tv.setBackgroundColor(getActivity().getResources().getColor((R.color.red)));
tv.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16);
tv.setText("Name...");
tv.setPadding(0, 0, 0, getDP(5));
layout.addView(tv);
TextView iView = new TextView(getActivity());
iView.setText("OTO");
iView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16);
iView.setBackgroundColor(getActivity().getResources().getColor((R.color.green)));
iView.setLayoutParams( new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, 0) );
layout.addView(iView);
frg_layout.addView(layout);
}
I am so confused! Maybe you can help me to find out my fail...
Thank you!
The Parent-ViewGroup:
<LinearLayout
android:id="#+id/frg_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="top"
android:gravity="top"
android:orientation="vertical" />
you change the layout orientation
LinearLayout layout = new LinearLayout(getActivity());
LayoutParams layout_parm = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
layout.setOrientation(LinearLayout.VERTICAL);
layout.setLayoutParams(layout_parm);
uset this type in xml
<LinearLayout
android:id="#+id/frg_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="#+id/TextView1"
android:layout_width="250dp"
android:layout_height="60dp"/>
<TextView
android:id="#+id/textview2"
android:layout_width="250dp"
android:layout_height="60dp"
/>
</linearlayout>
I think you've mostly got it right, just need a few minor tweaks:
for each(Ele el:elements){
LinearLayout layout = new LinearLayout(getActivity());
LayoutParams layout_parm = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
layout.setOrientation(LinearLayout.HORIZONTAL);
layout.setLayoutParams(layout_parm);
TextView tv = new TextView(getActivity());
//adjust the last number here to make the first block wider or larger as you want
tv.setLayoutParams(new LayoutParams(0, LayoutParams.WRAP_CONTENT, 2));
tv.setBackgroundColor(getActivity().getResources().getColor((R.color.red)));
tv.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16);
tv.setText("Name...");
tv.setPadding(0, 0, 0, getDP(5));
layout.addView(tv);
TextView iView = new TextView(getActivity());
iView.setText("OTO");
iView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16);
iView.setBackgroundColor(getActivity().getResources().getColor((R.color.green)));
//adjust your layout param to be a weight instead of wrap_content
iView.setLayoutParams(new LayoutParams(0, LayoutParams.WRAP_CONTENT, 1));
layout.addView(iView);
frg_layout.addView(layout);
}
See if that works! An alternative would be to build an xml layout which I think is generally cleaner, but programatically it should work roughly the same way.
Using LayoutInflater with xml will bring the solutuion!
Thank you!

setBackgroundColor(int color) and RelativeLayout

When i used this XML file...
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/RelativeLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#FF0000"
tools:context=".MainActivity" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/hello_world" />
</RelativeLayout>
..I see that background color wrap content
http://img716.imageshack.us/img716/8225/rlayout.jpg
But if i write this RelativeLayout by code...
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
RelativeLayout layout = new RelativeLayout(this);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
layout.setBackgroundColor(Color.parseColor("#FF0000"));
TextView text = new TextView(this);
text.setText("Hello world");
//Añado texto
layout.addView(text);
layout.setLayoutParams(params);
setContentView(layout);
}
...I see that background color match parent instead of wrap content
http://img404.imageshack.us/img404/1427/rlayoutfull.jpg
Any ideas?
Thanks!
you are never setting the layout params:
layout.setLayoutParams(params);
and I think that you should place the:
TextView text = new TextView(this);
text.setText("Hello world");
and all other view you will add to your layout before you setting the layout params, otherwise there will be no content to wrap-around.
Edit:
what happens when you set:
tried to replace between the two:
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
?

android Layout weight programmatically

i have hard-coded the layout_weight on layout xml.but now i want to give the layout_weight and weightSum from java code.
How we do that from our class?
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:weightSum="25" >
<TextView
android:id="#+id/textView1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="5"
android:background="#F51215"
android:paddingLeft="5dip"
android:text="5" />
<TextView
android:id="#+id/textView2"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="20"
android:background="#1AC92B"
android:paddingLeft="5dip"
android:text="20" />
</LinearLayout>
Something like this:
......
LinearLayout layout = (LinearLayout)findViewById(YOUR_LAYOT_ID);
layout.setWeightSum(25f);
LinearLayout.LayoutParams lParams = (LinearLayout.LayoutParams) layout.getLayoutParams(); //or create new LayoutParams...
lParams.weight = 0.5f;
.......
someView.setLayoutParams(lParams);
.......
//set as like this below for different view set different float value.
myview.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT,5f));
I just wanted to add an example of how to use the weightsum with e.g a TableRow with TextViews inside:
TableRow row = new TableRow(this);
TableRow.LayoutParams params1 = new TableRow.LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT, 10f);
row.setLayoutParams(params1);
row.setPadding(10, 10, 10, 10);
row.setBackgroundColor(R.color.black);
TextView tv = new TextView(this);
TableRow.LayoutParams params2 = new TableRow.LayoutParams(0, LayoutParams.WRAP_CONTENT, 6f);
tv.setLayoutParams(params2);
tv.setTextSize(30);
tv.setBackgroundResource(R.color.white);
TextView tv2 = new TextView(this);
TableRow.LayoutParams params3 = new TableRow.LayoutParams(0, LayoutParams.MATCH_PARENT, 2f);
tv2.setLayoutParams(params3);
tv2.setBackgroundResource(R.color.green);
TextView tv3 = new TextView(this);
TableRow.LayoutParams params4 = new TableRow.LayoutParams(0, LayoutParams.MATCH_PARENT, 2f);
tv3.setLayoutParams(params4);
tv3.setBackgroundResource(R.color.blue);
Produces the TableRow underneath. The parent whose weightsum is 10, and the children's widths are then equal to 60%, 20% and 20% of the width. The height is here determined by the TextView, tv, which has a height of 30. Hope it helps someone. :-)
If You want to change parent weight programmatically and it's child property as it is then use below
Here's how you set it.
LinearLayout yourLayout=(LinearLayout)findViewById(R.id.container);
yourLayout.setWeightSum(0.6f);
Dynamically Generate TextView with Weight using LinearLayout
LinearLayout lin_hoizontal = new LinearLayout(context);
lin_hoizontal.setOrientation(LinearLayout.HORIZONTAL);
lin_hoizontal.setLayoutParams(new android.widget.LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT, 10f));
lin_hoizontal.setPadding((int) context.getResources().getDimension(R.dimen.d_8), (int) context.getResources().getDimension(R.dimen.d_2), (int) context.getResources().getDimension(R.dimen.d_8), (int) context.getResources().getDimension(R.dimen.d_2));
android.widget.LinearLayout.LayoutParams params_label = new android.widget.LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.WRAP_CONTENT, 2.5f);
TextView txt_label = new TextView(context);
txt_label.setTextColor(context.getResources().getColor(R.color.listing_header_txt_color));//your text color
txt_label.setTextSize(TypedValue.COMPLEX_UNIT_PX, context.getResources().getDimension(R.dimen.d_13));
txt_label.setTypeface(Typeface.create("sans-serif-medium", Typeface.NORMAL));
txt_label.setLayoutParams(params_label);
txt_label.setPadding(0, 0, (int) context.getResources().getDimension(R.dimen.d_2), 0);
txt_label.setText("Label");
android.widget.LinearLayout.LayoutParams params_value = new android.widget.LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.WRAP_CONTENT, 7.5f);
TextView txt_value = new TextView(context);
txt_value.setTextColor(context.getResources().getColor(R.color.listing_header_txt_color));
txt_value.setTextSize(TypedValue.COMPLEX_UNIT_PX, context.getResources().getDimension(R.dimen.d_13));
txt_value.setTypeface(Typeface.create("sans-serif-light", Typeface.NORMAL));
txt_value.setLayoutParams(params_value);
txt_value.setPadding((int) context.getResources().getDimension(R.dimen.d_2), 0, 0, 0);
txt_value.setText("Value");
lin_hoizontal.addView(txt_label);
lin_hoizontal.addView(txt_value);
lin_hoizontal.addView(lin_main);
I like Ajii's answer or:
((LinearLayout)view).setWeightSum(n);
and for individual view weight:
((LinearLayout.LayoutParams)view.getLayoutParams()).weight = n;
of course you can do.. LinearLayout view = findViewById(R.id.view_name);
(and drop the dynamic casting (LinearLayout))
or substitute...……….. findViewById(R.id.view_name) for view above.
These both worked for me.
And if you want value in dimens file:
<item name="new_weight" format="float" type="dimen">(your number)</item>
and: float n = getResources().getFloat(R.dimen.new_weight);
I'm sure you already know most of this but... I was a newbie once and I always appreciated the extra descriptions.

Categories

Resources