我想动态添加一些视图。
LinearLayout mDescriptionLayout = (LinearLayout)findViewById(R.id.descriptionLayout);
LayoutInflater inflater = (LayoutInflater)getSystemService(LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate (R.layout.bonus_info_item, null,false);
TextView counter = (TextView) view.findViewById(R.id.counter);
TextView descriptionText = (TextView) view.findViewById(R.id.descriptionText);
String [] s = {"","A","B", "C","D"};
for (int i = 1; i < 5; i++){
counter.setText(String.valueOf(i));
descriptionText.setText(s[i]);
mDescriptionLayout.addView(view);
}
这是我的main.xml
,我想在LinearLayout
(@id/descriptionLayout
)
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fillViewport="true">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/days"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="12sp"/>
<LinearLayout
android:id="@+id/descriptionLayout"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="@id/bonusCardTitleText"
android:orientation="vertical">
</LinearLayout>
</RelativeLayout>
</ScrollView>
我不明白这里的问题是我无法添加视图动态,而且我总是遇到此错误。
Caused by: java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
at android.view.ViewGroup.addViewInner(ViewGroup.java:3339)
at android.view.ViewGroup.addView(ViewGroup.java:3210)
at android.view.ViewGroup.addView(ViewGroup.java:3155)
at android.view.ViewGroup.addView(ViewGroup.java:3131)
答案 0 :(得分:1)
正如错误所说,
The specified child already has a parent. You must call removeView() on the child's parent first.
您正尝试将子View
添加到父级,并且该子级已经拥有父级(在for loop
的第一次迭代之后)。每次声明和初始化View
内的for loop
或每次调用remove()
都应该修复它。我不确定您是否尝试多次添加此layout
,但如果是这样,那么您可以尝试
for (int i = 1; i < 5; i++)
{
View view = inflater.inflate (R.layout.bonus_info_item, null,false);
TextView counter = (TextView) view.findViewById(R.id.counter);
TextView descriptionText = (TextView) view.findViewById(R.id.descriptionText);
counter.setText(String.valueOf(i));
descriptionText.setText(s[i]);
mDescriptionLayout.addView(view);
}
另一种方式是拨打mDescriptionLayout.removeView(view);
,但我认为你不想在你的情况下这样做。通过View
每次迭代初始化一个新的loop
可以解决您的问题。
答案 1 :(得分:1)
您要向TextView
多次添加相同的LinearLayout
个对象。您需要为每个项目创建TextView
的新实例。
for (int i = 1; i < 5; i++){
View view = inflater.inflate (R.layout.bonus_info_item, null,false);
TextView counter = (TextView) view.findViewById(R.id.counter);
TextView descriptionText = (TextView) view.findViewById(R.id.descriptionText);
counter.setText(String.valueOf(i));
descriptionText.setText(s[i]);
mDescriptionLayout.addView(view);
}