Подтвердить что ты не робот

Ширина столбца GridLayout

У меня есть 2 столбца в моем GridLayout. Я хочу сделать, чтобы эти столбцы занимали половину ширины экрана каждый, а затем его дочернее содержимое заполняло их собственные ячейки шириной/высотой. Я попытался установить детей на fill_parent, но это просто заставляет первый захватить весь макет. И похоже, что GridLayout не поддерживает weight? Может быть, лучше использовать макет, но мне нужен макет стиля Grid, который кажется естественным выбором.

4b9b3361

Ответ 1

Этот код доступен в pre API21 с библиотекой поддержки!

У меня есть простой кусок кода, чтобы показать 4 кнопки в gridLayout из 2 столбцов, которые занимают 50% доступного пространства: возможно, это может помочь

<GridLayout
    android:id="@+id/grid"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:columnCount="2"
    >


    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button"
        android:layout_gravity="fill"
        android:layout_columnWeight="1"
        />

       <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button"
        android:layout_gravity="fill"
        android:layout_columnWeight="1"
        />

       <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button"
        android:layout_gravity="fill"
        android:layout_columnWeight="1"
        />

       <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button"
        android:layout_gravity="fill"
        android:layout_columnWeight="1"
        />



</GridLayout>

Решение, возможно, таково:

android:layout_gravity="fill"
android:layout_columnWeight="1"

Ответ 2

Для предварительного API 21 используйте библиотеку поддержки:

добавить

compile 'com.android.support:appcompat-v7:23.1.1'
compile 'com.android.support:design:23.1.1'

к вашим зависимостям.

Затем в вашем XML файле:

<android.support.v7.widget.GridLayout
                    xmlns:app="http://schemas.android.com/apk/res-auto"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    app:columnCount="2"
                    app:orientation="horizontal"
                    app:rowCount="1">

                    <TextView
                        android:text="1"
                        android:textStyle="bold"
                        app:layout_columnWeight="1"
                        />

                    <TextView
                        android:text="2"
                        android:textStyle="bold"
                        app:layout_columnWeight="1" />

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

Здесь обратите внимание на использование префикса приложения и не забудьте добавить

xmlns:app="http://schemas.android.com/apk/res-auto"

в ваш XML файл

Ответ 3

Хорошо, поэтому я отказался от вида сетки и просто использовал некоторые линейные макеты. Я сделал вертикальный, а затем добавил 2 горизонтали. Это немного больше, чем представление сетки... но пока я не понял, что, по крайней мере, это работает.

<LinearLayout
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:orientation="vertical" >

        <ImageButton
            android:id="@+id/btn_mybutton"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="5dp"
            android:background="@color/pomegranate"
            android:contentDescription="@string/contentDescriptionmybutton"
            android:src="@drawable/ic_launcher" />

    </LinearLayout>

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:orientation="vertical" >

        <ImageButton
            android:id="@+id/btn_prefs"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="5dp"
            android:background="@color/pomegranate"
            android:contentDescription="@string/contentDescriptionSettings"
            android:src="@drawable/ic_settings" />

    </LinearLayout>

</LinearLayout>

И затем я добавляю это, чтобы сделать квадраты кнопок:)

@Override
 public void onWindowFocusChanged(boolean hasFocus) {
  super.onWindowFocusChanged(hasFocus);

  btnPrefs.setMinimumHeight(btnPrefs.getWidth());
  btnVerse.setMinimumHeight(btnMyButton.getWidth());

 }

Ответ 4

Вы можете расширить класс RelativeLayout (или использовать LinearLayout, если хотите), чтобы убедиться, что высота элемента будет такой же, как высота.

public class GridItem extends RelativeLayout {

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

        public GridItem(Context context, AttributeSet attr) {
                super(context, attr);
        }

        public GridItem(Context context, AttributeSet attr, int integer) {
                super(context, attr, integer);
        }

        // Override onMeasure to give the view the same height as the specified width
        @Override
        public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
            super.onMeasure(widthMeasureSpec, widthMeasureSpec);
            setMeasuredDimension(getMeasuredWidth(), getMeasuredWidth());
        }

}

Родительский вид макета элемента должен быть представлением GridItem, чтобы убедиться, что он работает. Это должен быть файл макета, который вы будете раздувать в getView вашего ListAdapter

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

    <!-- The content of the item -->

</my.packagename.GridItem>

И установите для параметра stretchMode GridView значение columnWidth. Это приведет к тому, что все элементы будут соответствовать ширине указанного количества столбцов. В новом представлении убедитесь, что они также будут иметь одинаковую высоту.

<GridView
    android:id="@+id/gridList"
    android:numColumns="2"
    android:stretchMode="columnWidth"
/>

Ответ 5

Когда вы используете GridLayoutManager, вы можете использовать setSpanSizeLookup. Вот фрагмент моего проекта, который должен помочь правильно использовать этот метод:

if (mAdapter == null) {
    final int columnCount = getResources().getInteger(R.integer.numberGridColumns);
    mLayoutManager = new GridLayoutManager(getActivity(), columnCount);
    mLayoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
        @Override
        public int getSpanSize(int position) {
            switch (mAdapter.getItemViewType(position)) {
                case ListAdapter.VIEW_TYPE_ONE_COLUMN:
                    return columnCount;
                case RecipeListAdapter.VIEW_TYPE_FULL_COLUMN:
                default:
                    return 1;
            }
        }
    });
    mRecyclerView.setLayoutManager(mLayoutManager);

    mAdapter = new RecipeListAdapter(mPresenter);
    mRecyclerView.setAdapter(mAdapter);
}
mAdapter.notifyDataSetChanged();

Ответ 6

динамическое добавление представлений в сетке. Макет из двух столбцов, которые занимают 50% доступного пространства:

GridLayout gridLayout = новый GridLayout();

Просмотреть вид;//это может быть любой вид

GridLayout.LayoutParams param = new GridLayout.LayoutParams();

param.columnSpec = GridLayout.spec(GridLayout.UNDEFINED, GridLayout.FILL, 1f);

param.width = 0;

view.setLayoutParams(пары);

gridLayout.add(вид);