Pergunta

Estou lutando contra o terrível sistema de layout do Android. Estou tentando conseguir uma mesa para preencher a tela (simples, certo?), Mas é ridiculamente difícil.

Consegui trabalhar de alguma forma em XML assim:

<?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>

No entanto, não posso fazer com que funcione em Java. Eu tentei um milhão de combinações dos Layoutparams, mas nada funciona. Este é o melhor resultado que tenho que apenas preenche a largura da tela, não a 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, a documentação do Android não ajuda. Alguém tem alguma ideia?

Foi útil?

Solução 2

Finalmente descobriu como fazer isso. Desistiu TableLayout e apenas usado na horizontal LinearLayoutestá dentro de um vertical. A chave crítica é definir o peso. Se você especificar FILL_PARENT Mas com o peso padrão, ele não 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);

Outras dicas

Existem dois erros na discussão acima.

  1. É possível definir programaticamente o peso especificando TableLayout.LayoutParams e TableRow.LayoutParams e usando o construtor apropriado, por exemplo

    TableLayout.LayoutParams rowInTableLp = new TableLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT, 1.0f);
    
  2. Um widget deve ter o LayoutParams de seus pais. Portanto, as linhas devem usar TableLayout.LayoutParams.

Isso fornece a seguinte versão de trabalho do seu 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);

Graças ao comentário de Romain Guy no fórum do desenvolvedor do Android para a solução.

Encontrei a resposta: aparentemente, é o peso do layout que faz funcionar e não há como defini -lo de Java. Caramba.

Ver Como posso obter um tablelayout Android para preencher o pai no modo paisagem?

Você nunca define os parâmetros de layout da linha ou do botão, enquanto no XML publicado você faz isso ... Chegue os detalhes do loops para definir os parâmetros do layout da linha e os parâmetros de layout do botão do que deve fornecer o mesmo resultado que o seu XML.

Para definir o TableLayout LayoutParams, esperamos logicamente usar o tablelayout.layoutparams, mas você receberá um erro de elenco informando que o tablelayout.layoutparams não pode ser lançado em FreAlayout.layoutParams.

Portanto, você deve usar o Framelayout.LayoutParams, se deseja definir programaticamente o TableLayout Properties. Por exemplo:

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);
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top