3

Tengo una app en AndroidStudio la cual carga datos desde una BD en MySQL. Para mostrar dichos datos, lo hago a través de un TableLayout. El problema, es el siguiente, me gustaría que se respete un alto específico. Cuando estuve realizando pruebas, se mostraba con zonas de menor caracteres:

introducir la descripción de la imagen aquí

Pero cuando quise mostrar una nueva zona con más caracteres, sucedió lo siguiente:

introducir la descripción de la imagen aquí

La celda con la zona Sudeste Cepillada aumentó su altura quedando más alta que las que le siguen a su derecha.

Este es el xml de la actividad:

    <LinearLayout
        android:layout_marginTop="10dp"
        android:layout_marginLeft="10dp"
        android:layout_marginRight="10dp"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">
        <LinearLayout
            android:orientation="vertical"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:id="@+id/layoutTabla"
            android:gravity="center">
            <ScrollView
                android:id="@+id/scrollvertical"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:scrollbars="vertical"
                android:layout_weight="1">
                <HorizontalScrollView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:id="@+id/scrollhorizontal"
                    android:scrollbars="horizontal"
                    android:layout_weight="1">
                    <LinearLayout
                        android:orientation="vertical"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content">
                        <TableLayout
                            android:id="@+id/tabla"
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:stretchColumns="1"
                            android:shrinkColumns="0">
                        </TableLayout>
                    </LinearLayout>
                </HorizontalScrollView>
            </ScrollView>
        </LinearLayout>
    </LinearLayout>

Esta es la clase Tabla:

public class Tabla {
    // Variables de la clase

    private TableLayout tabla;          // Layout donde se pintará la tabla
    private ArrayList<TableRow> filas;  // Array de las filas de la tabla
    private Activity actividad;
    private Resources rs;
    private int FILAS, COLUMNAS;        // Filas y columnas de nuestra tabla

    /**
     * Constructor de la tabla
     * @param actividad Actividad donde va a estar la tabla
     * @param tabla TableLayout donde se pintará la tabla
     */
    public Tabla(Activity actividad, TableLayout tabla)
    {
        this.actividad = actividad;
        this.tabla = tabla;
        rs = this.actividad.getResources();
        FILAS = COLUMNAS = 0;
        filas = new ArrayList<TableRow>();
    }

    /**
     * Añade la cabecera a la tabla
     * @param recursocabecera Recurso (array) donde se encuentra la cabecera de la tabla
     */
    public void agregarCabecera(int recursocabecera)
    {
        TableRow.LayoutParams layoutCelda;
        TableRow fila = new TableRow(actividad);
        TableRow.LayoutParams layoutFila = new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT, TableRow.LayoutParams.WRAP_CONTENT);
        fila.setLayoutParams(layoutFila);

        String[] arraycabecera = rs.getStringArray(recursocabecera);
        COLUMNAS = arraycabecera.length;

        for(int i = 0; i < arraycabecera.length; i++)
        {
            TextView texto = new TextView(actividad);
            layoutCelda = new TableRow.LayoutParams(obtenerAnchoPixelesTexto(arraycabecera[i]), TableRow.LayoutParams.WRAP_CONTENT);
            texto.setText(arraycabecera[i]);
            texto.setGravity(Gravity.CENTER_HORIZONTAL);
            texto.setTextAppearance(actividad, R.style.estilo_celda);
            texto.setBackgroundResource(R.drawable.tabla_celda_cabecera);
            texto.setLayoutParams(layoutCelda);
            fila.addView(texto);
        }
        tabla.addView(fila);
        filas.add(fila);
        FILAS++;
    }

    /**
     * Agrega una fila a la tabla
     * @param elementos Elementos de la fila
     */
    public void agregarFilaTabla(ArrayList<String> elementos)
    {
        TableRow.LayoutParams layoutCelda;
        TableRow.LayoutParams layoutFila = new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT, TableRow.LayoutParams.WRAP_CONTENT);
        TableRow fila = new TableRow(actividad);
        fila.setLayoutParams(layoutFila);

        for(int i = 0; i< elementos.size(); i++)
        {
            TextView texto = new TextView(actividad);
            texto.setText(String.valueOf(elementos.get(i)));
            texto.setGravity(Gravity.CENTER_HORIZONTAL);
            texto.setTextAppearance(actividad, R.style.estilo_celda);
            texto.setBackgroundResource(R.drawable.tabla_celda);
            layoutCelda = new TableRow.LayoutParams(obtenerAnchoPixelesTexto(texto.getText().toString()), TableRow.LayoutParams.WRAP_CONTENT);
            texto.setLayoutParams(layoutCelda);
            fila.addView(texto);
        }
        tabla.addView(fila);
        filas.add(fila);
        FILAS++;
    }

    /**
     * Elimina una fila de la tabla
     * @param indicefilaeliminar Indice de la fila a eliminar
     */
    public void eliminarFila(int indicefilaeliminar)
    {
        if( indicefilaeliminar > 0 && indicefilaeliminar < FILAS )
        {
            tabla.removeViewAt(indicefilaeliminar);
            FILAS--;
        }
    }

    /**
     * Devuelve las filas de la tabla, la cabecera se cuenta como fila
     * @return Filas totales de la tabla
     */
    public int getFilas()
    {
        return FILAS;
    }

    /**
     * Devuelve las columnas de la tabla
     * @return Columnas totales de la tabla
     */
    public int getColumnas()
    {
        return COLUMNAS;
    }

    /**
     * Devuelve el número de celdas de la tabla, la cabecera se cuenta como fila
     * @return Número de celdas totales de la tabla
     */
    public int getCeldasTotales()
    {
        return FILAS * COLUMNAS;
    }

    /**
     * Obtiene el ancho en píxeles de un texto en un String
     * @param texto Texto
     * @return Ancho en píxeles del texto
     */
    private int obtenerAnchoPixelesTexto(String texto)
    {
        Paint p = new Paint();
        Rect bounds = new Rect();
        p.setTextSize(50);

        p.getTextBounds(texto, 0, texto.length(), bounds);
        return bounds.width();
    }
}

