android用java为编程语言,很多地方都很相似,界面这块也很像。我们都知道java画界面是一行一行代码去添加界面的控件的,所以那是一件让人崩溃的事。Android完美解决了这一问题,Android的界面布局是通过xml文件配置的,加上强大的ide画界面就非常方便了。但xml布局局限就是不能动态修改,所以还是需要像java那样在代码中动态添加view。
本人也是新手一个,没有研究全部布局,只简单写点RelativeLayout的动态布局,有错误及不足,欢迎大家评论指出。
首先,需要获得RelativeLayout这个对象,可以在xml中给其id,在onCreate中加载布局后用下面语句获得。
rootView=(RelativeLayout) findViewById(R.id.rootView);
需要添加的view可以代码里new一个,也可以加载布局xml文件,我是使用xml文件定义了一个LinearLayout,代码如下
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >
<Button
android:id="@+id/selectAll"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="全选" />
<Button
android:id="@+id/del_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="删除" />
<Button
android:id="@+id/cancel_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="取消" />
</LinearLayout>
在java代码中加载这个布局文件,代码如下
LayoutInflater inflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
openView=(LinearLayout) inflater.inflate(R.layout.delmenu_layout, null);
添加到RelativeLayout前还需要设置这个添加进去的view的布局属性,需要用到LayoutParams类,但这个类针对不同布局,需要引入不同的布局类下的这个类,本例中是在RelativLayout中,就需要RelativeLayout.LayoutParams,建议都这样写,不要只写LayoutParams,有多种布局绝对会晕死。
RelativeLayout.LayoutParams lp=new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT,RelativeLayout.LayoutParams.WRAP_CONTENT);//两个参数分别是layout_width,layout_height
lp.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);//这个就是添加其他属性的,这个是在父元素的底部。
addRule方法还有个两个参数的,用于RelativeLayout中相对于某个控件的属性,如android:layout_alignBottom="@+id/listView1"
可以写成
lp.addRule(RelativeLayout.ALIGN_BOTTOM,R.id.listView1);
两者效果一样,后面那个参数也可以是RelativeLayout.TRUE(-1)和0,如android:layout_alignParentBottom="true"
lp.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM,RelativeLayout.TRUE);
最后,添加新的view到RelativeLayout中,
rootView.addView(openView,lp);
补一个删除的方法
rootView.removeView(menuView);
写的比较简单,权当笔记了。欢迎大家指出不足和错误。