当我选择单选按钮时,它应该提交答案并同时打开下一个活动。我怎样才能做到这一点?

时间:2017-01-11 17:23:41

标签: android radio-button android-sharedpreferences

我正在尝试做多选的简单测验应用程序。当我选择单选按钮时,单选按钮应该提交答案并打开下一个活动。在我的代码中有一个“提交”按钮。因此,首先选择单选按钮,然后单击提交按钮并拖动页面以打开另一页,但这没有用。我想做所有这些只需选择单选按钮。

 public class Question1 extends Fragment {
     RadioButton q1a2;
     Button btn1;

     @Override
     public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
         View v = inflater.inflate(R.layout.fragment_question1, null);
         return v;
     }

     public void onActivityCreated(Bundle savedInstanceState){
         super.onActivityCreated(savedInstanceState);
         q1a2 = (RadioButton)getView().findViewById(R.id.q1a2);
         btn1 =(Button)getView().findViewById(R.id.btn1);

         final SharedPreferences app_preferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
         btn1.setOnClickListener(new OnClickListener() {

             @Override
             public void onClick(View v) {
                 SharedPreferences.Editor editor = app_preferences.edit();
                 if(q1a2.isChecked()){
                     editor.putInt("answer_value", 1);
                 }else{
                     editor.putInt("answer_value", 0);
                 }

                 editor.commit();
             }
         });
      }
  }

2 个答案:

答案 0 :(得分:1)

不使用不同的单选按钮侦听器和提交按钮来显式单击单选按钮,而是使用带有单选按钮的radiogroup。然后使用RadioGroup.OnCheckedChangeListener获取单击单选按钮的id,并以相同的方法启动新活动。

以下示例代码:

RadioGroup radio = (RadioGroup) dialog.findViewById(R.id.radioGroup1);
        radio.setOnCheckedChangeListener(new OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {

                View radioButton = radio.findViewById(checkedId);
                int index = radio.indexOfChild(radioButton);

                switch (index) {
                case 0: // first button
                        break;
                case 1: // second button
                        break;
                    case 3: // third button
                        break;
                    case 4: // fourth button
                        break;
                }
            }
        }); 

答案 1 :(得分:1)

在您的视图xml中,您必须拥有RadioButton所在的RadioGroup。

RadioGroup yourRadioGroup = (RadioGroup) findViewById(R.id.yourRadioGroup);        
yourRadioGroup.setOnCheckedChangeListener(new OnCheckedChangeListener() 
{
    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        // Here you can find selected radio button Id.
        // On the basis of Radio Button you can decide it is selected or not

    }
});