2

Android が ImageButton のレイアウト パラメータを無視しているようです。私のレイアウト xml がスタイルで ImageButtons を定義するとき、layout_weight が考慮されます。ただし、ボタンを動的に追加すると、重みが無視され、LayoutParameters を手動で定義する必要があります。

Styles.xml エントリ:

<style name="TabbedPanelToolbarControl" parent="android:style/Widget.ImageButton">
    <item name="android:background">@null</item>
    <item name="android:layout_width">wrap_content</item>
    <item name="android:layout_height">wrap_content</item>
    <item name="android:layout_weight">1.0</item>
    <item name="android:paddingTop">5dp</item>
    <item name="android:paddingBottom">5dp</item>
</style>

レイアウト xml:

...
<LinearLayout
    android:id="@+id/toolbar"
    android:orientation="vertical" >
    <!-- image buttons go here -->
</LinearLayout>
...

コード:

View view = inflater.inflate(R.layout.test, container, false);
LinearLayout mToolbar = (LinearLayout)view.findViewById(R.id.toolbar);

ImageButton ib = new ImageButton(this.getActivity(), null, R.style.TabbedPanelToolbarControl);

ib.setImageDrawable(icon);
ib.setContentDescription(title);

// ignored layout_weight defined in TabbedPanelToolbarControl style
mToolbar.addView(ib);
// need to re-specify layout
mToolbar.addView(ib, new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, 1.0f));

ボタンを動的に追加するときに、styles.xml から layout_weight を強制的に読み取る方法を知っている人はいますか?

4

2 に答える 2

4

コンストラクターでのレイアウト パラメーターの読み取りは機能しません。その理由は非常に論理的です。ImageButton

new ImageButton(this.getActivity(), null, R.style.TabbedPanelToolbarControl);

このコンストラクターは、スタイル属性を読み取ります。ただし、LinearLayout(または他の親)内にないため、どのLayoutParamsクラスをインスタンス化する必要があるかわかりません。ジェネリックには属性ViewGroup.LayoutParamsがないため、weight無視されます。

膨らませるときLayoutInflaterは状況がかなり異なります。LayoutInflaterクラスの関連コードは次のとおりです。

final View view = createViewFromTag(parent, name, attrs);
final ViewGroup viewGroup = (ViewGroup) parent;
final ViewGroup.LayoutParams params = viewGroup.generateLayoutParams(attrs);

viewGroup変数は完全に作成されたであるため、 と の両方を読み取るLinearLayoutオーバーライドがあります。generateLayoutParams()weightgravity

于 2014-06-13T21:42:16.440 に答える
2

スタイルからレイアウト パラメータを取得ImageButtonし、これらのパラメータを使用して追加できます。

    ...
    TypedArray a = obtainStyledAttributes(R.style.TabbedPanelToolbarControl, 
            new int[] {android.R.attr.layout_width,
            android.R.attr.layout_height,
            android.R.attr.layout_weight});


    int width = a.getInt(0, LayoutParams.WRAP_CONTENT);
    int height = a.getInt(1, LayoutParams.WRAP_CONTENT);
    float weight = a.getFloat(2, 1);

    mToolbar.addView(ib, new LayoutParams(width, height, weight));
于 2014-06-13T23:07:07.007 に答える