[英]Dynamically Creating Multiple TextViews in LinearLayout
我想在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);
}
我只是想学东西,这真的没有目的!
之所以提供NPE,是因为您没有正确设置活动布局。
做这个
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
所在的布局
问题在于root
为null-这是因为您尚未通过setContentView
设置Activity的内容视图。 您需要执行以下操作:
super.onCreate(...); setContentView(R.layout.yourLayoutName); root=(LinearLayout)findViewById(R.id.master);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.