
private LinearLayout layout
private TextView textView
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
layout = new LinearLayout( this ) // 变量layout是该Activity的成员变量(private LinearLayout layout)
layout.setOrientation( LinearLayout.VERTICAL ) // 设置layout布局方向为垂直
setContentView( layout )
// 接下来向layout中添加TextView
textView = new TextView( this )
textView.setText( "This Is a TextView" )
layout.addView( textView )
}
@Override
protected void onResume() {
// TODO Auto-generated method stub
layout.removeView(textView)
super.onResume()
}
}
但是Activity在启动的时候调用onCreate()之后也会调用onResume()方法,所以进入程序也看不到textview了
在Fragment中添加一个布局容器,并设置ID,在Activity中findbyview找到后,就可以动态添加了。
代码如下:
<?xml version="1.0"encoding="utf-8"?>
<LinearLayout xmlns:android="
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<Button
android:id="@+id/first_button"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/first_button"/>
<Button
android:id="@+id/second_button"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/second_button"/>
<Button
android:id="@+id/third_button"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/third_button"/>
</LinearLayout>
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)