Get selected radio button id placed in navigation

2019-09-10 02:10发布

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..

2条回答
相关推荐>>
2楼-- · 2019-09-10 02:46

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;
    }
}
查看更多
别忘想泡老子
3楼-- · 2019-09-10 03:00

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);
查看更多
登录 后发表回答