web-dev-qa-db-fra.com

Android obtient la valeur du bouton radio sélectionné

J'ai un morceau de code avec trois RadioButtons dans un RadioGroup. Je veux définir une onCheckedListener qui affichera la valeur de la RadioButton dans une Toast. Cependant, ce que j'ai obtenu jusqu'à présent ne fonctionne pas. Comment obtenir la valeur de la variable RadioButton et l'afficher dans une variable Toast? Merci d'avance, voici mon code:

import Android.os.Bundle;
import Android.app.Activity;
import Android.view.Menu;
import Android.view.View;
import Android.widget.RadioButton;
import Android.widget.RadioGroup;
import Android.widget.RadioGroup.OnCheckedChangeListener;
import Android.widget.Toast;

public class MainActivity extends Activity {

    RadioGroup rg;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        RadioGroup rg = (RadioGroup) findViewById(R.id.radioGroup1);
        final String value =
            ((RadioButton)findViewById(rg.getCheckedRadioButtonId()))
            .getText().toString();

        rg.setOnCheckedChangeListener(new OnCheckedChangeListener() {
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                Toast.makeText(getBaseContext(), value, Toast.LENGTH_SHORT).show();
            }
        });
    }
}

Fichier XML:

<RelativeLayout 
    xmlns:Android="http://schemas.Android.com/apk/res/Android"
    xmlns:tools="http://schemas.Android.com/tools"
    Android:layout_width="match_parent"
    Android:layout_height="match_parent"
    Android:paddingBottom="@dimen/activity_vertical_margin"
    Android:paddingLeft="@dimen/activity_horizontal_margin"
    Android:paddingRight="@dimen/activity_horizontal_margin"
    Android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <RadioGroup
        Android:id="@+id/radioGroup1"
        Android:layout_width="wrap_content"
        Android:layout_height="wrap_content"
        Android:layout_alignParentTop="true"
        Android:layout_centerHorizontal="true"
        Android:layout_marginTop="152dp" >

        <RadioButton
            Android:id="@+id/radio0"
            Android:layout_width="wrap_content"
            Android:layout_height="wrap_content"
            Android:text="Choose 1" />

         <RadioButton
            Android:id="@+id/radio1"
            Android:layout_width="wrap_content"
            Android:layout_height="wrap_content"
            Android:text="Choose 2" />

         <RadioButton
            Android:id="@+id/radio2"
            Android:layout_width="wrap_content"
            Android:layout_height="wrap_content"
            Android:text="Choose 3" />
     </RadioGroup>
 </RelativeLayout>
66
user2673161

Testé et fonctionnel. Vérifiez this

import Android.app.Activity;
import Android.os.Bundle;
import Android.view.View;
import Android.view.View.OnClickListener;
import Android.widget.Button;
import Android.widget.RadioButton;
import Android.widget.RadioGroup;
import Android.widget.Toast;

public class MyAndroidAppActivity extends Activity {

  private RadioGroup radioGroup;
  private RadioButton radioButton;
  private Button btnDisplay;

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    addListenerOnButton();

  }

  public void addListenerOnButton() {

    radioGroup = (RadioGroup) findViewById(R.id.radio);
    btnDisplay = (Button) findViewById(R.id.btnDisplay);

    btnDisplay.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {

                // get selected radio button from radioGroup
            int selectedId = radioGroup.getCheckedRadioButtonId();

            // find the radiobutton by returned id
            radioButton = (RadioButton) findViewById(selectedId);

            Toast.makeText(MyAndroidAppActivity.this,
                radioButton.getText(), Toast.LENGTH_SHORT).show();

        }

    });

  }
}

xml

<RadioGroup
        Android:id="@+id/radio"
        Android:layout_width="wrap_content"
        Android:layout_height="wrap_content" >

        <RadioButton
            Android:id="@+id/radioMale"
            Android:layout_width="wrap_content"
            Android:layout_height="wrap_content"
            Android:text="@string/radio_male" 
            Android:checked="true" />

        <RadioButton
            Android:id="@+id/radioFemale"
            Android:layout_width="wrap_content"
            Android:layout_height="wrap_content"
            Android:text="@string/radio_female" />

    </RadioGroup>
115
chinna_82

