【发布时间】:2026-01-12 19:55:02
【问题描述】:
我正在创建一个简单的考试问题应用程序。这就是我根据问题动态创建多个片段的原因。 该片段包含用于问题的 TextView 和用于选项的 4 个 RadioButtons。活动中有一个按钮可以清除选择(如果选择了答案)。 我为此创建了 interface 并将该方法实现到一个片段中并尝试取消选中所有单选按钮,但该方法正在调用但单选按钮大部分时间仍处于选中状态,并且很少取消选中。我不知道到底发生了什么,请帮忙。
当我重新检查所有事情时,我发现一件事,当我连续选择 8 个问题的 8 个选项并开始从第一个片段中取消选中每个选项时。当我在片段的第 0 个位置并单击按钮时,它会取消选中复选框,但是当我滚动到下一个片段(第一个)并单击按钮时,它会分别取消选中第 2 个位置片段第 2 个取消选中第 3 个,第 3 个取消选中第 4 个, 4th 取消选中 5th, 5th 没有任何反应, 6th 取消选中 7th。请告诉我如何解决这个问题。
代码如下,
FragmentManager fm = getSupportFragmentManager();
viewPager.setAdapter(new FragmentStatePagerAdapter(fm) {
public int getCount() {
return titles.size();
}
public Fragment getItem(int position) {
QuestionsFragment fragment = new QuestionsFragment();
fragment.setText(titles.get(position), position); //
return fragment;
}
public int getItemPosition(Object item) {
QuestionsFragment fragment = (QuestionsFragment)item;
String title = fragment.getText();
int position = titles.indexOf(title);
if (position >= 0) {
return position;
} else {
return POSITION_NONE;
}
}
});
界面:
public interface ClearSelection {
public void reamoveAllSelections();}
片段:
public final class QuestionsFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.question_fragment, null);
textView = view.findViewById(R.id.tv_question);
rbOptionOne = view.findViewById(R.id.rb_option_one);
rbOptionTwo = view.findViewById(R.id.rb_option_two);
rbOptionThree = view.findViewById(R.id.rb_option_three);
rbOptionFour = view.findViewById(R.id.rb_option_four);
((QuestionsActivity)getActivity()).clearSelectionApi(new ClearSelection() {
@Override
public void reamoveAllSelections() {
if (rbOptionOne.isChecked()) {
rbOptionOne.setChecked(false);
}
if (rbOptionTwo.isChecked()) {
rbOptionTwo.setChecked(false);
}
if (rbOptionThree.isChecked()) {
rbOptionThree.setChecked(false);
}
if (rbOptionFour.isChecked()) {
rbOptionFour.setChecked(false);
}
}
});
return view;
}}
或者,如果有任何替代选项可以做同样的事情,请建议我。提前致谢。
【问题讨论】: