GridLayout (GridView 아님) 모든 자식을 균등하게 늘리는 방법


217

안에 버튼이있는 2x2 그리드를 갖고 싶습니다. 이것은 ICS이므로 주어진 새로운 GridLayout을 사용하려고합니다.

내 레이아웃의 XML은 다음과 같습니다.

 <?xml version="1.0" encoding="utf-8"?>
<GridLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/favorites_grid"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#00ff00"
    android:rowCount="2"
    android:columnCount="2">
  <Button
      android:text="Cell 0"
      android:layout_row="0"
      android:layout_column="0"
      android:textSize="14dip" />
  <Button
      android:text="Cell 1"
      android:layout_row="0"
      android:layout_column="1"
      android:textSize="14dip" />

  <Button
      android:text="Cell 2"
      android:layout_row="1"
      android:layout_column="0"
      android:textSize="14dip" />
  <Button
      android:text="Cell 3"
      android:layout_row="1"
      android:layout_column="1"
      android:textSize="14dip" />
</GridLayout>

문제는 내 견해가 각 행마다 고르게 늘어나지 않는다는 것입니다. 이로 인해 GridLayout 오른쪽에 추가 공간이 많이 생깁니다.

설정을 시도 layout_gravity="fill_horizontal"했지만 행 의 마지막 보기 에만 적용됩니다 . 이것은 셀 1이 셀 0에 충분한 공간을 제공하기 위해 완전히 늘어나는 것을 의미합니다.

이 문제를 해결하는 방법에 대한 생각?


이러한 Button 요소에 특정 layout_width 및 layout_height 크기를 설정하지 않은 이유는 무엇입니까?
— IgorGanapolsky

귀하의 경우에 TableLayout을 사용하지 않으시겠습니까?
— weaknespase 2018 년

1
Lollipop에서는 이제 android.support.v7.widget.GridLayout (열 수 3)을 사용하고 각 열당 <TextView> <Space app : layout_columnWeight = "1"/> <TextView>를 사용하여 원하는 것을 달성 할 수 있습니다. SDK 21 전용으로 빌드하지 않고 일반적인 GradLayout
— AllDayAmazing

답변:


77

업데이트 : 가중치는 API 21부터 지원됩니다. 자세한 내용은 PaulT의 답변 을 참조하십시오. 업데이트 종료 GridLayout 사용시 제한 사항이 있습니다. 다음 인용문은 문서 에서 가져 왔습니다 .

"GridLayout은 무게로 정의 된 무게의 원리에 대한 지원을 제공하지 않습니다. 일반적으로 GridLayout을 구성하여 여러 행이나 열 사이에 공간을 사소한 비율로 분배 할 수는 없습니다. 행이나 열에 공간이 과도하게 분포되어 있으면 LinearLayout 하위보기를 사용하여 연관된 셀 그룹의 구성 요소를 보유하십시오. "

다음은 LinearLayout 서브 뷰를 사용하는 작은 예입니다. (사용하지 않은 영역을 차지하고 버튼을 원하는 위치로 밀는 공간 뷰를 사용했습니다.)

<GridLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:columnCount="1"
>
    <TextView
        android:text="2x2 button grid"
        android:textSize="32dip"
        android:layout_gravity="center_horizontal" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content" android:orientation="horizontal">
        <Space
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_weight="1" />
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Button 1" />
        <Space
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_weight="1" />
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="start"
            android:text="Button 2" />
        <Space
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_weight="1" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
    >
        <Space
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_weight="1" />
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Button 3" />
        <Space
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_weight="1" />
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="start"
            android:text="Button 4" />
        <Space
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_weight="1" />
    </LinearLayout>
</GridLayout>

117
열이 1 인이 GridLayout은 세로 방향으로 거의 LinearLayout입니다. 레이아웃이 더 복잡해집니다. GridLayout은 중첩 레이아웃을 단순화하고 제거해야합니다.
— Myo Htet를 승리

17
방법을 찾았습니다! android : layout_gravity = "fill_horizontal". 당신이 지원 라이브러리를 사용하는 경우, 다음 그리드로 변경 : layout_gravity = "fill_horizontal을"
— zubietaroberto

6
Win Myo Htet에 동의합니다. 이것은 안드로이드가 제안하는 답변 인 것 같지만 LinearLayout보다 개선 된 방법을 보지 못했습니다. GridLayout의 이유는 중첩 된 LinearLayouts를 피하는 것이라고 생각 했습니까? 이제 GridLayout의 유스 케이스를 볼 수 없습니다.
— Mitch 2013

4
API 21부터 가중치가 지원됩니다
— siyb

7
지원 라이브러리 GridLayout과의 버전은 무게를 지원하고 API 7에 호환됩니다 developer.android.com/reference/android/support/v7/widget/...
— 야곱 타박을

311

API 21부터 가중치 개념이 GridLayout에 추가되었습니다. 구형 Android 장치를 지원하기 위해 v7 지원 라이브러리에서 GridLayout을 사용할 수 있습니다.

다음 XML은 가중치를 사용하여 화면 너비를 채우는 방법의 예를 제공합니다.

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.GridLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:grid="http://schemas.android.com/apk/res-auto"

    android:id="@+id/choice_grid"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_centerHorizontal="true"
    android:padding="4dp"

    grid:alignmentMode="alignBounds"
    grid:columnCount="2"
    grid:rowOrderPreserved="false"
    grid:useDefaultMargins="true">

    <TextView
        android:layout_width="0dp"
        android:layout_height="100dp"
        grid:layout_columnWeight="1"
        grid:layout_gravity="fill_horizontal"
        android:gravity="center"
        android:background="#FF33B5E5"
        android:text="Tile1" />

    <TextView
        android:layout_width="0dp"
        android:layout_height="100dp"
        grid:layout_columnWeight="1"
        grid:layout_gravity="fill_horizontal"
        android:gravity="center"
        android:background="#FF33B5E5"
        android:text="Tile2" />

    <TextView
        android:layout_width="0dp"
        android:layout_height="100dp"
        grid:layout_columnWeight="1"
        grid:layout_gravity="fill_horizontal"
        android:gravity="center"
        android:background="#FF33B5E5"
        android:text="Tile3" />

    <TextView
        android:layout_width="0dp"
        android:layout_height="100dp"
        grid:layout_columnWeight="1"
        grid:layout_gravity="fill_horizontal"
        android:gravity="center"
        android:background="#FF33B5E5"
        android:text="Tile4" />

</android.support.v7.widget.GridLayout>

21
이 답변은 더 높아야합니다.
— SD

5
세로와 가로를 동시에 채우는 데 사용할 수 있습니까? 균등하게 확장 된 3x3 레이아웃을 원하지만 두 가중치를 모두 시도해도 효과가 없습니다.
— Eduardo Naveda

내 특별한 경우 는 키패드의 일부로 ImageView FrameLayout가 포함 된 Button and an 이미지 를 사용해야했습니다 (버튼에 아이콘을 겹쳐서 시각적으로 피드백을 보여주었습니다 ...). 설정 columnWeight과 gravity다른 모든 Button것들은 잘 작동했지만 FrameLayout. 그것을 위해 그것을 그대로두면 FrameLayout모든 것이 예상대로 균등하게 배치됩니다.
— psyren89


1
안녕하세요, 재미있는 답변이지만 팽창 된 어린이를 위해 프로그래밍 방식으로 grid : layout_columnWeight = "1"을 추가하는 방법은 무엇입니까?
— Waza_Be

78

여기에 이미지 설명을 입력하십시오

Appcompat21 GridLayout에는 열과 행 가중치가 있으며 위와 같이 그리드 레이아웃에서 각 그리드 항목을 고르게 생성하기 위해 아래와 같이 사용할 수 있습니다.

<android.support.v7.widget.GridLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:grid="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_centerHorizontal="true"
grid:alignmentMode="alignBounds"
grid:columnCount="4">
<Button android:layout_width="0dp"
    style="?buttonStyle"
    android:layout_height="0dp"
    android:text="-1"
    grid:layout_columnWeight="1"
    grid:layout_rowWeight="1"
    grid:layout_gravity="fill"/>
...
...
...


열이 두 개 뿐인 경우 자녀의 견해를 중앙에 어떻게 배치합니까?
— Muhammad Babar

17
compile "com.android.support:gridlayout-v7:$supportVersion"
— Miha_x64

