Eu tenho uma visão composta TableLayout, TableRow and TextView. Quero que pareça uma grade. Preciso obter a altura e a largura dessa grade. Os métodos getHeight()e getWidth()sempre retornam 0. Isso acontece quando eu formato a grade dinamicamente e também quando uso uma versão XML.
Como recuperar as dimensões para uma vista?
Aqui está o meu programa de teste que usei no Debug para verificar os 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()e getWidth()depois que o ciclo de vida da atividade solicitar que os pontos de vista se medam, em outras palavras, faça esse tipo de coisa onResume()e pronto. Você não deve esperar que um objeto ainda não definido conheça suas dimensões, esse é o truque. Não há necessidade da mágica sugerida abaixo.
getHeight()/Width()em onResume()não deu> 0 valor para mim.