安卓:添加两个文本视图编程 [英] Android: Add two text views programmatically
问题描述
我想添加视图编程的线性布局。
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);
}
首先,我只是加入了informationsView,一切工作正常。还加入了线查看后对接,它具有以下错误崩溃:
First, I have only added the informationsView, and everything worked fine. Butt after adding also the line-View, it crashed with the following error:
java.lang.IllegalStateException:指定的孩子已经有一个父。你必须先调用removeView()孩子的父母。
java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
所以,我想addView(视图V,INT指数),但它具有相同的消息崩溃...
So I tried addView(View v, int index), but it crashed with the same message...
有人来过的解决方案?
谢谢, 马丁
推荐答案
由于gpmoo7说你需要创建每次在循环新视图
As gpmoo7 said you need to create every time a new view in the loop
@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);
}
}
这篇关于安卓:添加两个文本视图编程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!