Search code examples
androidstaticintradio-group

Check RadioGroup checked or not and get value to static int



  1. GOAL 1: When click the button, if there isn't any radiobutton checked, it will warning user by Toast; if a radiobutton checked, it will take user to new activity (or do smt up on you).

First

public class hanh1_2 extends Activity{

public static int ButID;
@Override

Second, set the button action:

final Button ok2 = (Button) findViewById(R.id.ok2);
    ok2.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {
            // Set int of ButID = checkedradiobuttonID
                            //If ButID = -1 --> there isn't bt checked
            int ButID = tieng.getCheckedRadioButtonId();
            if (ButID == -1){
                Toast.makeText(hanh1_2.this, "Check a butt pls", Toast.LENGTH_SHORT).show();
            }
            else {
            Intent intent2 = new Intent(hanh1_2.this,hanh1_3.class);
            startActivity(intent2);
            }
        }
    });

Meaningless to advanced, but may helpful for some newbie like me :)


Solution

    1. Have a look at the Form stuff tutorial on the Android dev site. You can supply an OnClickListener to all RadioButtons and keep track of the one selected (if any).

      private OnClickListener radio_listener = new OnClickListener() {
          public void onClick(View v) {
              // Perform action on clicks
              RadioButton rb = (RadioButton) v;
              Toast.makeText(HelloFormStuff.this, rb.getText(), Toast.LENGTH_SHORT).show();
          }
      };
      

      Alternatively, you can potentially use the RadioGroup's getCheckedRadioButtonId() method.

    2. As illustrated in one of the other answers: pass the int value as an extra to the Intent you use to launch your second Activity:

      // In first activity
      Intent i = new Intent(FirstActivity.this, SecondActivity.class);
      i.putInt("selected_index", selectedIndex);
      startActivity(i);
      
      // In second activity
      int selectedIndex = getIntent().getExtras().getInt("selected_index");