Au cas où, si vous souhaitez effectuer un travail sur la sélection de l'un des boutons radio (sans aucun bouton OK supplémentaire ou quelque chose), votre code est correct, mis à jour peu.

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        RadioGroup rg = (RadioGroup) findViewById(R.id.radioGroup1);

        rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() 
        {
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch(checkedId){
                    case R.id.radio0:
                        // do operations specific to this selection
                        break;
                    case R.id.radio1:
                        // do operations specific to this selection
                        break;
                    case R.id.radio2:
                        // do operations specific to this selection
                        break;
                }   
            }
        });
    }
}
43
Kaps
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
       @Override
       public void onCheckedChanged(RadioGroup group, int checkedId)
       {
           radioButton = (RadioButton) findViewById(checkedId);
           Toast.makeText(getBaseContext(), radioButton.getText(), Toast.LENGTH_SHORT).show();
       }
   }
   );
7
Turuu

il suffit d’utiliser la fonction getCheckedRadioButtonId () pour déterminer si un élément est coché, si -1 est renvoyé, vous pouvez éviter d’afficher du pain grillé.

4
pailodze

Si vous remplissez un programme et cherchez à obtenir un index, vous remarquerez peut-être que le témoin CheckId change lorsque vous revenez à l'activité/au fragment et que vous rajoutez ces boutons radio. Une façon de contourner ce problème consiste à définir une balise avec l’index:

    for(int i = 0; i < myNames.length; i++) {
        rB = new RadioButton(getContext());
        rB.setText(myNames[i]);
        rB.setTag(i);
        myRadioGroup.addView(rB,i);
    }

Puis dans votre auditeur:

    myRadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(RadioGroup group, int checkedId) {
            RadioButton radioButton = (RadioButton) group.findViewById(checkedId);
            int mySelectedIndex = (int) radioButton.getTag();
        }
    });
2
Chris
Radiogroup rgteam;
String team;
rgteam.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {
            RadioButton rb= (RadioButton) findViewById(checkedId);
            team = rb.getText().toString();
        }
    });
1
saigopi
int genid=gender.getCheckedRadioButtonId();
RadioButton radioButton = (RadioButton) findViewById(genid);
String gender=radioButton.getText().toString();

J'espère que ça marche. Vous pouvez convertir votre sortie en chaîne de la manière indiquée ci-dessus .gender.getCheckedRadioButtonId(); - genre est l'id de RadioGroup.

1
Gowtham
mRadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
    @Override
    public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {
        RadioButton radioButton = (RadioButton)group.findViewById(checkedId);
    }
});
0
Dwivedi Ji

RadioGroup en XML

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:Android="http://schemas.Android.com/apk/res/Android"
    Android:layout_width="match_parent" Android:layout_height="match_parent">
<RadioGroup
    Android:layout_width="match_parent"
    Android:layout_height="wrap_content"
    Android:orientation="vertical">
    <RadioButton
        Android:layout_width="wrap_content"
        Android:layout_height="wrap_content"
        Android:text="Java"/>

    </RadioGroup>
</RelativeLayout>

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:Android="http://schemas.Android.com/apk/res/Android"
    Android:layout_width="match_parent" Android:layout_height="match_parent">
    <TextView
        Android:layout_width="wrap_content"
        Android:layout_height="wrap_content"
        Android:layout_marginTop="150dp"
        Android:layout_marginLeft="100dp"
        Android:textSize="18dp"
        Android:text="Select Your Course"
        Android:textStyle="bold"
        Android:id="@+id/txtView"/>
<RadioGroup
    Android:layout_width="match_parent"
    Android:layout_height="wrap_content"
    Android:orientation="vertical"
    Android:id="@+id/rdGroup"
    Android:layout_below="@+id/txtView">
    <RadioButton
        Android:id="@+id/rdbJava"
        Android:layout_width="wrap_content"
        Android:layout_height="wrap_content"
        Android:padding="10dp"
        Android:layout_marginLeft="100dp"
        Android:text="Java"
        Android:onClick="onRadioButtonClicked"/>
    <RadioButton
        Android:id="@+id/rdbPython"
        Android:layout_width="wrap_content"
        Android:layout_height="wrap_content"
        Android:padding="10dp"
        Android:layout_marginLeft="100dp"
        Android:text="Python"
        Android:onClick="onRadioButtonClicked"/>
    <RadioButton
        Android:id="@+id/rdbAndroid"
        Android:layout_width="wrap_content"
        Android:layout_height="wrap_content"
        Android:padding="10dp"
        Android:layout_marginLeft="100dp"
        Android:text="Android"
        Android:onClick="onRadioButtonClicked"/>
    <RadioButton
        Android:id="@+id/rdbAngular"
        Android:layout_width="wrap_content"
        Android:layout_height="wrap_content"
        Android:padding="10dp"
        Android:layout_marginLeft="100dp"
        Android:text="AngularJS"
        Android:onClick="onRadioButtonClicked"/>
