Android - The radio group creation and event handler mechanism

 This is very simple example for creating check box in android application. Here I have created the new android project and I have modified the main.xml file with following code.


    
        
 
        
 
        
 

    
    
    

 Here I have created the one radio grop and I have added some games names as option. Now I am going to display the selected game with using TextView. For getting this effect I have modified the main activity java file with following code.

import android.app.Activity;
import android.os.Bundle;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.TextView;

public class RadioBoxActivity extends Activity implements OnCheckedChangeListener{
    /** Called when the activity is first created. */
       RadioGroup radioGroup;
       TextView textView;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        radioGroup = (RadioGroup)findViewById(R.id.radioGroup1);
        textView = (TextView)findViewById(R.id.textView1);
        radioGroup.setOnCheckedChangeListener(this);
    }

       @Override
       public void onCheckedChanged(RadioGroup group, int checkedId) {
              // TODO Auto-generated method stub
              int myCheckedRadioId = radioGroup.getCheckedRadioButtonId();
              String displayStr = "";
              if(myCheckedRadioId == R.id.radio0) {
                     displayStr = "My favorite game is Cricket" ;
              }
              else if(myCheckedRadioId == R.id.radio1) {
                     displayStr = "My favorite game is Hockey" ;
              }
              else {
                     displayStr = "My favorite game is Football" ;
              }
              textView.setText(displayStr);
       }
}

 Here I have taken the radio group handle and text view handle through using findViewById method. For adding action listener to radio group, I have implemented the OnCheckedChangeListener interface and I have override the onCheckedChanged() method. In this method I have get the selected radio id using getCheckedRadioButtonId() method. After that I have used this selected id value for finding selected game through comparing this selected id value with all the radio id value. At last I have changed the text view value with computed string. The filnal result should be like this only.






Comments