0

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のアプローチの違いを引き起こしている可能性のあるアイデアを誰かが持っていますか?

4

1 に答える 1

-2

これがあなたの問題だと思います:

LinearLayout wrappedButton = (LinearLayout)getLayoutInflater().inflate(R.layout.dialog_button_wrapped, null);

nullは親ビューに置き換えて、設定したいlayoutParamsを取得できるようにする必要があります。

もう1つは、設定したウェイトについてです。ウェイトによってレイアウトプロセスが奇妙で非効率的に機能しないように、幅/高さを0pxに設定する必要があります。

ところで、(ボタンがある)内部レイアウトを削除して、代わりに単一のボタンを使用することができます。そこでlayout_gravityをcenter_horizo​​ntalに設定するだけです。

于 2013-02-01T00:20:39.963 に答える