Android RelativeLayout をプログラムで「centerInParent」に設定する 質問する

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"

これをプログラム的に作るにはどうすればいいでしょうか?

ベストアンサー1

完全にテストされていないが、これはすべき仕事:

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"マニフェスト内のアクティビティ内に追加する

おすすめ記事