필자의 경우에는 컴파일 지시문을 추가 한 후 그리드 속성 (예 app:columnCount="2"xmlns:app="http://schemas.android.com/apk/lib/android.support.v7.widget.GridLayout"
— Gene Bo

42

ScrollView를 사용하여 v7 지원 라이브러리없이 API 21에서 시작 :

여기에 이미지 설명을 입력하십시오

XML :

<?xml version="1.0" encoding="utf-8"?>
<ScrollView
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    >

    <GridLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:columnCount="2"
            >

        <TextView
            android:layout_width="0dp"
            android:layout_height="100dp"
            android:layout_columnWeight="1"
            android:gravity="center"
            android:layout_gravity="fill_horizontal"
            android:background="@color/colorAccent"
            android:text="Tile1" />

        <TextView
            android:layout_width="0dp"
            android:layout_height="100dp"
            android:layout_columnWeight="1"
            android:gravity="center"
            android:layout_gravity="fill_horizontal"
            android:background="@color/colorPrimaryDark"
            android:text="Tile2" />

        <TextView
            android:layout_width="0dp"
            android:layout_height="100dp"
            android:layout_columnWeight="1"
            android:gravity="center"
            android:layout_gravity="fill_horizontal"
            android:background="@color/colorPrimary"
            android:text="Tile3" />

        <TextView
            android:layout_width="0dp"
            android:layout_height="100dp"
            android:layout_columnWeight="1"
            android:gravity="center"
            android:layout_gravity="fill_horizontal"
            android:background="@color/colorAccent"
            android:text="Tile4" />

    </GridLayout>
</ScrollView>

나는 이것을 사용하고 있습니다. 감사합니다!
— Raj Bedi

35

모든 어린이의 너비를 동적으로 설정할 수 있습니다.

GridLayout.LayoutParams params = (GridLayout.LayoutParams) child.getLayoutParams();
    params.width = (parent.getWidth()/parent.getColumnCount()) -params.rightMargin - params.leftMargin;
    child.setLayoutParams(params);

3
때 줄을 나눌 것 useDefaultMargins="true"-로 설정 그들과 함께 완벽하게 작동false
— 리처드 르 Mesurier

16

GridLayout 사양에 다음을 추가하십시오. 작동합니다.

android:useDefaultMargins="true"

그리고 그걸로 다시 GridLayout이라고 부를 수 있습니다!
— clwhisk

하지만 실제로는 그렇지 않습니다.
— m0skit0

15

이것이 정답입니다

<?xml version="1.0" encoding="utf-8"?>
<GridLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/favorites_grid"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#00ff00"
    android:rowCount="2"
    android:columnCount="2">
    <Button
        android:text="Cell 0"
        android:layout_row="0"
        android:layout_column="0"
        android:layout_columnWeight="1"
        android:layout_rowWeight="1"
        android:textSize="14dip" 
        />
    <Button
        android:text="Cell 1"
        android:layout_row="0"
        android:layout_column="1"
        android:textSize="14dip"
        android:layout_columnWeight="1"
        android:layout_rowWeight="1"/>

    <Button
        android:text="Cell 2"
        android:layout_row="1"
        android:layout_column="0"
        android:textSize="14dip"
        android:layout_columnWeight="1"
        android:layout_rowWeight="1"/>
    <Button
        android:text="Cell 3"
        android:layout_row="1"
        android:layout_column="1"
        android:textSize="14dip"
        android:layout_columnWeight="1"
        android:layout_rowWeight="1"/>
</GridLayout>

너무 늦게 댓글을 작성해주세요. 답변에 약간의 설명을 추가해주세요.
— vatbub

1
속성 layout_columnWeight는 API 레벨 21 이상에서만 사용됩니다
— Vikash Parajuli

7

마침내 해결책을 찾았습니다. Rotemmiz가 말했듯이 나중에 동적으로 수행해야합니다. 이 코드는 버튼을 확장하여 뷰를 가로로 채우지 만 세로로 동일하게 수행 할 수 있습니다.

public void fillview(android.support.v7.widget.GridLayout gl)
{
    Button buttontemp;

    //Stretch buttons
    int idealChildWidth = (int) ((gl.getWidth()-20*gl.getColumnCount())/gl.getColumnCount());
    for( int i=0; i< gl.getChildCount();i++)
    {
        buttontemp = (Button) gl.getChildAt(i);
        buttontemp.setWidth(idealChildWidth);
    }
}

(20은 내부 및 외부 패딩 및 여백 용입니다.보다 보편적으로 수행 할 수 있지만 훨씬 깨끗합니다)

그러면 다음과 같이 호출 될 수 있습니다.

    android.support.v7.widget.GridLayout gl = (android.support.v7.widget.GridLayout)findViewById(R.id.buttongrid);
    ViewTreeObserver vto = gl.getViewTreeObserver();
    vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {@Override public void onGlobalLayout() 
    {

            android.support.v7.widget.GridLayout gl = (android.support.v7.widget.GridLayout) findViewById(R.id.buttongrid);
            fillview(gl);

            ViewTreeObserver obs = gl.getViewTreeObserver();
            obs.removeGlobalOnLayoutListener(this);
    }});

뷰를 호출하기 전에 뷰가 그려 질 때까지 기다려야하므로 관찰자와 함께 수행해야합니다.


7

필자의 경우 버튼을 동적으로 추가하여 솔루션에 XML 부분과 Java 부분이 필요했습니다. 몇 곳에서 솔루션을 찾아서 혼합해야했으며 비슷한 솔루션을 찾는 다른 사람이 도움이 될 수 있도록 여기에서 공유 할 것이라고 생각했습니다.

레이아웃 파일 XML의 첫 부분 ...

<android.support.v7.widget.GridLayout
    xmlns:grid="http://schemas.android.com/apk/res-auto"
    android:id="@+id/gl_Options"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    grid:useDefaultMargins="true">
</android.support.v7.widget.GridLayout>

grid:useDefaultMargins="true"필요하지는 않지만 나에게 더 좋게 보이기 때문에 추가했습니다. 여기서 답변에 언급 된 것처럼 다른 시각적 영향 (예 : 패딩)을 적용 할 수 있습니다. 이제 버튼을 동적으로 추가해야합니다. 이 버튼을 만드는 코드의 Java 부분은 다음과 같습니다.이 컨텍스트와 관련된 행만 포함합니다. myOptions내 코드에서 사용할 수있는 많은 버튼을 만들어야한다고 가정 하고 OnClickListener 코드도 복사하지 않습니다.

import android.support.v7.widget.GridLayout;   //Reference to Library

public class myFragment extends Fragment{
    GridLayout gl_Options;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        gl_AmountOptions = (GridLayout)view.findViewById( R.id.gl_AmountOptions );
        ...
        gl_Options.removeAllViews();     // Remove all existing views
        gl_AmountOptions.setColumnCount( myOptions.length <= 9 ? 3: 4 );  // Set appropriate number of columns

