问题
I have taken radio group in the navigation view of drawer layout like this
<android.support.design.widget.NavigationView
app:headerLayout="@layout/header"
app:menu="@menu/drawer">
<RadioGroup>
<RadioButton/>
<RadioButton/>
</RadioGroup>
</android.support.design.widget.NavigationView>
I want to get the selected radio button text or id but I am not getting any logs or Toast and no errors also..
Code for getting selected radio button:
rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
int pos=rg.indexOfChild(findViewById(checkedId));
Toast.makeText(MainActivity.this, "ID = "+String.valueOf(pos),
Toast.LENGTH_SHORT).show();
Log.e("",""+pos);
}
I know I can achieve this by using custom list view.. But how to get this working..
回答1:
Example - just like provided in developer.android
You just need to add attribute onClick in xml file like below
<?xml version="1.0" encoding="utf-8"?>
<RadioGroup xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<RadioButton android:id="@+id/radio_pirates"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/pirates"
android:onClick="onRadioButtonClicked"/>
<RadioButton android:id="@+id/radio_ninjas"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/ninjas"
android:onClick="onRadioButtonClicked"/>
</RadioGroup>
Handle the onClick event in code part
public void onRadioButtonClicked(View view) {
// Is the button now checked?
boolean checked = ((RadioButton) view).isChecked();
// Check which radio button was clicked
switch(view.getId()) {
case R.id.radio_pirates:
if (checked)
// Pirates are the best
break;
case R.id.radio_ninjas:
if (checked)
// Ninjas rule
break;
}
}
回答2:
Sorry couldn't answer in comment. Try this:
navigationView.getMenu().findItem(R.id.radioButtonId);
this will return Id of your RadioButton
.
Edit:
Can you do something like this:
RadioButton radio = (RadioButton)navigationView.findViewById(R.id.radioButtonId);
来源:https://stackoverflow.com/questions/36148421/get-selected-radio-button-id-placed-in-navigation-view