Search code examples
androidoncheckedchanged

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


Solution

  • 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.