        for( String opt : myOptions ) {
            GridLayout.LayoutParams lParams   = new GridLayout.LayoutParams( GridLayout.spec( GridLayout.UNDEFINED, 1f), GridLayout.spec( GridLayout.UNDEFINED, 1f));
            // The above defines LayoutParameters as not specified Column and Row with grid:layout_columnWeight="1" and grid:layout_rowWeight="1"
            lParams.width = 0;    // Setting width to "0dp" so weight is applied instead

            Button b = new Button(this.getContext());
            b.setText( opt );
            b.setLayoutParams(lParams);
            b.setOnClickListener( myClickListener );
            gl_Options.addView( b );
        }
    }
}

표준 GridLayout이 아닌 지원 라이브러리에서 GridLayout을 사용하고 있으므로 YourProject.grade파일 에서 그 등급을 알려야 합니다.

dependencies {
    compile 'com.android.support:appcompat-v7:23.4.0'
    ...
    compile 'com.android.support:gridlayout-v7:23.4.0'
}

GridLayout.spec (GridLayout.UNDEFINED, 1f)이있는 GridLayout.LayoutParams는 grid : useDefaultMargins가 false 인 경우에만 훌륭하게 작동했습니다. 또한 lParams.width = 0은 LayoutParams에 의해 너비와 높이가 설정되어 있기 때문에 사용하지 않는 것 같습니다.
— ichalos

4

ViewGroup onLayout 메서드를 재정 의하여이 작업을 더 빠르게 수행 할 수 있습니다. 이것이 내 보편적 인 해결책입니다.

package your.app.package;

import android.content.Context;
import android.view.ViewGroup;

public class GridLayout extends ViewGroup {

    public GridLayout(Context context) {
        super(context);
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        final int columns = 2;//edit this if you need different grid
        final int rows = 2;

        int children = getChildCount();
        if (children != columns * rows)
            throw new IllegalStateException("GridLayout must have " + columns * rows + " children");

        int width = getWidth();
        int height = getHeight();


        int viewWidth = width / columns;
        int viewHeight = height / rows;

        int rowIndex = 0;
        int columnIndex = 0;

        for (int i = 0; i < children; i++) {
            getChildAt(i).layout(viewWidth * columnIndex, viewHeight * rowIndex, viewWidth * columnIndex + viewWidth, viewHeight * rowIndex + viewHeight);
            columnIndex++;
            if (columnIndex == columns) {
                columnIndex = 0;
                rowIndex++;
            }
        }
    }

}

편집 : 어린이를위한 match_parent를 잊지 마십시오!

android:layout_width="match_parent"
android:layout_height="match_parent"

좋을 수는 있지만 어린이 패딩 및 여백에 대한 지원이 필요합니다
— Pascal

1
자식 패딩은 자식에 속성이 설정되어 있기 때문에 지원됩니다. 여백 지원을 추가하려면 다음과 같이 "layout"기능을 사용하여 행을 수정하십시오 (여백 변수는 여백입니다 (픽셀 단위)).getChildAt(i).layout(viewWidth * columnIndex + margin, viewHeight * rowIndex + margin, viewWidth * columnIndex + viewWidth - margin, viewHeight * rowIndex + viewHeight - margin);
— user1557434

3

내가 찾을 수있는 가장 좋은 해결책은 원하는 각 행에 선형 레이아웃 (수평)을 사용하고 버튼 (셀) 너비를 0dp에 가중치를 1에 할당하는 것입니다. 각 선형 레이아웃 (행)에 대해 높이를 지정하십시오 아래 코드를 찾으십시오. 또한 android : layout_gravity = "center_vertical"은 가변 길이 텍스트를 포함하는 경우 버튼을 행에 정렬하는 데 사용됩니다. 0dp를 사용하고 꽤 깔끔하지만 아직 잘 알려진 트릭은 없습니다.

<LinearLayout
 android:id="@+id/parent_layout"
 android:layout_width="match_parent"
 android:layout_height="wrap_content"
 android:background="@drawable/button_bue_3d"
 android:orientation="vertical" >

            <LinearLayout
                android:id="@+id/layout_row1"
                android:layout_width="match_parent"
                android:layout_height="0dp"
                android:layout_weight="1"

                android:orientation="horizontal" >

                <Button
                    android:id="@+id/button1"
                    style="?android:attr/buttonStyleSmall"
                   android:layout_height="wrap_content"
                   android:layout_width="0dp"
                   android:layout_weight="1"
                    android:clickable="false"
                   android:layout_gravity="center_vertical"
                    android:text="ssssssssssssssssssssssssss" />

                <Button
                    android:id="@+id/button2"
                    style="?android:attr/buttonStyleSmall"
                    android:clickable="false"
                    android:layout_height="wrap_content"
                     android:layout_width="0dp"
                   android:layout_weight="1"
                   android:layout_gravity="center_vertical"
                    android:text="sggggggg" />


            </LinearLayout>

            <LinearLayout
                android:id="@+id/layout_row2"
                android:layout_weight="1"
                android:layout_width="match_parent"
                  android:layout_height="0dp"

                android:orientation="horizontal" >

                <Button
                    android:id="@+id/button3"
                    style="?android:attr/buttonStyleSmall"
                    android:layout_height="wrap_content"
                     android:layout_width="0dp"
                   android:layout_weight="1"
                    android:layout_gravity="center_vertical"
                    android:text="s" />

                <Button
                    android:id="@+id/button4"
                    style="?android:attr/buttonStyleSmall"
                    android:layout_height="wrap_content"
                     android:layout_width="0dp"
                   android:layout_weight="1"
                    android:clickable="false"
                     android:layout_gravity="center_vertical"
                    android:text="s" />


            </LinearLayout>


       </LinearLayout>

