問題:我是否可以在兒童活動中反覆使用RadioButton對象?Android中重複使用單選按鈕
我有一個家長活動和一個兒童活動。在兒童活動中,我在UI中顯示了大量的單選按鈕。爲了提供從父母到孩子的數據綁定,我創建了一個包含RadioButton集合的類(如下所示)。爲了填充孩子的活動,我把這個類的引用傳遞給孩子,孩子將radioButtons分組成RadioGroups並顯示出來。我這樣做是因爲每個按鈕的檢查狀態現在都可以在父類中自動獲得,而不需要通過捆綁包傳輸任何數據。
public class GeneralAttribute{
Activity mThis;
public class Gender { // Mutually exclusive members
String categoryDesc = "Gender of user";
RadioButton isUnspecified = initRadioButton("Unspecified", true);
RadioButton isMale = initRadioButton("Male" , false);
RadioButton isFemale = initRadioButton("Female" , false);
} ;
<....more subclasses....>
RadioButton initRadioButton(String str, Boolean b) { // Factory
float cLayoutWeight = 0.5f;
RadioButton rb = new RadioButton(mThis);
rb.setText (str);
rb.setChecked(b);
rb.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, cLayoutWeight));
return rb;
}
GeneralAttribute(Activity localThis){ // Constructor
mThis = localThis;
gender = new Gender();
handedness = new Handedness();
location = new Location();
}
}
在父活動,我有:
public class Parent(...)
public GeneralAttribute mGeneralAttribute; // Member class of RadioButtons
public static SPIGestureLoggerActivity TopLevelActivity;// Reference to the parent activity
public void onCreate(Bundle savedInstanceState) {
TopLevelActivity = this; // Assign this to the reference
mGeneralAttribute = new GeneralAttribute(this); // Initialize the class of RBs
startActivity(child); // Start the child
在孩子的活動,我有這樣的:
radiogroup = new RadioGroup(this);
radiogroup.setOrientation(RadioGroup.VERTICAL);
radiogroup.addView(Parent.TopLevelActivity.mGeneralAttribute.gender.isUnspecified);
radiogroup.addView(Parent.TopLevelActivity.mGeneralAttribute.gender.isMale);
radiogroup.addView(Parent.TopLevelActivity.mGeneralAttribute.gender.isFemale);
Parent.TopLevelActivity.mGeneralAttribute.gender.isUnspecified.setChecked(true);
mLinearLayout.addView(radiogroup);
這工作得很好....在第一時間孩子活動顯示。第二次顯示時,我得到一個異常。 總之,這裏是一連串事件:
- 創建類的RadioButtons,
- 它們傳遞給孩子,
- 將它們添加到一個新的RadioGroup中
- 收集用戶的選擇
- 完成小孩活動(應該銷燬RadioGroups)
- 使用父數據,
- 再次啓動子活動,
- 嘗試將RadioButtons添加到新的RadioGroups ... ...異常。
我可以避免這個問題,如果我空類和重構它。但是,我想重新顯示從第一次查看和第二次查看所做出的選擇。
思路:
- 正在保存指針指向不存在的RadioGroups從第一視角的單選按鈕?
- 有沒有辦法在班級中的每個單選按鈕上重新分配視圖父級?
P.S.你可能會問爲什麼我不使用XML。首先,我將擁有100多個這些單選按鈕,我認爲通過XML進行管理將會非常痛苦。另一方面,我只是喜歡以編程方式處理這些事情。
太棒了!我正在尋找一個像clear()或setParent()這樣的方法。我沒有想到刪除。我現在就試一試。 – Hephaestus
太棒了。這解決了它!你剛剛驗證了半天的工作!我擔心我將不得不拋棄這個並重建它。謝謝! – Hephaestus
順便說一句,這種將視圖對象傳遞給子類的技術是否與衆不同?我看起來很奇怪,但它符合我的需求。 – Hephaestus