¿Cómo puedo obtener un Android TableLayout para llenar la pantalla?

Estoy luchando con el terrible sistema de diseño de Android. Estoy tratando de conseguir una mesa para llenar la pantalla (simple ¿verdad?), Pero es ridículamente difícil.

Tengo que trabajar de alguna manera en XML como este:

<?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. He intentado 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 ayuda. ¿Alguien tiene alguna idea?

Hay dos errores en la discusión anterior.

  1. Es posible programar el peso especificando TableLayout.LayoutParams y TableRow.LayoutParams y usando el constructor apropiado, por ejemplo

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

  2. Un widget debe tener LayoutParams de su padre. 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 Guy en el foro de desarrolladores de Android para la solución .

Finalmente trabajó cómo hacer esto. Dejó en TableLayout y acaba de utilizar LinearLayout horizontal dentro de una vertical. La clave clave 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); 

Encontrado la respuesta: al parecer, es el layout_weight que hace que funcione y no hay forma de establecerlo desde Java. Maldición.

Consulte ¿Cómo puedo obtener un Android TableLayout para rellenar el padre en modo horizontal?

Nunca se establecen los parámetros de diseño de fila o botón, mientras que en el xml publicado se hace eso … cambia los detalles de los bucles for para establecer tanto los parámetros de disposición de fila como los parámetros de diseño del botón que debería dar el mismo resultado que el xml.

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

Por lo tanto, debe utilizar FrameLayout.LayoutParams, si desea establecer las propiedades de TableLayout mediante programación. 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); 
  • SOAP - Respuesta XML muy grande - OutOfMemoryError
  • El servidor no pudo procesar su solicitud. El valor no puede ser nulo: análisis de jabón
  • Cómo crear un menú mediante programación en Android?
  • Android - Botón de radio - el botón dibujable no se muestra en Lollipop
  • Submenú del menú del cajón de navegación
  • Android, envío de XML a través de HTTP POST (SOAP)
  • Cómo obtener contenido completo de noticias de un sitio web de noticias
  • Jsoup no puede leer el archivo de retorno xml
  • Archivo XML válido da un error "no se pudo analizar" en Android ADT
  • Ejemplo de programa para android Parche relajante usando xml API
  • Prioridad de truncamiento de Android TextView o Resistencia de compresión
  • FlipAndroid es un fan de Google para Android, Todo sobre Android Phones, Android Wear, Android Dev y Aplicaciones para Android Aplicaciones.