我有一个像这样的 RelativeLayout :
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dip">
<Button
android:id="@+id/negativeButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20dip"
android:textColor="#ffffff"
android:layout_alignParentLeft="true"
android:background="@drawable/black_menu_button"
android:layout_marginLeft="5dip"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"/>
<Button
android:id="@+id/positiveButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20dip"
android:textColor="#ffffff"
android:layout_alignParentRight="true"
android:background="@drawable/blue_menu_button"
android:layout_marginRight="5dip"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"/>
</RelativeLayout>
我希望能够以positiveButton
编程设置与以下相同的效果:
android:layout_centerInParent="true"
如何以编程方式进行此操作?
答案 0 :(得分:371)
完全未经测试,但此应工作:
View positiveButton = findViewById(R.id.positiveButton);
RelativeLayout.LayoutParams layoutParams =
(RelativeLayout.LayoutParams)positiveButton.getLayoutParams();
layoutParams.addRule(RelativeLayout.CENTER_IN_PARENT, RelativeLayout.TRUE);
positiveButton.setLayoutParams(layoutParams);
在清单
中的活动中添加android:configChanges="orientation|screenSize"
答案 1 :(得分:12)
只是为了从Reuben响应中添加另一种风格,我会像这样使用它来根据条件添加或删除此规则:
RelativeLayout.LayoutParams layoutParams =
(RelativeLayout.LayoutParams) holder.txtGuestName.getLayoutParams();
if (SOMETHING_THAT_WOULD_LIKE_YOU_TO_CHECK) {
// if true center text:
layoutParams.addRule(RelativeLayout.CENTER_IN_PARENT);
holder.txtGuestName.setLayoutParams(layoutParams);
} else {
// if false remove center:
layoutParams.addRule(RelativeLayout.CENTER_IN_PARENT, 0);
holder.txtGuestName.setLayoutParams(layoutParams);
}
答案 2 :(得分:4)
我已经为
private void addOrRemoveProperty(View view, int property, boolean flag){
RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) view.getLayoutParams();
if(flag){
layoutParams.addRule(property);
}else {
layoutParams.removeRule(property);
}
view.setLayoutParams(layoutParams);
}
如何调用方法:
centerInParent - true
addOrRemoveProperty(mView, RelativeLayout.CENTER_IN_PARENT, true);
centerInParent - false
addOrRemoveProperty(mView, RelativeLayout.CENTER_IN_PARENT, false);
centerHorizontal - true
addOrRemoveProperty(mView, RelativeLayout.CENTER_HORIZONTAL, true);
centerHorizontal - false
addOrRemoveProperty(mView, RelativeLayout.CENTER_HORIZONTAL, false);
centerVertical - true
addOrRemoveProperty(mView, RelativeLayout.CENTER_VERTICAL, true);
centerVertical - false
addOrRemoveProperty(mView, RelativeLayout.CENTER_VERTICAL, false);
希望这会对你有所帮助。