1
resposta

Como criar TableRow dinâmicas e suas Views filhas com IDs únicos?

Estou trabalhando em um projeto que preciso criar uma tabela. Nessa tabela terá alguns componentes clicaveis, cada um com seu comportamento específico. Preciso identificar individualmente cada um. Utilizei dois xmls para criar a tabela, sendo um layout com um componente TableLayout e outro layout com o "esqueleto" das linhas, o TableRow, assim consigo inflar esse layout e preencher os componentes já estilizados. Ficou mais ou menos assim:

tabela.xml:

<?xml version="1.0" encoding="utf-8"?>
<HorizontalScrollView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingTop="5dp">

    <ScrollView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:fillViewport="true"
        android:orientation="vertical">

        <TableLayout
            android:id="@+id/tabela"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content">

        </TableLayout>
    </ScrollView>
</HorizontalScrollView>

linha.xml

<?xml version="1.0" encoding="utf-8"?>
<TableRow xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/linha_tabela_tablerow"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/linha_tabela_texto"
        android:text="Algum texto"
        android:textSize="16sp"
        android:padding="10dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
</TableRow>

E gostaria de preencher essa tabela dinamicamente:

TableLayout tabela = (TableLayout) findViewById(R.id.tabela);

for (int i = 1; i < 5; i++) {
    View tr = getLayoutInflater().inflate(R.layout.linha, null, false);

    TextView txt= (TextView) tr.findViewById(R.id.linha_tabela_texto);
       txt.setText("Texto da linha");
    tabela.addView(tr, new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT, TableRow.LayoutParams.WRAP_CONTENT));
}

Até ai, blz. Mas eu preciso recuperar cada caixa de texto criada dentro de cada TableRow com o findViewById, eu não consego, já que todas as TextView terão o mesmo ID: linha_tabela_texto. Como faço para dinamizar isso? Fazer que cada componente dentro de um TableRow criado no looping tenha seu próprio id?

1 resposta

Erick, tudo bem ?

Dessa forma acho que o melhor jeito de você poder recuperar a view que quer é recuperando a atráves da tag.

Pois toda view tem o método setTag e getTag, você poderia colocar seu identificador quando for adicionar os componentes.

Quer mergulhar em tecnologia e aprendizagem?

Receba a newsletter que o nosso CEO escreve pessoalmente, com insights do mercado de trabalho, ciência e desenvolvimento de software