我在适配器单选按钮中创建如下:
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View vi = convertView;
if (vi == null) {
LayoutInflater li = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
vi = li.inflate(R.layout.row, null);
} else {
vi = convertView;
}
final ItemFormRow item = items.get(position);
v = new ViewHolder();
v.answerGroup = (RadioGroup) vi.findViewById(R.id.answerGroup);
v.answerGroup.removeAllViews();
for (int i=0; i<answers.size(); i++) {
RadioButton rb = answers.get(i);
v.answerGroup.addView(rb);
}
return vi;
}
我使用onSaveInstanceState
为活动中的适配器保存项目:
@Override
protected void onSaveInstanceState(Bundle outState) {
outState.putParcelableArrayList("test", listItems);
super.onSaveInstanceState(outState);
}
然后在onCreate
方法中检索。
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState != null) {
listItems = savedInstanceState.getParcelableArrayList("test");
}
....
}
当我旋转设备时,(stop on line: v.answerGroup.addView(rb))
会出现异常:
java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
如果我删除了 - onSaveInstanceState
,那么一切正常,并且不会抛出异常。
我需要保存状态。 你能帮我解决一下吗?
答案 0 :(得分:0)
试试这个:
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder vh = new ViewHolder();
if (convertView == null) {
LayoutInflater li = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = li.inflate(R.layout.row, parent, false);
// Do all necessary findViewById's here
convertView.setTag(vh);
} else {
vh = (ViewHolder) convertView.getTag();
}
// Not sure what you are trying to do here. But the above should solve (or at least mitigate) the issue
final ItemFormRow item = items.get(position);
vh.answerGroup = (RadioGroup) convertView.findViewById(R.id.answerGroup);
for (int i = 0; i < answers.size(); i++) {
RadioButton rb = answers.get(i);
vh.answerGroup.addView(rb);
}
return convertView;
}
我删除了您的View
变量,因为它不需要。
修改强>
也删除了这一行
vh.answerGroup.removeAllViews();