This is a XML LinearLayout linlayout.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/mylinear"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
</LinearLayout>
I want to add TextViews to this layout programmatically because the number of TextViews to be added can be different sometimes.
Here is the activity code:
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.linlayout);
LinearLayout linear=(LinearLayout) findViewById(R.layout.mylinear);
TextView [] txt =new TextView[3];
for(int i=0;i<txt.length;i++)
{
txt[i]=new TextView(this);
txt[i].setText("text "+i);
txt[i].setLayoutParams(new
LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT));
linear.addView(txt[i]);
}
}
The LogCat don't display errors but the TextViews are not displayed when I run the app.
I try to put the line:
setContentView(R.layout.linlayout);
at the end, after the for, but doesn't work.
Use this :
TextView [] txt = new TextView[3];
for (int i=0; i<txt.length; i++) {
txt[i] = new TextView(YourActivity.this);
txt[i].setText("text " + i);
txt[i].setLayoutParams(newLayoutParams
(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT));
linear.addView(txt[i]);
}
It would be best to use a ListView. By the way did you change the orientation of your layout to a vertical orientation ? But if it necessary for you i suggesst this : i suppose you have an element with a certain size.
final int size = 3; // replace with the size of your element
LinearLayout linear = (LinearLayout) findViewById(R.layout.mylinear);
for(int i=0;i<size;i++){
final TextView textView = new TextView(this);
textView.setText("text "+i);
textView.setLayoutParams(new LayoutParams(
LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT));
linear.addView(textView);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With