¿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:
- Mejor editor de diseño XML de Android que el de Eclipse
- ¿Java sobreescribe XML en Android?
- No se pueden obtener widgets de main.xml referenciados en el programa Java
- ¿Cómo puedo crear un ListView con divisiones de línea punteadas / punteadas en Android?
- Android cómo cambiar <item> anchura y altura
<?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?
- ActionBar / Barra de herramientas no se muestra en la versión de Lollipop de la aplicación
- Imagen de estiramiento en la imagen para ajustar la pantalla en xml
- Android - ejemplo de análisis XML roto
- Cómo crear líneas en xml
- ¿Debería estar lleno el archivo xml del contenido de la copia de seguridad completa o no incluirlo en todos?
- Efecto de ondulación en la parte superior de la imagen - Android
- Acceso al atributo de manifiesto android: installLocation
- No existe una etiqueta de meta-datos necesaria en AndroidManifest.xml de la aplicación.
Hay dos errores en la discusión anterior.
-
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);
- 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);
- Convertir JSONArray a Array de cadenas
- Android Gradle DexException: Múltiples archivos dex definen Lorg / hamcrest / Descripción