How to create a multiple column table view in andr

2020-07-22 19:36发布

问题:

I'm developping an android application. For that I need to have a dynamic tableView. I'm using TableLayout for that which is available in android. But I couldn't find a way to have multiple columns in my tableView. Any option please?

回答1:

I don't know if I fully understand your question, but here:

@Override
public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    TableLayout tableLayout = new TableLayout(getApplicationContext());
    TableRow tableRow;
    TextView textView;

    for (int i = 0; i < 4; i++) {
        tableRow = new TableRow(getApplicationContext());
        for (int j = 0; j < 3; j++) {
            textView = new TextView(getApplicationContext());
            textView.setText("test");
            textView.setPadding(20, 20, 20, 20);
            tableRow.addView(textView);
        }
        tableLayout.addView(tableRow);
    }
    setContentView(tableLayout);
}

This code creates TableLayout with 3 columns and 4 rows. Basically you can have TableLayout declared in XML file, then setContentView to XML, and use findViewById to find your TableLayout. Only TableRow and it's children have to be done in java code.



回答2:

You can add as many column as you want on design view. All you have to do is to put any View element you want to show as a column bettwen TablaRow tags.

<TableLayout>
  <TableRow>
    <TextView></TextView> // That's a column
    <ImageView></ImageView>  // That's other column
    ....

    <Other views></Other views> // That's the last column
  </TableRow>
 </TableLayout>