动态创建中的LinearLayout多TextViews [英] Dynamically Creating Multiple TextViews in LinearLayout

查看:223
本文介绍了动态创建中的LinearLayout多TextViews的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要创建多个的TextView 的内线一个的LinearLayout 。下面code成功生成,但给一个 NullPointerException异常在该行 root.addView(T [i]);

I want to create multiple TextViews inside a LinearLayout.The following code builds successfully but gives a NullPointerException at the line 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!

推荐答案

它给NPE,因为你没有正确设置你的活动布局。

It's giving NPE because you are not setting your activity layout properly.

做到这一点。

 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]);
    }
}

注意 R.layout.whereLinearLayoutMasterIs 的象征,用你的布局中, R.id.master

NOTER.layout.whereLinearLayoutMasterIs is indicative, use your layout in which R.id.master is

这篇关于动态创建中的LinearLayout多TextViews的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