-1

我在適配器單選按鈕創建如下:然後在RadioGroup中的自定義適配器創建單選按鈕

@Override 
protected void onSaveInstanceState(Bundle outState) { 
    outState.putParcelableArrayList("test", listItems); 
    super.onSaveInstanceState(outState); 
} 

檢索在onCreate

@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的狀態保存物品適配器方法。

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

你的運氣如何? – Chisko

回答

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();