这是一个XML LinearLayout linlayout.xml
:编程添加TextViews到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>
我想补充TextViews
到此布局编程,因为添加的TextViews
的数量可以是不同的,有时。
下面是活动代码:
@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]);
}
}
的LogCat
不显示错误,但TextViews
当我运行的应用程序不会显示。
我尝试把线:
setContentView(R.layout.linlayout);
末,该for
后,但不起作用。
您是否检查文本视图文本的颜色是否与布局的背景颜色不同? – Paul
通过删除TextView来检查txt = new TextView [3]; – mukesh
TextView txt = new TextView [3];通过TextView更改此行txt = new TextView [this]; –