简体   繁体   English

在LinearLayout中动态创建多个TextView

[英]Dynamically Creating Multiple TextViews in LinearLayout

I want to create multiple TextView s inside a LinearLayout .The following code builds successfully but gives a NullPointerException at the line root.addView(t[i]); 我想在LinearLayout创建多个TextView 。以下代码构建成功,但是在root.addView(t[i]);行处提供了NullPointerException root.addView(t[i]);

public class MainActivity extends ActionBarActivity {
    TextView t[];
    LinearLayout root;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        root=(LinearLayout)findViewById(R.id.master);
        t=new TextView[10];
       LinearLayout.LayoutParams dim=new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        for(int i=0;i<10;i++)
        {
            t[i]=new TextView(this);
            t[i].setLayoutParams(dim);
            t[i].setText("YOHOHO: "+i);
            root.addView(t[i]);
        }
        setContentView(root);
    }

This really has no aim Iam just trying to learn things! 我只是想学东西,这真的没有目的!

It's giving NPE because you are not setting your activity layout properly. 之所以提供NPE,是因为您没有正确设置活动布局。

Do this 做这个

 protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.whereLinearLayoutMasterIs); // Add your layout here
    root=(LinearLayout)findViewById(R.id.master);
    t=new TextView[10];
   LinearLayout.LayoutParams dim=new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
    for(int i=0;i<10;i++)
    {
        t[i]=new TextView(this);
        t[i].setLayoutParams(dim);
        t[i].setText("YOHOHO: "+i);
        root.addView(t[i]);
    }
}

NOTE R.layout.whereLinearLayoutMasterIs is indicative, use your layout in which R.id.master is 注意 R.layout.whereLinearLayoutMasterIs是指示性的,请使用R.id.master所在的布局

The problem is that root is null - this is because you've not yet set your Activity's content view via setContentView . 问题在于root为null-这是因为您尚未通过setContentView设置Activity的内容视图。 You need to do something like this: 您需要执行以下操作:

super.onCreate(...); setContentView(R.layout.yourLayoutName); root=(LinearLayout)findViewById(R.id.master);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM