首页 > 解决方案 > 如何知道从哪个 Fragment 实例调用 setOnCheckedChangeListener?

问题描述

我有一个主要活动,我必须在每个屏幕中显示 12 个问题中的 3 个(保存在 sql 数据库中),并带有单选按钮 Yes 和 No 。所以我做了一个片段类,并在我的主要活动中调用了三次。在我的下一个按钮上,我创建了主类的意图。因此,我用一个片段在 4 个屏幕中填充了 12 个问题。

现在,当我按下单选按钮时,我想查看单击单选按钮的问题,然后计算分数(每个问题都有单独的分数。这也映射到我的 sqlite 数据库中针对每个问题)我该怎么做?

标签: android

解决方案


方法 1:创建 4 个片段。

public class Fragment1 extends Fragment {
    private RadioButton radioButton;
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        // radioButton.setOnCheckedChangeListener...
    }
}

public class Fragment2 extends Fragment {
    private RadioButton radioButton;
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        // radioButton.setOnCheckedChangeListener...
    }
}

public class Fragment3 extends Fragment {
    private RadioButton radioButton;
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        // radioButton.setOnCheckedChangeListener...
    }
}

public class Fragment4 extends Fragment {
    private RadioButton radioButton;
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        // radioButton.setOnCheckedChangeListener...
    }
}

方法 2:通过传递 4 个不同的整数包创建 1 个片段。

Bundle bundle1 = new Bundle();
bundle1.putInt("questions1" , 1);

Bundle bundle2 = new Bundle();
bundle2.putInt("questions2" , 2);

Bundle bundle3 = new Bundle();
bundle3.putInt("questions3" , 3);

Bundle bundle4 = new Bundle();
bundle4.putInt("questions4" , 4);

Fragment fragment = new QuestionsFragment();
fragment.setArguments(bundle1);

Fragment fragment = new QuestionsFragment();
fragment.setArguments(bundle2);

Fragment fragment = new QuestionsFragment();
fragment.setArguments(bundle3);

Fragment fragment = new QuestionsFragment();
fragment.setArguments(bundle4);

onCreateView用于QuestionsFragment获取Bundle bundle1 = getArguments();整数标志。


推荐阅读