Java Android:以编程方式添加两个文本视图
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3210599/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Android: Add two text views programmatically
提问by Martin
I am trying to add Views to a linear layout programmatically.
我正在尝试以编程方式将视图添加到线性布局。
LinearLayout layout = (LinearLayout) findViewById(R.id.info);
String [] informations = topOffer.getInformations();
TextView informationView;
View line = new View(this);
line.setLayoutParams(new LayoutParams(1, LayoutParams.FILL_PARENT));
line.setBackgroundColor(R.color.solid_history_grey);
for (int i = 0; i < informations.length; i++) {
informationView = new TextView(this);
informationView.setText(informations[i]);
layout.addView(informationView, 0);
layout.addView(line, 1);
}
First, I have only added the informationsView, and everything worked fine. Butt after adding also the line-View, it crashed with the following error:
首先,我只添加了信息视图,一切正常。Butt 在添加 line-View 后,它崩溃并出现以下错误:
java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
java.lang.IllegalStateException: 指定的孩子已经有一个父母。您必须首先在孩子的父级上调用 removeView()。
So I tried addView(View v, int index), but it crashed with the same message...
所以我尝试了 addView(View v, int index),但它以相同的消息崩溃了......
Has somebody a solution?
有人有解决方案吗?
Thanks, Martin
谢谢,马丁
回答by mmathieum
You can't add the same child view multiple times in the same parent view. You need to create a new view or inflate a new view every time.
您不能在同一个父视图中多次添加同一个子视图。您每次都需要创建一个新视图或膨胀一个新视图。
回答by vsm
As gpmoo7 said you need to create every time a new view in the loop
正如 gpmoo7 所说,您每次都需要在循环中创建一个新视图
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.linear);
LinearLayout layout = (LinearLayout) findViewById(R.id.linear);
String[] informations = new String[] { "one", "two", "three" };
TextView informationView;
for (int i = 0; i < informations.length; i++) {
View line = new View(this);
line.setLayoutParams(new LayoutParams(1, LayoutParams.MATCH_PARENT));
line.setBackgroundColor(0xAA345556);
informationView = new TextView(this);
informationView.setText(informations[i]);
layout.addView(informationView, 0);
layout.addView(line, 1);
}
}