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:

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.

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

  • Cambiar un divisor con setDivider en un ListActivity sin un ListView personalizado?
  • Ocultar divisor sin ocultar childDivider en ExpandableListView
  • ActionBarsherlock cómo establecer divisores en elementos de menú con sólo iconos
  • Cómo establecer el ancho de divisor ListView?
  • Cómo obtener divisores en el menú de NavigationView sin títulos?
  • ¿Cómo tener fondos y colores diferentes para divisores en GridView?
  • Radiogrupo Android, divisor entre los botones de radio
  • Implementar el divisor entre el último elemento del niño y el siguiente grupo de cabecera.
  • Cómo cambiar el color del divisor PreferenceCategory en PreferenceScreen
  • Eliminar divisor después de un pie de página en un ListView
  • ¿Cómo agregar un divisor (vertical) a un LinearLayout horizontal?
  • FlipAndroid es un fan de Google para Android, Todo sobre Android Phones, Android Wear, Android Dev y Aplicaciones para Android Aplicaciones.