Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Listener for RadioButton for change Fragments

I need to switch fragments at the application with tabs (RadioButton). What is the event listener should I use? onClick or onCheckedChanged? If it is possible to example

like image 868
Gend Avatar asked Dec 13 '25 17:12

Gend


1 Answers

For single RadioButton you can use OnClickListener as follows:

         OnClickListener listener = new OnClickListener() {
               @Override
               public void onClick(View v) {
                      RadioButton rb = (RadioButton) v;
                      Toast.makeText(your_Activity.this, rb.getText(), 
                      Toast.LENGTH_SHORT).show();
               }
         };

         RadioButton rb1 = (RadioButton) findViewById(R.id.radioButton1);
         rb1.setOnClickListener(listener);

In case of RadioGroup you need to use OnCheckedChangeListener as follows :

    RadioGroup radioGroup = (RadioGroup) findViewById(R.id.yourRadioGroup);

    radioGroup.setOnCheckedChangeListener(new OnCheckedChangeListener() 
    {
        public void onCheckedChanged(RadioGroup group, int checkedId) {
            // checkedId is the RadioButton selected

            switch(checkedId) {
                  case R.id.radioButton1:
                       // switch to fragment 1                
                       break;
                  case R.id.radioButton2:
                      // Fragment 2
                      break;
                  case R.id.radioButton3:
                      // Fragment 3
                      break;
            }   
        }
    }); 

The onCheckedChanged callback receives the ID of the newly checked button in the checkedId parameter.

like image 175
Ritesh Gune Avatar answered Dec 15 '25 07:12

Ritesh Gune