将视图动态添加到GridLayout时,对齐方式不对

时间:2015-11-20 07:41:48

标签: android android-layout grid-layout android-gridlayout

  

按XML添加按钮时 - 全部好

When adding buttons through XML

  <GridLayout
    android:id="@+id/social_gl_content"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_centerHorizontal="true"
    android:alignmentMode="alignBounds"
    android:columnCount="2"
    android:padding="8dp">

    <LinearLayout
        android:layout_width="0dp"
        android:layout_height="45dp"
        android:layout_columnWeight="1">
        <Button
            android:layout_width="fill_parent"
            android:layout_height="45dp"
            android:background="@android:color/holo_blue_light"
            android:text="Hi"/>
    </LinearLayout>

    <LinearLayout
        android:layout_width="0dp"
        android:layout_height="45dp"
        android:layout_columnWeight="1">
        <Button
            android:layout_width="fill_parent"
            android:layout_height="45dp"
            android:background="@android:color/holo_green_light"
            android:text="Whatsapp"/>
    </LinearLayout>

    <LinearLayout
        android:layout_width="0dp"
        android:layout_height="45dp"
        android:layout_columnWeight="1">
        <Button
            android:layout_width="match_parent"
            android:layout_height="45dp"
            android:background="@android:color/holo_green_light"
            android:text="This is facebook"
            />
    </LinearLayout>

    <LinearLayout
        android:layout_width="0dp"
        android:layout_height="45dp"
        android:layout_columnWeight="1">
        <Button
            android:layout_width="match_parent"
            android:layout_height="45dp"
            android:background="@android:color/holo_blue_light"
            android:text="On"
            />
    </LinearLayout>

</GridLayout>
  

动态添加按钮时(按代码) - 对齐缺失,按钮不占据列的完整宽度

GridLayout gl = (GridLayout) findViewById(R.id.social_gl_content);
    LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
    for (int i = 0 ; i < strs.length ; i++) {
        View v = inflater.inflate(R.layout.grid_item, null);
        Button b = (Button) v.findViewById(R.id.button);
        b.setText(strs[i]);
        if ( i % 2 ==0) {
            b.setBackgroundColor(Color.BLACK);
        }else{
            b.setBackgroundColor(Color.BLUE);
        }
        gl.addView(v);
    }

enter image description here

2 个答案:

答案 0 :(得分:5)

而不是传递null:

View v = inflater.inflate(R.layout.grid_item, null);

传递parentView,以便v具有正确的布局参数。

View v = inflater.inflate(R.layout.grid_item, gl, false);

答案 1 :(得分:1)

试试这个:

LinearLayout.LayoutParams parms = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
b.setLayoutParams(parms);