3

여기 있어요 :

Button button = new Button(this);
// weight = 1f , gravity = GridLayout.FILL 
GridLayout.LayoutParams param= new GridLayout.LayoutParams(GridLayout.spec(
            GridLayout.UNDEFINED,GridLayout.FILL,1f),
            GridLayout.spec(GridLayout.UNDEFINED,GridLayout.FILL,1f));
// Layout_height = 0 ,Layout_weight = 0
params.height =0;                                                                                                           
params.width = 0;
button.setLayoutParams(param);

1

레이블이 오른쪽으로 정렬되고 값이 왼쪽으로 정렬 된 중앙 테이블을 원했습니다. 여분의 공간이 테이블 주위에 있어야합니다. 많은 실험을하고 문서가해야한다고 말한 것을 따르지 않은 후 나는 효과가있는 것을 생각해 냈습니다. 내가 한 일은 다음과 같습니다.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:orientation="vertical" >

<GridLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:columnCount="2"
    android:orientation="horizontal"
    android:useDefaultMargins="true" >

    <TextView
        android:layout_gravity="right"
        android:text="Short label:" />

    <TextView
        android:id="@+id/start_time"
        android:layout_gravity="left"
        android:text="Long extended value" />

    <TextView
        android:layout_gravity="right"
        android:text="A very long extended label:" />

    <TextView
        android:id="@+id/elapsed_time"
        android:layout_gravity="left"
        android:text="Short value" />
</GridLayout>

이것은 작동하는 것 같지만 GridLayout은 다음 메시지를 보여줍니다.

"이 GridLayout 레이아웃 또는 LinearLayout 부모는 쓸모가 없습니다"

그것이 나를 위해 일할 때 왜 "무용 지"인지 확실하지 않습니다.

왜 이것이 효과가 있는지 또는 이것이 좋은 아이디어인지 확실하지 않지만 시도해보고 더 나은 아이디어를 제공하거나 작은 개선을 제공하거나 그것이 왜 효과가 있는지 (또는 효과가 없는지) 설명 할 수 있다면 의견을 보내 주셔서 감사합니다.

감사.


