【问题标题】:Get selected radio button id placed in navigation view获取放置在导航视图中的选定单选按钮 ID
【发布时间】:2016-03-22 07:26:15
【问题描述】:

我在这样的抽屉布局的导航视图中选择了单选组

 <android.support.design.widget.NavigationView
     app:headerLayout="@layout/header"
     app:menu="@menu/drawer">

 <RadioGroup>
      <RadioButton/>
      <RadioButton/>
 </RadioGroup>

     </android.support.design.widget.NavigationView>

我想获取选定的单选按钮文本或 ID,但我没有得到任何日志或 Toast,也没有错误..

获取选中单选按钮的代码:

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

我知道我可以通过使用自定义列表视图来实现这一点。但是如何让它工作..

【问题讨论】:

  • 给一个单选按钮设置一个标签然后根据位置获取上面代码中的标签,即rg中的radiobutton1.setTag(1)和radioButton2.setTag(2)。 setOnCheckedChangeListener 只是把 if condition (radiobutton1.getTag==1){// do the stuff} else {//do another stuff};

标签: android radio-group drawerlayout navigationview


【解决方案1】:

示例 - 就像 developer.android 中提供的一样

你只需要像下面这样在 xml 文件中添加属性 onClick

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

在代码部分处理 onClick 事件

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

【讨论】:

  • 但是如果我在 if(checked) 部分写日志或吐司,我什么也得不到..
【解决方案2】:

抱歉,无法在评论中回答。试试这个:

navigationView.getMenu().findItem(R.id.radioButtonId);

这将返回您的 RadioButton 的 ID。

编辑:

你可以这样做吗:

RadioButton radio = (RadioButton)navigationView.findViewById(R.id.radioButtonId);

【讨论】:

  • 你能不能这样做:RadioButton radio = (RadioButton)navigationView.findViewById(R.id.radioButtonId);
猜你喜欢
  • 2014-01-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-09-22
  • 1970-01-01
  • 2016-08-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多