将TableRow动态添加到TableLayout的上方

时间:2018-04-10 06:48:39

标签: android view add tablelayout tablerow

我想将TableRow动态添加到TableLayout以上。我用吹码:

在我的活动中:

TableLayout table = (TableLayout)ChatActivity.this.findViewById(R.id.tblChats);
        for(int i = 1; i < 10; ++i)
        {
            TableRow row = (TableRow)LayoutInflater.from(ChatActivity.this).inflate(R.layout.chat_row, null);
            ((TextView)row.findViewById(R.id.attrib_name)).setText("A");
            ((TextView)row.findViewById(R.id.attrib_value)).setText(i + "");
            table.addView(row);
        }
        table.requestLayout();

chat_row.xml:

<?xml version="1.0" encoding="utf-8"?>

<TableRow xmlns:android="http://schemas.android.com/apk/res/android">

    <TextView android:id="@+id/attrib_name"
        android:textStyle="bold"/>

    <TextView android:id="@+id/attrib_value"
        android:gravity="right"
        android:textStyle="normal"/>

</TableRow>

如您所知,这些代码会在TableRow的底部添加TableLayout

有没有办法将其添加到TableLayout的上方?

2 个答案:

答案 0 :(得分:1)

是的,您可以在表格布局中添加行作为运行时。 使用下面的代码如chart.xml

<?xml version="1.0" encoding="utf-8"?>   
<TableLayout 

xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/tblChats"
android:layout_width="match_parent"
android:layout_height="match_parent">  </TableLayout>

并进行如下活动..

公共类ChartActivity扩展了AppCompatActivity {

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.chart_layout);
    TableLayout table = findViewById(R.id.tblChats);
    for (int i = 0; i < 5; i++) {

        TableRow row = new TableRow(this);
        TableRow.LayoutParams lp = new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT);
        row.setLayoutParams(lp);
        TextView textView = new TextView(this);
        textView.setText("Name" + " " + i);
        EditText editText = new EditText(this);
        row.addView(textView);
        table.addView(row, i);
    }

}

}

答案 1 :(得分:0)

根据Android Team的回答,我意识到我必须改变这一行:

table.addView(row);

到此:

table.addView(row, 0);