Y así es como cargo los datos:

private void listaPreciosPapa() {//método que nos trae los precios
    //stringrquest para traer los datos del php
    //lo ideal sería parsear el array
    StringRequest stringRequest = new StringRequest(Request.Method.POST, "url",
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    try {//try para atrapar errores si es que los hay
                        JSONArray jsonArray = new JSONArray(response);//creamos un array que dibuja los datos del php
                        for (int i = 0; i < jsonArray.length(); i++) {//ciclo para ya saben qué
                            JSONObject jsonObject1 = jsonArray.getJSONObject(i);//creamos un JSON objeto
                            //le agregamos los campos pertinentes, requisito funciona: nombre de los campos de la bd
                            String zona = jsonObject1.getString("nombreZona");
                            String premin = jsonObject1.getString("precioMinimo");
                            String premax = jsonObject1.getString("precioMaximo");
                            String prom = jsonObject1.getString("promedio");

                            //probando la tabla
                            Tabla tabla = new Tabla(ListaPreciosActivity.this, (TableLayout)findViewById(R.id.tabla));
                            tabla.agregarCabecera(R.array.cabecera_tabla);
                            ArrayList<String> elementos = new ArrayList<String>();
                            zona = zona.replaceAll(" ", "\n");
                            elementos.add(zona);
                            elementos.add(premax);
                            elementos.add(premin);
                            elementos.add(prom);
                            tabla.agregarFilaTabla(elementos);
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();//captamos el error
                    }
                }
            }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            error.printStackTrace();
        }
    });//same bug, different error
    RequestQueue requestQueue = Volley.newRequestQueue(ListaPreciosActivity.this); //esto ya fue explicado
    requestQueue.add(stringRequest);
}

¿Alguien me puede decir como hago para que se mantenga el alto?

3
  • 1
    Los elementos de las celdas los estas creando dinamicamente
    – Jorgesys
    el 15 ene. 2021 a las 18:00
  • Sí, es una tabla dinámica el 18 ene. 2021 a las 12:29
  • se deve conservar los valores de una cadena el 19 ene. 2021 a las 11:23

1 respuesta 1

2
+100

Prueba ajustando el parámetro height cuando usas TableRow.LayoutParams() en el método agregarFilaTabla (ya que es allí donde se ingresa el ancho y alto), dale un tamaño fijo.

Ejemplo de la modificación:

/**
 * Agrega una fila a la tabla
 * @param elementos Elementos de la fila
 */
public void agregarFilaTabla(ArrayList<String> elementos)
{
    TableRow.LayoutParams layoutCelda;
    TableRow.LayoutParams layoutFila = new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT, TableRow.LayoutParams.WRAP_CONTENT);
    TableRow fila = new TableRow(actividad);
    fila.setLayoutParams(layoutFila);

    for(int i = 0; i< elementos.size(); i++)
    {
        TextView texto = new TextView(actividad);
        texto.setText(String.valueOf(elementos.get(i)));
        texto.setGravity(Gravity.CENTER_HORIZONTAL);
        texto.setTextAppearance(actividad, R.style.estilo_celda);
        texto.setBackgroundResource(R.drawable.tabla_celda);


// En esta línea yo puse un 100 para probar
        layoutCelda = new TableRow.LayoutParams(obtenerAnchoPixelesTexto(texto.getText().toString()), 100);
        texto.setLayoutParams(layoutCelda);
        fila.addView(texto);
    }
    tabla.addView(fila);
    filas.add(fila);
    FILAS++;
}

Una solución alternativa también podría ser usando setShrinkAllColumns(boolean) que en este caso te serviría para ver las columnas encogibles.

Aquí puedes ver ejemplos del método mencionado, el cambio en este caso seria cuando defines tu tabla:

this.tabla = tabla;
this.tabla.setShrinkAllColumns(true);

Espero te funcione. Saludos ;)

2
  • Lo probé, pero no ha funcionado tan bien. Pues, según el dispositivo se altera. Ejemplo: en Motorolas, la tabla se ve de manera correcta pero en Xiaomi no el 19 ene. 2021 a las 14:07
  • 1
    Agregué una solución alternativa que podrías probar o incluso combinar ambas soluciones ;)
    – Israel-ICM
    el 19 ene. 2021 a las 15:09

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge you have read our privacy policy.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.