代码中进行RelativeLayout布局的修改添加

本文介绍了在Android中如何使用Java代码动态地添加和修改RelativeLayout布局。通过获取RelativeLayout对象,加载布局文件,创建并设置View,以及调整布局属性,实现界面的动态更新。示例代码展示了添加和删除视图的过程。
摘要由CSDN通过智能技术生成

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);


写的比较简单,权当笔记了。欢迎大家指出不足和错误。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值