web-dev-qa-db-ger.com

Android holt Wert aus dem ausgewählten Optionsfeld

Ich habe einen Code mit drei RadioButtons innerhalb einer RadioGroup. Ich möchte eine onCheckedListener setzen, die den Wert der RadioButton in einer Toast anzeigt. Was ich bisher bekommen habe, funktioniert jedoch nicht. Wie erhalte ich den Wert der RadioButton und zeige ihn in einer Toast an? Vielen Dank im Voraus, das ist mein 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();
            }
        });
    }
}

XML-Datei:

<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

Getestet und funktioniert. Überprüfen Sie 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

Wenn Sie bei der Auswahl eines der Optionsfelder etwas tun möchten (ohne einen zusätzlichen OK-Button oder etwas anderes zu haben), ist Ihr Code in Ordnung, wenig aktualisiert.

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

verwenden Sie einfach die Funktion getCheckedRadioButtonId (), um festzustellen, ob etwas markiert ist. Wenn -1 zurückgegeben wird, können Sie das Auftreten von Toast vermeiden

4
pailodze

Für jeden, der sich programmgesteuert auffüllt und nach einem Index sucht, stellen Sie möglicherweise fest, dass sich die checkedId ändert, wenn Sie zur Aktivität/zum Fragment zurückkehren und diese Optionsfelder erneut hinzufügen. Eine Möglichkeit, dies zu umgehen, besteht darin, ein Tag mit dem Index festzulegen:

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

Dann in Ihrem Hörer:

    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();

Hoffe das klappt. Sie können Ihre Ausgabe auf die oben beschriebene Weise in einen String konvertierengender.getCheckedRadioButtonId(); - gender ist die ID von 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

Radiogruppe in 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

Vielen Dank an Chris.

Das ist meine Lösung:

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();
    }