我想製作一個測驗應用程序。到目前爲止,我有3個活動 - 家庭,測驗,得分。由於測驗活動包含多個等效的視圖(圖片標題,問題和4個答案按鈕),我做了一些閱讀,並決定 ViewPager
與FragmentStatePagerAdapter
顯示做伎倆。因此,我製作了一個xml
模板,並誇大了幾個測試視圖,並且這一切都看起來不錯,直到我開始處理用戶交互。如何在Android中正確使用ViewPager
我想模擬切換按鈕,每個問題只有一個正確的答案,所以選擇一個按鈕應該取消選擇前一個(如果有的話)。當按下按鈕時,我改變我的Question model
,然後我找到所有4個按鈕,並且重置他們的濾色器。然後我將該過濾器重新放回到我選定的按鈕上。要確定要更新哪個問題模型,我使用我在模板根視圖中設置的當前位置fragment
(在片段的onCreate中使用setTag
)。
這是我打電話給我的fragmets:
public Fragment getItem(int position) {
Question question = Repository.findById(position);
int correctAnswerBtnId;
switch (question.getCorrectAnswerIndex()) {
case 0: correctAnswerBtnId = R.id.quiz_answer_0_btn; break;
case 1: correctAnswerBtnId = R.id.quiz_answer_1_btn; break;
case 2: correctAnswerBtnId = R.id.quiz_answer_2_btn; break;
case 3: correctAnswerBtnId = R.id.quiz_answer_3_btn; break;
this.ACTIVITY_ROOT.setTag(question.getID());
Fragment fragment = new QuestionFragment();
Bundle args = new Bundle();
args.putSerializable(QuestionFragment.QUESTION, question);
fragment.setArguments(args);
return fragment;
}
我QuestionFragment onCreateView是按文件:
public View onCreateView(
LayoutInflater inflater,
ViewGroup container,
Bundle questionData) {
this.rootView = inflater.inflate(
R.layout.layout_question_template,
container,
false);
Bundle args = getArguments();
this.question = (Question) args.getSerializable(QuestionFragment.QUESTION);
populateInflatable();
rootView.findViewById(R.id.layout_question_template_root).setTag(this.question.getID());
return rootView;
}
在populateInflatable
我用this.rootView
來fintViewById
,並填充它我的問題數據。然後我改變一個按鈕的顏色,如果從問題中選擇了一個。
在按鈕點擊我打電話selectAnserButton
:
public void selectAnswerButton(View selectedButton) {
int questionId =
(int) this.activityRoot.findViewById(
R.id.layout_question_template_root).getTag(); //??
unSelectAllButtons();
changeColor(selectedButton);
Repository.findById(questionId).selectAnswer(selectedButton.getId());
}
凡unSelectAllButtons
代表的四個按鈕buttonToUnSelect.getBackground().clearColorFilter();
。和Repository
只是一個static
類與示例問題數據。
當我有更多的一個視圖時,這一切都非常錯誤。在每個片段上,我使用相同的視圖ID對相同的xml
進行膨脹,因爲我已經定義了它們。而且現在我明白了,要求findViewById
檢索不到一個,但是從我目前檢索到的那個Id的所有視圖,也從我的上一個和下一個fragment
中檢索。所以每次我想選擇我當前的fragment
的視圖,我也會修改上一個和下一個fragments
中的相同視圖。你可以想象這是如何產生問題的。這讓我覺得我有一個根本的錯誤,因爲我不認爲應該有更多的View
與ID
相同。
我真的不明白我應該如何使用ViewPager來做到這一點。在這一點上,我覺得我正在試圖製作一個木雕,但相反,我正在將這個框架劈成碎片。 ViewPager必須有更好的方法。
已解決:感謝Soo Chun Jung爲我指出了答案。總之,它爲我工作的是:
- 將我的
Question model
id傳遞給Bundle
的每個片段。 - 將每個片段存儲在
ArrayMap
內部,片段位置爲key
,片段爲value
。 - 從我的
selectAnswer
函數獲取每個單獨的片段現在很容易:首先獲取當前片段的位置,然後調用getter
函數,該函數返回當前位置上的片段。 - 既然我有片段,我可以輕鬆地更改它的按鈕,因爲它們保留爲專用字段,並分配在'onCreateView`方法中。
這將會是有用的,如果你能表現出[MCVE] –
'如何正確使用android' ViewPager - https://developer.android.com/reference/android/support/v4/view/ ViewPager.html& https://developer.android.com/training/animation/screen-slide.html –
此外,它聽起來像你需要了解RadioButton。 https://developer.android.com/guide/topics/ui/controls/radiobutton.html – Gary99