Android 4.0でプログラムでUIの一部を構築するときに、間隔の問題が発生します。様式化されたLinearLayoutに様式化されたボタンを追加しようとしています。ボタンの間隔を均等にするために、各ボタンは重み1のLinearLayoutでラップされます。XMLで定義されたレイアウト(概念実証のようなもの)から始めました。これは、期待どおりにレンダリングされます。
<LinearLayout android:id="@+id/dialog_footer"
android:layout_width="500dp"
android:layout_height="wrap_content"
android:background="@drawable/dialog_footer">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:orientation="horizontal"
android:gravity="center">
<Button android:id="@+id/cancel"
style="@style/Button"
android:layout_width="130dp"
android:layout_height="38dp"
android:text="Cancel" />
</LinearLayout>
<!-- Another LinearLayout with a nested Button like the one above -->
</LinearLayout>
プログラムでボタンを追加するために、内側のLinearLayoutを削除し、Javaの外側のLinearLayoutに拡張して追加できる独自のレイアウトファイルに配置しました。ほぼ同じです。
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:orientation="horizontal"
android:gravity="center" >
<Button android:id="@+id/button"
style="@style/Button"
android:layout_width="130dp"
android:layout_height="38dp" />
</LinearLayout>
そして、これは大まかに私がコードにボタンを追加する方法です:
LinearLayout dialogFooter = (LinearLayout)dialogView.findViewById(R.id.dialog_footer);
LinearLayout wrappedButton = (LinearLayout)getLayoutInflater().inflate(R.layout.dialog_button_wrapped, null);
Button button = (Button)wrappedButton.findViewById(R.id.button);
button.setText(R.string.button_one_text);
// button.setOnClickListener(...);
dialogFooter.addView(wrappedButton);
ボタンは表示されますが、グループ化されて左にシフトされます。レイアウトを解析するときにAndroidが行うことで、dialog_footerに追加する場合に自分で行う必要があることはありますか?ここでウェイトが機能するので、追加するコンテナー(dialog_footer)でsetWeightSum()を呼び出す必要があるかもしれないと思いましたが、それは役に立ちませんでした。XMLとJavaのアプローチの違いを引き起こしている可能性のあるアイデアを誰かが持っていますか?