动态设置Relative Layout中按钮的layout_align_parent_right属性

你可以使用View.getLayoutParams从代码中访问 LayoutParams。你只需要知道你访问的什么LayoutParams。这通常是通过检查包含的ViewGroup就能知道。如果它有一个LayoutParams子类,那你就应该使用这个LayoutParams类。
在你的案例中它是RelativeLayout.LayoutParams,你应该使用RelativeLayout.LayoutParams#addRule(int verb)RelativeLayout.LayoutParams#addRule(int verb, int anchor)
你可以通过以下代码获得:

RelativeLayout.Layoutparams params = (RelativeLayout.LayoutParams)button.getLayoutParams();
params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
params.addRule(RelativeLayout.LEFT_OF, R.id.id_to_be_left_of);

button.setLayoutParams(params); //使layout更新
好的,下面是使用相对布局实现最左边一个图片,图片右边围绕着两个TextView,最右边一个按钮代码: ``` <RelativeLayout android:layout_width="match_parent" android:layout_height="wrap_content"> <!-- 最左边的图片 --> <ImageView android:id="@+id/image_left" android:layout_width="wrap_content" android:layout_height="match_parent" android:src="@drawable/image_left" android:scaleType="fitCenter"/> <!-- 右边的两个TextView --> <TextView android:id="@+id/textview1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Textview 1" android:layout_toRightOf="@id/image_left" android:layout_alignTop="@id/image_left" android:layout_marginLeft="16dp"/> <TextView android:id="@+id/textview2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Textview 2" android:layout_toRightOf="@id/image_left" android:layout_below="@id/textview1" android:layout_marginLeft="16dp" android:layout_marginTop="8dp"/> <!-- 最右边的按钮 --> <Button android:id="@+id/button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Button" android:layout_alignParentRight="true" android:layout_centerVertical="true" android:layout_marginRight="16dp"/> </RelativeLayout> ``` 在这个布局,我们首先使用相对布局,将最左边的图片放在最下面,并为它设置一个id。然后,我们将右边的两个TextView分别放在图片的右边,并使用 `android:layout_toRightOf` 和 `android:layout_below` 属性来确定它们的位置关系。最后,我们将最右边的按钮放在布局的右边,并使用 `android:layout_alignParentRight` 和 `android:layout_centerVertical` 属性来确定它在布局的位置。这样,我们就用相对布局实现了这个布局,保证了各个控件之间的位置关系。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值