将 TableRow 动态添加到 TableLayout 的上方

Dynamically add TableRow to above of TableLayout

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

在我的 activity:

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>

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

有什么办法可以加到TableLayout的上面吗?

是的,您可以在 table 布局中添加行作为运行时。 使用下面的代码,如 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>

并使 activity 如下所示..

public class ChartActivity extends 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);
        }

    }
}

根据 Android 团队的回答,我意识到我必须更改此行:

table.addView(row);

对此:

table.addView(row, 0);