如何处理活动中动态多个片段的内容



我正在创建一个简单的考试问题应用程序。 这就是为什么我根据问题动态创建多个片段的原因。 该片段包含用于问题的文本视图和用于选项的 4 个单选按钮。活动中有一个按钮用于清除选择(如果选择了答案)。 我为此创建了接口并将该方法实现为一个片段,并尝试取消选中所有单选按钮,但该方法正在调用,但单选按钮大部分时间仍处于选中状态,很少取消选中。我没有得到确切的快乐请帮助。

当我重新检查所有内容时,当我连续选择 8 个问题中的 8 个选项并开始从第一个片段中取消选中每个选项时,我发现了一件事。 当我在片段的第 0 个位置并单击按钮时,它会取消选中复选框,但是当我滚动到下一个片段(1st)并单击按钮时,它分别取消选中第二个位置片段 第二个取消选中第三个, 第 3 次取消选中第 4 次,第 4 次取消检查第 5 次,第 5 次取消检查 5 次无所事事,第 6 次取消检查第 7 次。请告诉我如何解决这个问题。

代码为波纹管,

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;
}}

或者请建议我是否有任何替代选项来做同样的事情。提前谢谢。

尝试在OnAttach()片段方法中使用此代码。

最新更新