Android RelativeLayout 通过编程设置“ centerInParent”

我的 相对布局是这样的:

<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"

如何通过编程方式实现这一点?

134896 次浏览

完全未经测试,但这个 应该工作:

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"

为了从 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. 中心水平

3. 中央垂直

没错假的

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

如何调用方法:

真实

addOrRemoveProperty(mView, RelativeLayout.CENTER_IN_PARENT, true);

错误

addOrRemoveProperty(mView, RelativeLayout.CENTER_IN_PARENT, false);

水平-真

addOrRemoveProperty(mView, RelativeLayout.CENTER_HORIZONTAL, true);

水平-假

addOrRemoveProperty(mView, RelativeLayout.CENTER_HORIZONTAL, false);

垂直-真

addOrRemoveProperty(mView, RelativeLayout.CENTER_VERTICAL, true);

中心垂直-虚假

addOrRemoveProperty(mView, RelativeLayout.CENTER_VERTICAL, false);

希望这个能帮到你。