2010-03-06 8 views
27

Estoy luchando con el horrible sistema de diseño de Android. Estoy tratando de obtener una tabla para llenar la pantalla (¿verdad?) Pero es ridículamente difícil.¿Cómo puedo obtener un TableLayout de Android para llenar la pantalla?

Yo tengo que trabajar de alguna manera en XML como esto:

<?xml version="1.0" encoding="utf-8"?> 

<TableLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_height="fill_parent" android:layout_width="fill_parent"> 
<TableRow android:layout_height="fill_parent" android:layout_width="fill_parent" android:layout_weight="1"> 
<Button android:text="A" android:layout_width="wrap_content" android:layout_height="fill_parent" android:layout_weight="1"/> 
<Button android:text="B" android:layout_width="wrap_content" android:layout_height="fill_parent" android:layout_weight="1"/> 
</TableRow> 
<TableRow android:layout_height="fill_parent" android:layout_width="fill_parent" android:layout_weight="1"> 
<Button android:text="C" android:layout_width="wrap_content" android:layout_height="fill_parent" android:layout_weight="1"/> 
<Button android:text="D" android:layout_width="wrap_content" android:layout_height="fill_parent" android:layout_weight="1"/> 
</TableRow> 

sin embargo no puedo conseguir que funcione en Java. Probé un millón de combinaciones de LayoutParams, pero nada funciona. Este es el mejor resultado que tengo que sólo llena el ancho de la pantalla, no la altura:

table = new TableLayout(this); 
    // Java. You suck. 
    TableLayout.LayoutParams lp = new TableLayout.LayoutParams(
            ViewGroup.LayoutParams.FILL_PARENT, 
            ViewGroup.LayoutParams.FILL_PARENT); 
    table.setLayoutParams(lp); // This line has no effect! WHYYYY?! 
    table.setStretchAllColumns(true); 
    for (int r = 0; r < 2; ++r) 
    { 
     TableRow row = new TableRow(this); 
     for (int c = 0; c < 2; ++c) 
     { 
      Button btn = new Button(this); 
      btn.setText("A"); 
      row.addView(btn); 
     } 
     table.addView(row); 
    } 

Obviamente la documentación de Android no es ninguna ayuda. ¿Alguien tiene alguna idea?

+3

No creo que vaya a hacer que mucha gente se apresure a darle una respuesta con toda esa negatividad en su pregunta. –

+3

Sí, lo sé. Es realmente frustrante cuando luchas por siglos con lo que debería ser una tarea simple. – Timmmm

+5

+1 para el 'sistema de diseño retrasado de Android' –

Respuesta

8

finalmente funcionó la manera de hacer esto. Partió de TableLayout y simplemente usó LinearLayout horizontal dentro de uno vertical. La clave crítica es establecer el peso. Si especifica FILL_PARENT pero con el peso predeterminado, no funciona:

LinearLayout buttonsView = new LinearLayout(this); 
    buttonsView.setOrientation(LinearLayout.VERTICAL); 
    for (int r = 0; r < 6; ++r) 
    { 
     LinearLayout row = new LinearLayout(this); 
     row.setOrientation(LinearLayout.HORIZONTAL); 
     for (int c = 0; c < 4; ++c) 
     { 
      Button btn = new Button(this); 
      btn.setText("A"); 
      LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.FILL_PARENT); 
      lp.weight = 1.0f; 
      row.addView(btn, lp); 
     } 
     LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.FILL_PARENT); 
     lp.weight = 1.0f; 
     buttonsView.addView(row, lp); 
    } 

    ViewGroup.LayoutParams lp = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT); 
    setContentView(buttonsView, lp); 
0

Nunca establece los parámetros de diseño de fila o botón, mientras que en el xml publicado lo hace ... cambie los detalles de los bucles for para establecer los parámetros de diseño de fila y de diseño de botón de lo que debería dar el mismo resultado tu xml

+0

No es así - Lo intenté (¡de muchas maneras!). Además, en los documentos de Android dice: "Los elementos secundarios de un TableLayout no pueden especificar el atributo layout_width. El ancho siempre es FILL_PARENT. Sin embargo, el atributo layout_height puede ser definido por un elemento secundario, el valor predeterminado es WRAP_CONTENT. , entonces la altura siempre es WRAP_CONTENT ". Y "Los elementos secundarios de un TableRow no necesitan especificar los atributos layout_width y layout_height en el archivo XML. TableRow siempre impone que dichos valores sean, respectivamente, FILL_PARENT y WRAP_CONTENT". – Timmmm

34

Hay 2 errores en la discusión anterior.

  1. Es posible establecer programáticamente el peso especificando TableLayout.LayoutParams y TableRow.LayoutParams y utilizando el constructor apropiado, por ejemplo,

    TableLayout.LayoutParams rowInTableLp = new TableLayout.LayoutParams (LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT, 1.0f);

  2. Un widget debe tener los LayoutParams de su elemento primario. Por lo tanto, las filas deben utilizar TableLayout.LayoutParams

Esto le da la siguiente versión de trabajo de su código inicial:

TableLayout table = new TableLayout(this); 
// Java. You succeed! 
FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(
     ViewGroup.LayoutParams.FILL_PARENT, 
     ViewGroup.LayoutParams.FILL_PARENT); 
table.setLayoutParams(lp); 
table.setStretchAllColumns(true); 

TableLayout.LayoutParams rowLp = new TableLayout.LayoutParams(
     ViewGroup.LayoutParams.FILL_PARENT, 
     ViewGroup.LayoutParams.FILL_PARENT, 
     1.0f); 
TableRow.LayoutParams cellLp = new TableRow.LayoutParams(
     ViewGroup.LayoutParams.FILL_PARENT, 
     ViewGroup.LayoutParams.FILL_PARENT, 
     1.0f); 
for (int r = 0; r < 2; ++r) 
{ 
    TableRow row = new TableRow(this); 
    for (int c = 0; c < 2; ++c) 
    { 
     Button btn = new Button(this); 
     btn.setText("A"); 
     row.addView(btn, cellLp); 
    } 
    table.addView(row, rowLp); 
} 
setContentView(table); 

Gracias al comentario de Romain individuo en el foro de desarrolladores de Android para the solution.

+0

¡Whooah, he estado luchando con otros ejemplos por edades! ¡Finalmente este funciona! Thaaanks! – bk138

+2

Esta frase me funcionó: 'Un widget debe tener los LayoutParams de su principal. Por lo tanto, las filas deben usar TableLayout.LayoutParams ' – hhh3112

+1

Pasé horas en esto hasta que leí esto ... ** "Un widget debe tener los LayoutParams de su principal." ** Gracias me salvó mucho tiempo ! – Bojan

0

Para configurar TableLayout LayoutParams, lógicamente esperamos utilizar la clase TableLayout.LayoutParams, pero obtendrá un error de conversión que indica que TableLayout.LayoutParams no se puede convertir en FrameLayout.LayoutParams.

Por lo tanto, debe usar FrameLayout.LayoutParams, si desea establecer programáticamente las propiedades de TableLayout. Por ejemplo:

FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(TableLayout.LayoutParams.MATCH_PARENT,TableLayout.LayoutParams.MATCH_PARENT); 
      layoutParams.setMargins(80, 0, 0, 0); 
      TableLayout tableLayout = (TableLayout) findViewById(R.id.header_detail); 
      tableLayout.setLayoutParams(layoutParams); 
Cuestiones relacionadas