Tengo una vista hecha de TableLayout, TableRow and TextView. Quiero que se vea como una cuadrícula. Necesito obtener la altura y el ancho de esta cuadrícula. Los métodos getHeight()y getWidth()siempre devuelven 0. Esto sucede cuando formateo la cuadrícula dinámicamente y también cuando uso una versión XML.
¿Cómo recuperar las dimensiones de una vista?
Aquí está mi programa de prueba que utilicé en Debug para verificar los resultados:
import android.app.Activity;
import android.os.Bundle;
import android.widget.TableLayout;
import android.widget.TextView;
public class appwig extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.maindemo); //<- includes the grid called "board"
int vh = 0;
int vw = 0;
//Test-1 used the xml layout (which is displayed on the screen):
TableLayout tl = (TableLayout) findViewById(R.id.board);
tl = (TableLayout) findViewById(R.id.board);
vh = tl.getHeight(); //<- getHeight returned 0, Why?
vw = tl.getWidth(); //<- getWidth returned 0, Why?
//Test-2 used a simple dynamically generated view:
TextView tv = new TextView(this);
tv.setHeight(20);
tv.setWidth(20);
vh = tv.getHeight(); //<- getHeight returned 0, Why?
vw = tv.getWidth(); //<- getWidth returned 0, Why?
} //eof method
} //eof class
getHeight()y getWidth()después del ciclo de vida de la Actividad ha pedido a las opiniones que se midan, en otras palabras, hacer este tipo de cosas onResume()y eso es todo. No debe esperar que un objeto aún no diseñado sepa sus dimensiones, ese es el truco completo. No hay necesidad de la magia sugerida a continuación.
getHeight()/Width()en onResume()no dió> 0 valor para mí.