2017-02-14 3 views
1

私はGridLayoutビューを持っていますが、これには動的にいくつかのImageButtonを追加しています。私はImageButtonが正しくレイアウトされている理由を理解しようとしていますが、ImageButtonをレイアウトxmlファイルから膨張させると、ImageButtonのコンストラクタを直接使用してイメージを作成していません。ImageButtonは動的に作成されたときに別の方法で表示されます

のGridLayoutとImageButtonsが以前に同じレイアウトで定義された両方の(予想通りとレンダリング).xmlファイル:

<ScrollView 
    style="@style/my_list_style" 
    android:layout_height="wrap_content"> 

    <LinearLayout 
     android:layout_width="match_parent" 
     android:layout_height="match_parent" 
     android:orientation="vertical" 
     android:padding="12dp"> 

     <GridLayout 
      android:id="@+id/my_list" 
      android:layout_width="match_parent" 
      android:layout_height="wrap_content" 
      android:layout_gravity="center"> 

      <!-- These ImageButtons are being converted to dynamic. --> 
      <ImageButton 
       style="@style/my_button_style" 
       android:src="@drawable/image1" /> 

      <ImageButton 
       style="@style/my_button_style" 
       android:src="@drawable/image2" /> 

     </GridLayout> 
    </LinearLayout> 
</ScrollView> 

動的にImageButtonsを変換するために、私は、最初のレイアウトファイルからそれらを除去し、使用します実行時に次のようなコードを追加してください。

ImageButton imageButton = new ImageButton(context, null, R.style.my_button_style); 
imageButton.setImageResource(R.drawable.image1); 
parent.addView(imageButton); 

ボタンは正しく表示されませんでした。それらは中心合わせされておらず、それらのサイズは正しい/均一ではないように見える。

私は、その後のImageButtonとそのスタイルだけを含んでいない、新しいレイアウトファイルを作成しようとした

<ImageButton 
    style="@style/my_button_style"/> 

私は、実行時のGridViewにこのレイアウトを膨らませる、すべてが期待通りになります。

LayoutInflater inflater = LayoutInflater.from(context); 
ImageButton imageButton = (ImageButton) inflater.inflate(
    R.layout.my_button_layout, parent, false); 
imageButton.setImageResource(R.drawable.image1); 
parent.addView(imageButton); 

LayoutInflatorでビューを拡大すると、コンストラクタから直接ボタンを作成するのとは異なる結果になるのはなぜですか?

答えて

1

手動でImageButtonを作成すると、その親を指定しないため、親のレイアウトパラメータがわからず、期待通りにレイアウトできないためです。

一方、LayoutInflaterで膨らませた場合は、parentと指定しています。その後、正しいレイアウトパラメータが子に渡されます。そういうわけで、違いが見えます。

Dave Smithによるdetailed articleをご覧ください。

+0

私が 'addView'を呼んだとき、親のLayoutParamsがフレームワークによって推論できないことは私には明らかでした。どうやら、これはViewインスタンシエーション時に発生しているに違いない。リンクありがとう。 –

関連する問題