이것은 레이아웃 편집기에서는 좋아 보이지만 실행할 때 실패합니다. :-(
— Mitch 2013

2
"부모는 쓸모가 없습니다"라는 메시지는 wrap_content 안에 wrap_content가 있고 내가 볼 수있는 한 유일한 요소이기 때문입니다.
— 벤 윌킨슨

1

이것은 상당히 오래된 질문이지만 분명히 많은 사람들에게 관심이 있습니다. 이와 같은 4 개의 버튼을 간단하게 배치하려면 TableLayout이 원하는 결과를 얻는 가장 쉬운 방법 인 것 같습니다.

다음은 부모의 너비에 걸쳐 6 개의 열이있는 테이블의 처음 2 행을 보여주는 예제 코드입니다. 각 셀의 LinearLayout 및 ImageView는 셀 색상이 유지되는 동안 셀 내 이미지의 "켜기 및 끄기"를 허용하는 데 사용됩니다.

<TableLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:stretchColumns="1,2,3,4,5,6"
    android:background="@drawable/vertical_radio_button_background"
    android:padding="2dp">

    <TableRow
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <LinearLayout
            android:id="@+id/brown"
            android:tag="13"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:gravity="center_horizontal"
            android:layout_margin="1dp"
            android:layout_column="1"
            android:background="@color/brown">

            <ImageView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:padding="5dp"
                android:src="@drawable/selected_check"
                android:visibility="invisible"/>
        </LinearLayout>

        <LinearLayout
            android:id="@+id/maraschino"
            android:tag="9"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:gravity="center_horizontal"
            android:layout_margin="1dp"
            android:layout_column="2"
            android:background="@color/maraschino">

            <ImageView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:padding="5dp"
                android:src="@drawable/selected_check"
                android:visibility="invisible"/>
        </LinearLayout>

        <LinearLayout
            android:id="@+id/cayenne"
            android:tag="22"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:gravity="center_horizontal"
            android:layout_margin="1dp"
            android:layout_column="3"
            android:background="@color/cayenne">

            <ImageView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:padding="5dp"
                android:src="@drawable/selected_check"
                android:visibility="invisible"/>
        </LinearLayout>

        <LinearLayout
            android:id="@+id/maroon"
            android:tag="18"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:gravity="center_horizontal"
            android:layout_margin="1dp"
            android:layout_column="4"
            android:background="@color/maroon">

            <ImageView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:padding="5dp"
                android:src="@drawable/selected_check"
                android:visibility="invisible"/>
        </LinearLayout>

        <LinearLayout
            android:id="@+id/plum"
            android:tag="3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:gravity="center_horizontal"
            android:layout_margin="1dp"
            android:layout_column="5"
            android:background="@color/plum">

            <ImageView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:padding="5dp"
                android:src="@drawable/selected_check"
                android:visibility="invisible"/>
        </LinearLayout>

        <LinearLayout
            android:id="@+id/eggplant"
            android:tag="15"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:gravity="center_horizontal"
            android:layout_margin="1dp"
            android:layout_column="6"
            android:background="@color/eggplant">

            <ImageView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:padding="5dp"
                android:src="@drawable/selected_check"
                android:visibility="invisible"/>
        </LinearLayout>
    </TableRow>

    <TableRow
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <LinearLayout
            android:id="@+id/plum2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:gravity="center_horizontal"
            android:layout_margin="1dp"
            android:layout_column="1"
            android:background="@color/plum">

            <ImageView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:padding="5dp"
                android:src="@drawable/selected_check"
                android:visibility="invisible"/>
        </LinearLayout>

        <LinearLayout
            android:id="@+id/lavender"
            android:tag="14"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:gravity="center_horizontal"
            android:layout_margin="1dp"
            android:layout_column="2"
            android:background="@color/lavender">

            <ImageView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:padding="5dp"
                android:src="@drawable/selected_check"
                android:visibility="invisible"/>
        </LinearLayout>

        <LinearLayout
            android:id="@+id/carnation"
            android:tag="16"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:gravity="center_horizontal"
            android:layout_margin="1dp"
            android:layout_column="3"
            android:background="@color/carnation">

            <ImageView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:padding="5dp"
                android:src="@drawable/selected_check"
                android:visibility="invisible"/>
        </LinearLayout>

        <LinearLayout
            android:id="@+id/light_pink"
            android:tag="23"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:gravity="center_horizontal"
            android:layout_margin="1dp"
            android:layout_column="4"
            android:background="@color/light_pink">

            <ImageView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:padding="5dp"
                android:src="@drawable/selected_check"
                android:visibility="invisible"/>
        </LinearLayout>

        <LinearLayout
            android:id="@+id/strawberry"
            android:tag="10"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:gravity="center_horizontal"
            android:layout_margin="1dp"
            android:layout_column="5"
            android:background="@color/strawberry">

            <ImageView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:padding="5dp"
                android:src="@drawable/selected_check"
                android:visibility="invisible"/>
        </LinearLayout>

        <LinearLayout
            android:id="@+id/magenta"
            android:tag="20"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:gravity="center_horizontal"
            android:layout_margin="1dp"
            android:layout_column="6"
            android:background="@color/magenta">

            <ImageView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:padding="5dp"
                android:src="@drawable/selected_check"
                android:visibility="invisible"/>
        </LinearLayout>
    </TableRow>
</TableLayout>


1

이것이 도움이되기를 바랍니다.

결과

여기에 이미지 설명을 입력하십시오

여기에 이미지 설명을 입력하십시오

암호:

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.GridLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:grid="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="item 0x0"
        grid:layout_column="0"
        grid:layout_columnWeight="1"
        grid:layout_gravity="center"
        grid:layout_row="0"
        grid:layout_rowWeight="1" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="item 0x1"
        grid:layout_column="1"
        grid:layout_columnWeight="1"
        grid:layout_gravity="center"
        grid:layout_row="0"
        grid:layout_rowWeight="1" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="item 0x2"
        grid:layout_column="2"
        grid:layout_columnWeight="1"
        grid:layout_gravity="center"
        grid:layout_row="0"
        grid:layout_rowWeight="1" />


    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="item 1x0"
        grid:layout_column="0"
        grid:layout_columnWeight="1"
        grid:layout_gravity="center"
        grid:layout_row="1"
        grid:layout_rowWeight="1" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="item 1x1"
        grid:layout_column="1"
        grid:layout_columnWeight="1"
        grid:layout_gravity="center"
        grid:layout_row="1"
        grid:layout_rowWeight="1" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="item 1x2"
        grid:layout_column="2"
        grid:layout_columnWeight="1"
        grid:layout_gravity="center"
        grid:layout_row="1"
        grid:layout_rowWeight="1" />


    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="item 2x0"
        grid:layout_column="0"
        grid:layout_columnWeight="1"
        grid:layout_gravity="center"
        grid:layout_row="2"
        grid:layout_rowWeight="1" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="item 2x1"
        grid:layout_column="1"
        grid:layout_columnWeight="1"
        grid:layout_gravity="center"
        grid:layout_row="2"
        grid:layout_rowWeight="1" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="item 2x2"
        grid:layout_column="2"
        grid:layout_columnWeight="1"
        grid:layout_gravity="center"
        grid:layout_row="2"
        grid:layout_rowWeight="1" />


    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="item 3x0"
        grid:layout_column="0"
        grid:layout_columnWeight="1"
        grid:layout_gravity="center"
        grid:layout_row="3"
        grid:layout_rowWeight="1" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="item 3x1"
        grid:layout_column="1"
        grid:layout_columnWeight="1"
        grid:layout_gravity="center"
        grid:layout_row="3"
        grid:layout_rowWeight="1" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="item 3x2"
        grid:layout_column="2"
        grid:layout_columnWeight="1"
        grid:layout_gravity="center"
        grid:layout_row="3"
        grid:layout_rowWeight="1" />

</android.support.v7.widget.GridLayout>

1

결과 :

여기에 이미지 설명을 입력하십시오

다음과 같이 해보십시오.

    final int MAX_COLUMN = gridView.getColumnCount(); //5
    final int MAX_ROW = gridView.getRowCount(); //7
    final int itemsCount = MAX_ROW * MAX_COLUMN; //35

    int row = 0, column = 0;

    for (int i = 0; i < itemsCount; i++) {
        ImageView view = new ImageView(this);

        //Just to provide alternate colors
        if (i % 2 == 0) {
            view.setBackgroundColor(Color.RED);
        } else {
            view.setBackgroundColor(Color.GREEN);
        }

        GridLayout.LayoutParams params = new GridLayout.LayoutParams(GridLayout.spec(row, 1F), GridLayout.spec(column, 1F));
        view.setLayoutParams(params);
        gridView.addView(view);

        column++;

        if (column >= MAX_COLUMN) {
            column = 0;
            row++;
        }
    }

셀에 특정 너비와 높이를 원하면 다음을 사용하십시오.

     params.width = 100; // Your width
     params.height = 100; //your height

1

이것은 버튼이없는 더 기본 응용 프로그램의 코드이며, 이것은 매우 편리합니다.

<GridLayout
   xmlns:android="http://schemas.android.com/apk/res/android"
   android:layout_width="match_parent"
   android:layout_height="wrap_content"
   android:columnCount="1"
   >
   <TextView
       android:text="2x2 button grid"
       android:textSize="32dip"
       android:layout_gravity="center_horizontal" />

   <LinearLayout
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:orientation="horizontal">
       <Space
           android:layout_width="wrap_content"
           android:layout_height="match_parent"
           android:layout_weight="1" />
       <TextView
           android:layout_width="wrap_content"
           android:layout_height="wrap_content"
           android:text="Naam" />
       <Space
           android:layout_width="wrap_content"
           android:layout_height="match_parent"
           android:layout_weight="1" />
       <TextView
           android:layout_width="wrap_content"
           android:layout_height="wrap_content"
           android:layout_gravity="start"
           android:text="@{viewModel.selectedItem.test2}" />
       <Space
           android:layout_width="wrap_content"
           android:layout_height="match_parent"
           android:layout_weight="1" />
   </LinearLayout>

   <LinearLayout
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:orientation="horizontal"
       >
       <Space
           android:layout_width="wrap_content"
           android:layout_height="match_parent"
           android:layout_weight="1" />
       <TextView
           android:layout_width="wrap_content"
           android:layout_height="wrap_content"
           android:text="Nummer" />
       <Space
           android:layout_width="wrap_content"
           android:layout_height="match_parent"
           android:layout_weight="1" />
       <TextView
           android:layout_width="wrap_content"
           android:layout_height="wrap_content"
           android:layout_gravity="start"
           android:text="@{viewModel.selectedItem.test}" />
       <Space
           android:layout_width="wrap_content"
           android:layout_height="match_parent"
           android:layout_weight="1" />
   </LinearLayout>
</GridLayout>

1

나는 같은 문제가 있고 프로그래밍 방식으로 너비와 높이를 설정한다고 생각합니다.

metrics.widthPixels / 2 메트릭은 버튼의 너비를 DisplayMetrics의 객체로 설정합니다.

 GridLayout gridLayout=findViewById(R.id.grid);
    for (int i = 0; i <gridLayout.getChildCount() ; i++) {
        View view= gridLayout.getChildAt(i);
        if(view instanceof Button){
            Button btn = (Button) view;
            btn.setWidth(200);//metrics.widthPixels / 2
            btn.setHeight(200);//metrics.heightPixels / 7
        }
    } 

0

그리드 레이아웃

       <GridLayout
        android:layout_width="match_parent"
        android:layout_weight="3"
        android:columnCount="2"
        android:padding="10dp"
        android:rowCount="3"
        android:background="@drawable/background_down"
        android:layout_height="0dp">


        <androidx.cardview.widget.CardView
            android:layout_height="0dp"
            android:layout_width="0dp"
            android:layout_columnWeight="1"
            android:layout_rowWeight="1"
            android:layout_margin="10dp"
            android:elevation="10dp"
            app:cardCornerRadius="15dp"
            >
            <LinearLayout
                android:weightSum="3"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="vertical"
                >

                <ImageView
                    android:layout_weight="2"
                    android:layout_width="50dp"
                    android:layout_height="50dp"
                    android:layout_margin="15dp"
                    android:src="@drawable/user" />

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Users"
                    android:textSize="16sp"
                    android:layout_marginStart="15dp"
                    android:layout_marginLeft="15dp" />
            </LinearLayout>

        </androidx.cardview.widget.CardView>
        <androidx.cardview.widget.CardView
            android:layout_height="0dp"
            android:layout_width="0dp"
            android:layout_columnWeight="1"
            android:layout_rowWeight="1"
            android:layout_margin="10dp"
            android:elevation="10dp"
            app:cardCornerRadius="15dp"
            >
            <LinearLayout
                android:weightSum="3"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="vertical"
                >

                <ImageView
                    android:layout_weight="2"
                    android:layout_width="50dp"
                    android:layout_height="50dp"
                    android:layout_margin="15dp"
                    android:src="@drawable/addusers" />

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Add Users"
                    android:textSize="16sp"
                    android:layout_marginStart="15dp"
                    android:layout_marginLeft="15dp" />
            </LinearLayout>


        </androidx.cardview.widget.CardView>

        <androidx.cardview.widget.CardView
            android:layout_height="0dp"
            android:layout_width="0dp"
            android:layout_columnWeight="1"
            android:layout_rowWeight="1"
            android:layout_margin="10dp"
            android:elevation="10dp"
            app:cardCornerRadius="15dp"
            >
            <LinearLayout
                android:weightSum="3"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="vertical"
                >

                <ImageView
                    android:layout_weight="2"
                    android:layout_width="50dp"
                    android:layout_height="50dp"
                    android:layout_margin="15dp"
                    android:src="@drawable/newspaper" />

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Report"
                    android:textSize="16sp"
                    android:layout_marginStart="15dp"
                    android:layout_marginLeft="15dp" />
            </LinearLayout>



        </androidx.cardview.widget.CardView>
        <androidx.cardview.widget.CardView
            android:layout_height="0dp"
            android:layout_width="0dp"
            android:layout_columnWeight="1"
            android:layout_rowWeight="1"
            android:layout_margin="10dp"
            android:elevation="10dp"
            app:cardCornerRadius="5dp"
            >
            <LinearLayout
                android:weightSum="3"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="vertical"
                >

                <ImageView
                    android:layout_weight="2"
                    android:layout_width="50dp"
                    android:layout_height="50dp"
                    android:layout_margin="15dp"
                    android:src="@drawable/settings" />

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Settings"
                    android:textSize="16sp"
                    android:layout_marginStart="15dp"
                    android:layout_marginLeft="15dp" />
            </LinearLayout>


        </androidx.cardview.widget.CardView>

    </GridLayout>

CardView 및 OnItemClickListener가있는 Android Grid Layout 에서 전체 자습서를 찾을 수 있습니다.


-2

여기 내가 한 일이 있으며 이것이 나를 위해 일했다고 기쁘다. 나도 전체 화면을 덮기 위해 2x2, 3x3 등의 항목 그리드를 원했습니다. Gridlayout은 화면 너비에 맞지 않습니다. LinearLayouts는 일종의 작업이지만 중첩 된 가중치를 사용할 수 없습니다.

나를 위해 최선의 선택은 사용하는 것이었다 조각 내가 사용 이 튜토리얼을 하여 내가하고 싶은 일을 시작 .

다음은 몇 가지 코드입니다.

주요 활동:

public class GridHolderActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main_6);
    }
}

