it-swarm.dev

Android získává hodnotu z vybraných přepínačů

Mám kus kódu se třemi RadioButtons uvnitř RadioGroup. Chci nastavit onCheckedListener, které bude zobrazovat hodnotu RadioButton v Toast. To, co jsem zatím dostal, však nefunguje. Jak mohu získat hodnotu RadioButton a zobrazit ji v Toast? Děkuji předem, to je můj kód:

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

Soubor 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

Testováno a funkční. Kontrola toto

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

V případě, že chcete provést nějakou práci při výběru některého z přepínačů (aniž byste měli nějaké další tlačítko OK nebo tak něco), je váš kód v pořádku, málo aktualizovaný.

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

použijte funkci getCheckedRadioButtonId () k určení, zda je-li něco zaškrtnuto, je-li hodnota -1 vrácena, můžete se vyhnout zobrazování toastu

4
pailodze

Pro každého, kdo se programově zaplní a hledá index, můžete si všimnout, že checkId se změní při návratu k aktivitě/fragmentu a znovu přidáte tyto přepínače. Jedním ze způsobů, jak toho dosáhnout, je nastavit značku s indexem:

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

Pak ve vašem posluchači:

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

Doufám, že to funguje. Výstup můžete převést na řetězec výše uvedeným způsobem gender.getCheckedRadioButtonId(); - rod je id 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 v 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>

aktivita_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

Děkuji Chrisovi.

Toto je moje řešení:

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