</RadioGroup>
    <Button
        Android:id="@+id/getBtn"
        Android:layout_width="wrap_content"
        Android:layout_height="wrap_content"
        Android:layout_marginLeft="100dp"
        Android:layout_below="@+id/rdGroup"
        Android:text="Get Course" />
</RelativeLayout>

MainActivity.Java

import Android.support.v7.app.AppCompatActivity;
import Android.os.Bundle;
import Android.view.View;
import Android.widget.Button;
import Android.widget.RadioButton;
import Android.widget.Toast;

public class MainActivity extends AppCompatActivity {
    RadioButton Android, Java, angular, python;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Android = (RadioButton)findViewById(R.id.rdbAndroid);
        angular = (RadioButton)findViewById(R.id.rdbAngular);
        Java = (RadioButton)findViewById(R.id.rdbJava);
        python = (RadioButton)findViewById(R.id.rdbPython);
        Button btn = (Button)findViewById(R.id.getBtn);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String result = "Selected Course: ";
                result+= (Android.isChecked())?"Android":(angular.isChecked())?"AngularJS":(Java.isChecked())?"Java":(python.isChecked())?"Python":"";
                Toast.makeText(getApplicationContext(), result, Toast.LENGTH_SHORT).show();
            }
        });
    }
    public void onRadioButtonClicked(View view) {
        boolean checked = ((RadioButton) view).isChecked();
        String str="";
        // Check which radio button was clicked
        switch(view.getId()) {
            case R.id.rdbAndroid:
                if(checked)
                str = "Android Selected";
                break;
            case R.id.rdbAngular:
                if(checked)
                str = "AngularJS Selected";
                break;
            case R.id.rdbJava:
                if(checked)
                str = "Java Selected";
                break;
            case R.id.rdbPython:
                if(checked)
                str = "Python Selected";
                break;
        }
        Toast.makeText(getApplicationContext(), str, Toast.LENGTH_SHORT).show();
    }
}
0
Mr_Moradi

Merci beaucoup à Chris.

Ceci est ma solution:

RadioGroup radgroup_opcionesEventos = null;


 private static String[] arrayEventos = {
            "Congestión", "Derrumbe", "Accidente"
    };
@Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps);
        radgroup_opcionesEventos = (RadioGroup)findViewById(R.id.rg_opciones_evento);
        int i=0;//a.new.ln
        for(String evento : arrayEventos) {
            //RadioButton nuevoRadio = crearRadioButton(evento);//a.old.ln
            RadioButton nuevoRadio = crearRadioButton(evento,i);//a.new.ln
            radgroup_opcionesEventos.addView(nuevoRadio,i);
        }

        RadioButton primerRadio = (RadioButton) radgroup_opcionesEventos.getChildAt(0);
        primerRadio.setChecked(true);
}

private RadioButton crearRadioButton(String evento, int n)
    {
        //RadioButton nuevoRadio = new RadioButton(this);//a.old.ln
        RadioButton nuevoRadio = new RadioButton(getApplicationContext());//a.new.ln

        LinearLayout.LayoutParams params = new RadioGroup.LayoutParams(
                RadioGroup.LayoutParams.WRAP_CONTENT,
                RadioGroup.LayoutParams.WRAP_CONTENT);
        nuevoRadio.setLayoutParams(params);
        nuevoRadio.setText(evento);
        nuevoRadio.setTag(evento);
        return nuevoRadio;
    }


@Override
    protected void onResume()
    {
        radgroup_opcionesEventos.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                RadioButton radioButton = (RadioButton) group.findViewById(checkedId);
                //int mySelectedIndex = (int) radioButton.getTag();
                String mySelectedIndex = radioButton.getTag().toString();
            }
        });
        super.onResume();
    }