<TextViewandroid: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>然后我们在Activity类里边进行添加组件,代码如下所示:
/*** 代码中,布局的位置,是垂直顺序排列的因为界面代码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 ); }}效果如下图所示:
图 1 动态添加组件-LinearLayout
(2) 动态添加布局:
* 下面的例子将介绍如何动态添加布局,基本内容和上面的代码一致,主要注重如何控制添加的布局的位置
* 在控制布局的位置的时候使用LayoutParam类来实现。
* 注意:控制位置和样式的时候,布局和控件使用的方法是一样的。
*/这次只是在MainActivity中进行操作,不涉及布局文件(.xml),其代码如下所示:
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); }}效果如下所示:
图 2 动态添加布局-RelativeLayout
学会了上面的介绍,你就可以很轻松的布局界面,无论是按钮还是其他组件,对于布局,你也可以很方便的进行布局使用,以上就是在安卓中如何动态添加组件的方法。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。