Agregar espacio entre columnas de un TableLayout
Tengo un TableLayout donde agrego dinámicamente TableRows. En cada TableRow, agrego un botón.
Sólo me gustaría añadir un poco de espacio entre mis columnas (que son mis botones), pero no puedo averiguar cómo … He intentado cambiar todos los márgenes posibles, pero no funciona 🙁 Así que tal vez he hecho Un error en mi código donde los hincho de archivos XML:
- ¿Cómo generar un ListView con encabezados por encima de algunas secciones?
- Estilos / atributos de divisor predeterminados de ListView de Android
- Ocultar ListView Encabezado / Ocultar Single Divider en una lista
- ¿Cómo puedo eliminar el divisor de un listview en android?
- Cómo establecer divisor entre columnas en tablelayout?
private void createButtons(final CategoryBean parentCategory) { final List<CategoryBean> categoryList = parentCategory.getCategoryList(); title.setText(parentCategory.getTitle()); // TODO à revoir int i = 0; TableRow tr = null; Set<TableRow> trList = new LinkedHashSet<TableRow>(); for (final CategoryBean category : categoryList) { TextView button = (TextView) inflater.inflate(R.layout.button_table_row_category, null); button.setText(category.getTitle()); if (i % 2 == 0) { tr = (TableRow) inflater.inflate(R.layout.table_row_category, null); tr.addView(button); } else { tr.addView(button); } trList.add(tr); button.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { CategoryBean firstChild = category.getCategoryList() != null && !category.getCategoryList().isEmpty() ? category .getCategoryList().get(0) : null; if (firstChild != null && firstChild instanceof QuestionsBean) { Intent intent = new Intent(CategoryActivity.this, QuestionsActivity.class); intent.putExtra(MainActivity.CATEGORY, category); startActivityForResult(intent, VisiteActivity.QUESTION_LIST_RETURN_CODE); } else { Intent intent = new Intent(CategoryActivity.this, CategoryActivity.class); intent.putExtra(MainActivity.CATEGORY, category); startActivityForResult(intent, VisiteActivity.CATEGORY_RETURN_CODE); } } }); i++; } for (TableRow tableRow : trList) { categoryLaout.addView(tableRow); } }
Mi button_table_row_category.xml:
<?xml version="1.0" encoding="utf-8"?> <TextView xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/buttonTableRowCategory" style="@style/ButtonsTableRowCategory" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:text="@string/validate" />
Mi table_row_category.xml:
<?xml version="1.0" encoding="utf-8"?> <TableRow xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/tableRowCategory" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_margin="100dp" android:gravity="center" android:padding="5dp" > </TableRow>
Gracias por tu ayuda.
- Establecimiento de diferentes colores de divisor para cada elemento en la vista de lista
- Barra de acción de Android barra divisora de barras
- Quite el divisor inferior de un ListView de Android
- Divisor para LinearLayout vertical?
- Divisor ListView para Android
- Android: ¿Cuál es el valor predeterminado de android: dividerHeight para una vista de lista
- ¿Cómo agregar divisores entre elementos de menú específicos?
- Android: eliminar el divisor de algunos listitems en listview
En el caso de un TableLayout, los Botones mismos son las columnas. Eso significa que usted tiene que aconsejar a los botones para mantener un poco de espacio entre. Puede hacerlo utilizando parámetros de diseño. Son mucho más fáciles de establecer en XML, pero también funciona mediante programación. Es importante que siempre use la clase LayoutParam del diseño padre del elemento donde lo aplique – en este caso el padre es un TableRow:
// Within createButtons(): android.widget.TableRow.LayoutParams p = new android.widget.TableRow.LayoutParams(); p.rightMargin = DisplayHelper.dpToPixel(10, getContext()); // right-margin = 10dp button.setLayoutParams(p); // DisplayHelper: private static Float scale; public static int dpToPixel(int dp, Context context) { if (scale == null) scale = context.getResources().getDisplayMetrics().density; return (int) ((float) dp * scale); }
La mayoría de los atributos de dimensión en Android toman píxeles si los configura de forma programática; por lo tanto, debería usar algo como mi método dpToPixel (). Por favor, no utilice los valores de píxeles en Android. Lo lamentarás más tarde.
Si no desea que el botón más a la derecha tenga este margen, solo marque con un IF y no agregue el LayoutParam en él.
Solución en XML:
Para evitar que el LayoutInflater elimine los atributos definidos por XML, haga esto mientras se infla (tomado de los parámetros de Layout de la vista cargada se ignoran ):
View view = inflater.inflate( R.layout.item /* resource id */, MyView.this /* parent */, false /*attachToRoot*/);
Alternativa : Utilice un GridView así: Android: Simple GridView que muestra texto en las cuadrículas
Agregar el relleno derecho para un componente en el componente de fila de tabla
<TableRow android:id="@+id/tableRow1"> <TextView android:id="@+id/textView1" android:paddingRight="20dp" /> </TableRow>
Intente usar la función setColumnStretchable
de TableLayout
. Darle un índice columnn y establecer su propiedad elástica a true.
P.ej. Si tiene 3 columnas.
TableLayout tblLayout; tblLayout.setColumnStretchable(0, true); tblLayout.setColumnStretchable(1, true); tblLayout.setColumnStretchable(2, true);
Lo anterior le dará el mismo espacio entre las 3 columnas de la tableLayout
.
Pruebe el android:layout_marginRight="6dp"
esto funcionó para mí.