activity_main_6 XML (3 개의 조각을 팽창시킵니다)

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <fragment
        android:id="@+id/frag1"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:name=".TwoHorizontalGridFragment"
        tools:layout="@layout/two_horiz" />
    <fragment
        android:id="@+id/frag2"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:name=".TwoHorizontalGridFragment"
        tools:layout="@layout/two_horiz" />
    <fragment
        android:id="@+id/frag3"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:name=".Grid.TwoHorizontalGridFragment"
        tools:layout="@layout/two_horiz" />

기본 조각 레이아웃

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="wrap_content"
    android:layout_gravity="center"
    android:layout_height="match_parent">

    <ImageQueue
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:id="@+id/img1"
        android:layout_weight="1"/>


    <ImageQueue
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:id="@+id/img2"
        android:layout_weight="1"/>
</LinearLayout>

조각 클래스 (사용자 정의보기의 초기화 만 처리)는 조각 당 2 개의 타일을 팽창시킵니다

public class TwoHorizontalGridFragment extends Fragment {
private View rootView;

private ImageQueue imageQueue1;
private ImageQueue imageQueue2;

@Override
public View onCreateView(LayoutInflater inflater,
                         ViewGroup container, Bundle savedInstanceState) {
    /**
     * Inflate the layout for this fragment
     */
    rootView = inflater.inflate(
            R.layout.two_horiz, container, false);
    return rootView;
}

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    imageQueue1 = (ImageQueue)rootView.findViewById(R.id.img1);
    imageQueue2 = (ImageQueue)rootView.findViewById(R.id.img2);
    imageQueue1.updateFiles();
    imageQueue2.updateFiles();
}

}

그게 다야!

이것은 본질적으로 중첩 가중치를 사용하는 이상한 해결책입니다. 10 인치 태블릿과 HTC 드로이드 DNA의 전체 화면을 채우는 완벽한 2x3 그리드를 제공합니다. 어떻게되는지 알려주세요!


1
gridview / gridlayout을 사용하여 얻을 수있는 간단한 tak을 수행하기 위해 복잡한 구조가 많이있는 여러 조각을 가지고 있기 때문에 이것은 나쁜 접근법입니다.
— Raykud

OP는 몇 개의 버튼에 2x2 그리드가 필요하다고 말했다. 당신 말이 맞아요, 이것은 복잡한 방법입니다. 더 많은 텍스트,보기 및 기타 컨텐츠가 포함 된 레이아웃의 경우 조각을 사용하는 것이 좋습니다. 또한 레이아웃이 완전히 정적이고 동적으로 빌드되지 않은 경우에만 유용합니다.
— Nlinscott

API 21에서 GridLayouts에 대한 지원이 추가
— 되었으므로이
당사 사이트를 사용함과 동시에 당사의 쿠키 정책과 개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.