我想动态地添加一些 View 。
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
) 中添加这个膨胀 View
<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>
我不明白这里有什么问题,我无法动态添加 View ,而且我总是遇到这个错误。
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)
最佳答案
如错误所述,
指定的 child 已经有一个 parent 。您必须先对 child 的 parent 调用 removeView()。
您正在尝试将子 View
添加到父项,而该子项已经有一个父项(在您的 for 循环
的第一次迭代之后)。在 for 循环
中声明和初始化 View
或每次调用 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);
但我认为您不想在您的情况下这样做。通过 loop
的每次迭代初始化一个新的 View
应该可以解决您的问题。
关于android - 如何动态添加此 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17596692/