android addRule() 的作用!

        布局中有很多特殊的属性,通常在载入布局之前,在相关的xml文件中进行静态设置即可。但是,在有些情况下,我们需要动态设置布局的属性,在不同的条件下设置不同布局排列方式,这时候就需要用到 RelativeLayout.LayoutParams.addRule() 方法,该方法有两种重载方式:
  1. addRule(int verb) :用此方法时,所设置节点的属性不能与其它兄弟节点相关联或者属性值为布尔值(布尔值的属性,设置时表示该属性为 true,不设置就默认为 false),比如:addRule(RelativeLayout.CENTER_VERTICAL) 就表示在 RelativeLayout 中的相应节点是垂直居中的。
  2. addRule(int verb, int anchor) :该方法所设置节点的属性必须关联其它的兄弟节点或者属性为布尔值( 属性为布尔值时,anchor 为 RelativeLayout.TRUE 表示 true,anchor 为0表示 false),比如:addRule(RelativeLayout.ALIGN_LEFT, R.id.date) 就表示 RelativeLayout 中的相应节点放置在一个 id 值为 date 的兄弟节点的左边。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Android 中,可以使用 View 的布局参数来实现视图的伸缩效果。常用的布局参数有 LinearLayout.LayoutParams 和 RelativeLayout.LayoutParams。下面介绍两种常见的视图伸缩方式。 1. LinearLayout 中的权重(weight) LinearLayout 中的权重是一种常见的视图伸缩方式。可以通过设置子视图的权重来控制它们在 LinearLayout 中的占比。具体使用方法如下: 1)设置 LinearLayout 的方向为水平或垂直方向。 2)设置子视图的宽度或高度为 0dp。 3)设置子视图的权重(weight),权重越大,占比越大。 示例代码: ``` <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal"> <TextView android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:text="View 1"/> <TextView android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="2" android:text="View 2"/> <TextView android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:text="View 3"/> </LinearLayout> ``` 上述代码中,三个 TextView 的占比分别为 1:2:1,即中间的 TextView 占比最大。 2. RelativeLayout 中的规则属性 RelativeLayout 中常用的视图伸缩方式是通过设置视图之间的相对位置关系来实现。可以使用 RelativeLayout.LayoutParams 中的规则属性来设置视图之间的相对位置关系。具体使用方法如下: 1)设置 RelativeLayout 的布局参数为 RelativeLayout.LayoutParams。 2)通过 addRule() 方法设置视图之间的相对位置关系,比如设置某个视图在另一个视图的下方或右侧等。 示例代码: ``` <RelativeLayout android:layout_width="match_parent" android:layout_height="match_parent"> <TextView android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="View 1"/> <TextView android:id="@+id/textView2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="View 2" android:layout_below="@id/textView1"/> <TextView android:id="@+id/textView3" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="View 3" android:layout_below="@id/textView1" android:layout_toRightOf="@id/textView2"/> </RelativeLayout> ``` 上述代码中,textView2 在 textView1 的下方,textView3 在 textView1 的下方且在 textView2 的右侧。通过设置不同的规则属性,可以实现更复杂的布局效果。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值