Creating table layout and adding rows from the code behind in Android

拜拜、爱过 提交于 2019-12-12 03:19:19

问题


I need to create a table layout and add rows dynamically from Java code behind. I have already read questions here, but they are mentioning to add table rows in an already created table layout (from xml).

I need to create the table layout as well as add data to it dynamically. Can anyone please provide some inputs?

For now, I have linear layout code in place which adds button from code behind one below the other, I need to place it under a tabular format now.


回答1:


To add three buttons to TableRow use the code below

TableLayout tableLayout = new TableLayout(this);
    for (int i = 0; i < 10; i++)
    {
        TableRow tableRow = new TableRow(this);
        Button button = new Button(this);
        button.setText("1");
        tableRow.addView(button);

        button = new Button(this);
        button.setText("2");
        tableRow.addView(button);

        button = new Button(this);
        button.setText("3");
        tableRow.addView(button);

        tableLayout.addView(tableRow);
    }
    setContentView(tableLayout);



回答2:


Add the code below to your onCreate() method in you Activity class:

@Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    TableLayout tableLayout = new TableLayout(this);
    for (int i = 0; i < 5; i++)
    {
        TableRow tableRow = new TableRow(this);

        for (int j = 0; j < 3; j++)
        {
            Button button = new Button(this);
            button.setText(""+j);
            tableRow.addView(button);
        }

        tableLayout.addView(tableRow);
    }
    setContentView(tableLayout);
}

The code will add five rows with three buttons with the text 1 to 3 to the table.




回答3:


Add the following code below your init() method:

for (int i = 0; i < GetGlobal.totalrow; i++) {
            TableRow tbrow = new TableRow(this);
            // tbrow.setLayoutParams(tableRowParams);
            TextView t1v = new TextView(this);

            t1v.setText(JSONParser.heading[i].replace('"', ' '));
            t1v.setBackgroundResource(R.drawable.diamond_detail1);
            t1v.setPadding(5, 3, 5, 3);
            t1v.setMinHeight(50);
            t1v.setTypeface(Typeface.SERIF);
            t1v.setTextColor(Color.parseColor("#FFFFFF"));
            t1v.setGravity(Gravity.FILL);
            tbrow.addView(t1v);


来源:https://stackoverflow.com/questions/33009529/creating-table-layout-and-adding-rows-from-the-code-behind-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!