gridlayout columns android android-layout android-gridlayout

gridlayout 2 columns android



GridLayout Ancho de columna (6)

Tengo 2 columnas en mi GridLayout . Lo que quiero hacer es hacer que esas columnas ocupen la mitad del ancho de la pantalla y que sus contenidos secundarios llenen sus propias celdas de ancho / alto. Intenté configurar los hijos para fill_parent pero eso solo hace que el primero se haga cargo de todo el diseño. ¿Y parece que GridLayout no es compatible con el weight ? Tal vez haya un mejor diseño para usar, pero quiero un diseño de estilo Grid para que parezca la elección natural.


¡Este código está disponible en pre API21 con la biblioteca de soporte!

Tengo un código simple para mostrar 4 botones en una cuadrícula. Diseño de 2 columnas que ocupan el 50% del espacio disponible: quizás pueda ayudar

<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>

La solución es quizás esto:

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


Cuando usa un GridLayoutManager , puede usar setSpanSizeLookup . Aquí hay un fragmento de mi proyecto que debería ayudar a usar este método correctamente:

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();


Ok, entonces desistí de la vista de cuadrícula y solo usé algunos diseños lineales. Hice una vertical y luego agregué 2 horizontales. Es un poco más complicado que la vista de la cuadrícula ... pero hasta que lo descubra, al menos, esto funciona.

<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>

Y luego agrego esto para hacer que los botones cuadren :)

@Override public void onWindowFocusChanged(boolean hasFocus) { super.onWindowFocusChanged(hasFocus); btnPrefs.setMinimumHeight(btnPrefs.getWidth()); btnVerse.setMinimumHeight(btnMyButton.getWidth()); }


Para pre API 21, use la biblioteca de soporte:

añadir

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

a tus dependencias

Luego en tu archivo 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>

Aquí tenga en cuenta el uso del prefijo "aplicación" y no se olvide de agregar

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

a tu archivo xml


Puede extender la clase RelativeLayout (o usar LinearLayout si lo desea) para asegurarse de que la altura del elemento sea la misma que la altura.

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()); } }

La vista principal del diseño del elemento debe ser la vista GridItem para asegurarse de que funciona. Este debe ser el archivo de diseño que inflará en el getView de su 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>

Y configure el stretchMode de GridView en columnWidth. Esto hará que todos los elementos se ajusten al ancho especificado en el número de columnas. La nueva vista se asegurará de que también tengan la misma altura.

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


agregar vistas dinámicamente en una grilla Diseño de 2 columnas que toman el 50% del espacio disponible:

GridLayout gridLayout = new GridLayout(); View view; //it can be any view GridLayout.LayoutParams param = new GridLayout.LayoutParams(); param.columnSpec = GridLayout.spec(GridLayout.UNDEFINED,GridLayout.FILL,1f); param.width = 0; view.setLayoutParams(param); gridLayout.add(view);

de forma estática (en el archivo .xml).

<android.support.v7.widget.GridLayout xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="match_parent" app:alignmentMode="alignBounds" app:columnCount="2" app:columnOrderPreserved="false" app:orientation="horizontal" android:layout_margin="20dp" android:layout_marginBottom="30dp" android:padding="4dp" app:rowCount="2"> <TextView android:layout_marginTop="2dp" android:id="@+id/edit_profile_username" android:layout_width="0dp" android:layout_height="wrap_content" app:layout_column="0" app:layout_row="0" app:layout_gravity="fill" app:layout_columnWeight="1" android:text="@string/user_name" /> <TextView android:layout_marginTop="2dp" android:id="@+id/edit_profile_first_name" android:layout_width="0dp" android:layout_height="wrap_content" app:layout_column="1" app:layout_row="0" app:layout_gravity="fill" app:layout_columnWeight="1" android:text="@string/first_name" /> <TextView android:layout_marginTop="2dp" android:id="@+id/edit_profile_middle_name" android:layout_width="0dp" android:layout_height="wrap_content" app:layout_column="0" app:layout_gravity="fill" app:layout_columnWeight="1" app:layout_row="1" android:text="@string/middle_name" /> <TextView android:layout_marginTop="2dp" android:id="@+id/edit_profile_last_name" android:layout_width="0dp" android:layout_height="wrap_content" app:layout_column="1" app:layout_gravity="fill" app:layout_columnWeight="1" app:layout_row="1" android:text="@string/last_name" /> </android.support.v7.widget.GridLayout>