无法动态创建LinearLayout

时间:2018-01-21 09:09:21

标签: java android android-linearlayout dynamically-generated

我试图动态创建一个带有多个TextView的LinearLayout,就像在这个论坛上的几个帖子中描述的那样。

    LinearLayout llTest = new LinearLayout(this);

    for(int i=0; i<20; i++){

        TextView tvLine = new TextView(this);
        llTest.addView(tvLine);

        tvLine.setText("Text");
    }

不幸的是,无论我到目前为止用不同的方法尝试过什么,它都不会显示任何空白屏幕。我已经尝试将LayoutParams设置为各种值,setOrientation,setGravity等。我已经使用相当复杂的TableLayout成功创建了一个应用程序但是在这里,TableLayout是用XML创建的,只有TableRows和TextViews是动态创建的。

我的基本错误是什么?

1 个答案:

答案 0 :(得分:0)

你可以这样做

public class MainActivity extends Activity {

 @Override
 protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);

 //Creating LinearLayout.
 LinearLayout linearlayout = new LinearLayout(this);

 //Setting up LinearLayout Orientation
 linearlayout.setOrientation(LinearLayout.VERTICAL);

 LayoutParams linearlayoutlayoutparams = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT); 

 setContentView(linearlayout, linearlayoutlayoutparams);

 LayoutParams LayoutParamsview = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);

 //Creating textview .
 TextView SampleTextView1 = new TextView(this);
 TextView SampleTextView2 = new TextView(this);

 //Adding text to TextView.
 SampleTextView1.setText("First TextView Text");
 SampleTextView2.setText("Second TextView Text");

 //Setting TextView text Size 
 SampleTextView1.setTextSize(25);
 SampleTextView2.setTextSize(25);

 SampleTextView1.setLayoutParams(LayoutParamsview);
 SampleTextView2.setLayoutParams(LayoutParamsview);

 //Adding textview to linear layout using Add View function.
 linearlayout.addView(SampleTextView1);
 linearlayout.addView(SampleTextView2);

 }
}