<TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="动态添加组件示例" android:id="@+id/textview"/> <LinearLayout android:layout_below="@+id/textview" android:id="@+id/linearlay_1" android:layout_height="wrap_content" android:layout_width="wrap_content" android:orientation="vertical" > </LinearLayout>
/**
* 代码中,布局的位置,是垂直顺序排列的因为界面代码Linerlayout的orientation设置的是
* vertical的,但是为了美观,需要设置添加的View的位置和样式。在添加View的时候分
* 为两类来介绍,一种是布局(例如:Linearlayout和RelativeLayout等,对于RelativeLayout属于相对布局)
*注意,对于LinearLayout布局来说,设置横向还是纵向是必须的!否则就看不到效果了。
*/
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//绑定activity_main布局文件中的布局项,其中R.id.lenearlay_1为布局文件中设置的id
LinearLayout linear=(LinearLayout) findViewById(R.id.linearlay_1);
//添加文本,this代表当前项目
TextView tv=new TextView(this);
tv.setText("示例文本框");
tv.setId(1);//设置ID,可有可无,也可以在R文件中添加字符串,然后在这里使用引用的方式使用
linear.addView(tv);
// 将Button 加入到LinearLayout 中
Button b1 = new Button(this);
b1.setText("取消");
linear. addView ( b1 );
// 将Button 2 加入到LinearLayout 中
Button b2 = new Button(this);
b2.setText("确定");
linear. addView ( b2 );
// 从LinearLayout 中移除Button 1
// linear. removeView ( b1 );
}
}
public class MainActivity extends Activity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//////////////////////////////////////
//创建一个相对布局relative
RelativeLayout relative = new RelativeLayout(this);
relative.setBackgroundColor(Color.YELLOW);
// 将Button1 加入到RelativeLayout 中
Button btn_r1 = new Button(this);
btn_r1.setText("取消");//设置显示的字符
btn_r1.setId(24);
relative.addView(btn_r1);
// 将Button2 加入到RelativeLayout 中
Button btn_r2 = new Button(this);
btn_r2.setText("确定");//设置显示的字符
btn_r2.setId(25);
relative.addView(btn_r2);
// 设置RelativeLayout布局的宽高
RelativeLayout.LayoutParams lp=new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
lp.addRule(RelativeLayout.ALIGN_PARENT_LEFT, RelativeLayout.TRUE);
lp.addRule(RelativeLayout.ALIGN_PARENT_TOP, RelativeLayout.TRUE);
btn_r1.setLayoutParams(lp); ////设置按钮的布局属性
lp=new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
lp.addRule(RelativeLayout.RIGHT_OF, btn_r1.getId());
btn_r2.setLayoutParams(lp); ////设置按钮的布局属性
setContentView(relative);
}
}
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有