繁体   English   中英

启动时将数据分配给TableLayout会使应用程序实用地崩溃

[英]Assigning Data to TableLayout Pragmatically Crashes app when launching

我在XML中有一个表格布局,其中有一行并具有三个textview。 从数组动态解析表中的数据,但是当我启动应用程序时会崩溃。 这是我的代码

TableLayout historyEntries = (TableLayout)findViewById(R.id.DataTable);
        historyEntries.setStretchAllColumns(true);
        historyEntries.bringToFront();
        for(int i = 0; i < dataArray.length; i++){
            TableRow tr =  (TableRow) findViewById(R.id.datarow);
            TextView c1 = (TextView) findViewById(R.id.TextView1);
            TextView c2 = (TextView) findViewById(R.id.TextView2);
            TextView c3 = (TextView) findViewById(R.id.TextView3);
            c1.setText(dataArray[i]);
            c2.setText(String.valueOf(dataArray[i]));
            c3.setText(String.valueOf(dataArray[i]));
            tr.addView(c1);
            tr.addView(c2);
            tr.addView(c3);
            historyEntries.addView(tr);
        }

错误

java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.

一个视图可以只有一个父视图。 根据findViewById调用判断,您的一个或所有视图可能都有父视图。 如果您的视图已经在活动中膨胀,只需删除以下行:

tr.addView(c1);
tr.addView(c2);
tr.addView(c3);
historyEntries.addView(tr);

否则,如果要添加更多行,则可以使用TableRowTextView创建单独的布局文件:

for (int i = 0; i < dataArray.length; i++){
    View v = LayoutInflater.from(context).inflate(R.layout.your_table_row, historyEntries, false);
    TableRow tr =  (TableRow) v.findViewById(R.id.datarow);
    TextView c1 = (TextView) v.findViewById(R.id.TextView1);
    TextView c2 = (TextView) v.findViewById(R.id.TextView2);
    TextView c3 = (TextView) v.findViewById(R.id.TextView3);
    c1.setText(dataArray[i]);
    c2.setText(String.valueOf(dataArray[i]));
    c3.setText(String.valueOf(dataArray[i]));
    historyEntries.addView(tr);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM