[英]How Handle If all RadioGroup Checked?
我有60個項目的RecyclerView。 該項目具有RadioGroup,並且在此具有兩個單選按鈕
我也使用DataBinding
我有FabButton,如果單擊“是”,我將進入“結果活動”,但是如果所有RadioGroup已選中:)
我寫這樣的代碼,它可以工作,但是有一些錯誤...當我單擊第60個項目時,即使不檢查59個項目,我也將進入結果活動。
為什么呢?
這是我的代碼:
//Select All Radio Group
public boolean allSelected() {
boolean allChecked = true;
for (Question question : questions) {
allChecked = question.getSelectedId() != 0;
}
return allChecked;
}
//Card background if Uncheck the question
private void showHideErrorBackground(boolean show) {
for (Question question : questions) {
question.setShowErrorBackground(show);
}
mbtiQuestAdapter.notifyDataSetChanged();
}
並且喜歡它,我使用This Method:
if (allSelected()) {
Intent intent = new Intent(MbtiQuestionActivity.this, ResultActivity.class);
startActivity(intent);
} else {
snack bar =
Snackbar.make(coordinator, R.string.check_all_ques_err, Snackbar.LENGTH_SHORT)
.setAction(R.string.snack_find_unchecked_ques, new View.OnClickListener() {
@Override
public void onClick(View view) {
showHideErrorBackground(true);
}
});
ViewCompat.setLayoutDirection(snackbar.getView(), ViewCompat.LAYOUT_DIRECTION_RTL);
snackbar.show();
}
Question.java(模型數據)
public class Question extends BaseQuestion {
private int selectedId;
private boolean showErrorBackground;
@Bindable
public void setShowErrorBackground(boolean showErrorBackground) {
this.showErrorBackground = showErrorBackground;
notifyPropertyChanged(BR.showErrorBackground);
}
@Bindable
public int getSelectedId() {
return selectedId;
}
public void setSelectedId(int selectedId) {
this.selectedId = selectedId;
notifyPropertyChanged(BR.selectedId);
}
public boolean isShowErrorBackground() {
return showErrorBackground;
}
}
謝謝你幫我
在allSelected
方法內部,直接將變量allChecked
的值設置為循環中當前問題的檢查狀態。 這意味着只要檢查了最后一個問題, allChecked
的值將為true
。 同樣,如果不進行檢查,則始終為false
,但這與您的應用程序行為一致,因此您可能不會遇到任何問題。
相反,您應該使用AND操作,如下所示:
allChecked = allChecked && (question.getSelectedId() != 0);
由於如果未解決任何問題, for
循環應該中斷,因此您可以通過執行以下操作來優化代碼:
for (Question question : questions) {
if (question.getSelectedId() == 0) {
allChecked = false;
break;
}
}
在此代碼中,一旦遇到未回答的問題, allChecked
將設置為false
,其余的問題將被跳過。 您無需在每次迭代中使用AND操作。
此方法返回的布爾值只是最后一個question.getSelectedId()的值。
public boolean allSelected() {
boolean allChecked = true;
for (Question question : questions) {
allChecked = question.getSelectedId() != 0;
}
return allChecked;
}
嘗試這個 :
public boolean allSelected() {
for (Question question : questions) {
if (question.getSelectedId() == 0)
return false;
}
return true;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.