2012-04-02 111 views
12

Tengo un TableLayout donde agrego dinámicamente TableRows. En cada TableRow, agrego un botón.Agregar espacio entre columnas de un TableLayout

Simplemente me gustaría agregar algo de espacio entre mis columnas (que son mis botones) pero no puedo entender cómo ... He intentado cambiar todos los márgenes posibles, pero no funciona: ( Así que tal vez cometió un error en mi código donde les inflar a partir 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 su ayuda.

+0

¿realmente quiere decir que quiere agregar espacio entre las filas (no las columnas?) – manmal

+0

¿Desea espacio entre el botón y el nombre de la columna o qué? No tengo una idea exacta. – Dhruvisha

+0

@manmal Tengo una nueva columna por botón. Quiero agregar espacio entre columnas. Entre filas está bien. – Nico

Respuesta

13

En el caso de un TableLayout, los botones son las columnas. Eso significa que debe aconsejar a los botones que mantengan un espacio entre ellos. Puede hacerlo utilizando parámetros de diseño. Son mucho más fáciles de configurar en XML, pero también funciona mediante programación. Es importante que siempre se utiliza la clase LayoutParam de la disposición padre del elemento donde se aplica - en este caso el padre es un TableRow: Atributos

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

mayoría dimensión en Android tomar píxeles si se configura programáticamente; por lo tanto, debe usar algo como mi método dpToPixel(). ¡Por favor, nunca use valores de píxeles en Android! Te arrepentirás más adelante.

Si no desea que el botón de la derecha tenga este margen, simplemente verifique con un IF y no agregue el LayoutParam en él.


Solución en XML:

Para evitar la LayoutInflater borrar sus atributos XML definidos, hacer esto mientras infla (tomado de Layout params of loaded view are ignored):

View view = inflater.inflate(R.layout.item /* resource id */, 
            MyView.this /* parent */, 
            false /*attachToRoot*/); 

Alternativa: Use un GridView como ese: Android: Simple GridView that displays text in the grids

+0

Gracias Manmal funciona pero no lo entiendo! Cuando trato de poner android: layout_marginRight = "10dp" o android: layout_margin = "10dp" en mi button_table_row_category.xml, no funciona. ¿Cómo podría hacerlo en XML? Gracias de nuevo ! – Nico

+0

respuesta actualizada con la solución XML :) – manmal

+0

En realidad, no tengo una clase que represente mi diseño como MyView lo hace por el problema en su enlace. Solo uso XML, en ese caso, ¿cómo puedo hacerlo? También estoy sorprendido, LayoutInflater borra mis atributos XML definidos? Por qué eso ? ¿Cuál es el punto de inflar un XML? – Nico

8

Añadir relleno derecho para un componente en el componente de fila de la tabla

<TableRow 
    android:id="@+id/tableRow1"> 

    <TextView 
     android:id="@+id/textView1" 
     android:paddingRight="20dp" /> 

</TableRow> 
+0

Aunque el que pregunta preguntó cómo agregar el espaciado programáticamente, esto me ayudó a buscar para una solución alternativa en XML. –

0

tratar de usar la función de la setColumnStretchableTableLayout. Déle un índice de columna y establezca su propiedad estirable en verdadero.

Ej. Si tienes 3 columnas

TableLayout tblLayout; 
tblLayout.setColumnStretchable(0, true); 
tblLayout.setColumnStretchable(1, true); 
tblLayout.setColumnStretchable(2, true); 

Lo anterior le dará igual separación entre los 3 columnas de la tableLayout.

1

Probar android:layout_marginRight="6dp" esto funcionó para mí.

Cuestiones relacionadas