安卓RelativeLayout编程方式设置"centerInParent"
-
10-10-2019 - |
题
我有一个 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"
我怎么能让这种通过程序?
解决方案
完全未经测试,但是 应该 工作:
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"
在您的清单中的活动中
其他提示
只是为了添加鲁本响应中的另一种风味,我以这样的方式使用它来添加或删除此规则:
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);
}
我已经做了
1.centerInParent
2.centerHorizontal
3.centerVertical
与 真的 和 假.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-真的
addOrRemoveProperty(mView, RelativeLayout.CENTER_IN_PARENT, true);
centerInParent-假的
addOrRemoveProperty(mView, RelativeLayout.CENTER_IN_PARENT, false);
centerHorizontal-真的
addOrRemoveProperty(mView, RelativeLayout.CENTER_HORIZONTAL, true);
centerHorizontal-假的
addOrRemoveProperty(mView, RelativeLayout.CENTER_HORIZONTAL, false);
centerVertical-真的
addOrRemoveProperty(mView, RelativeLayout.CENTER_VERTICAL, true);
centerVertical-假的
addOrRemoveProperty(mView, RelativeLayout.CENTER_VERTICAL, false);
希望这会帮助你。
不隶属于 StackOverflow