猿问

Android从选定的单选按钮获取价值

我有一段代码,其中RadioButton一个包含三个s RadioGroup。我想设置的onCheckedListener,将显示的值RadioButton的Toast。但是,到目前为止我没有得到任何结果。如何获取的值RadioButton并将其显示在中Toast?预先谢谢您,这是我的代码:


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档案:


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

 </RelativeLayout>


跃然一笑
浏览 801回答 3
3回答

慕哥9229398

对于以编程方式填充并希望获取索引的任何人,您可能会注意到,当您返回到活动/片段并重新添加这些单选按钮时,checkedId会更改。解决该问题的一种方法是使用索引设置标签:&nbsp; &nbsp; for(int i = 0; i < myNames.length; i++) {&nbsp; &nbsp; &nbsp; &nbsp; rB = new RadioButton(getContext());&nbsp; &nbsp; &nbsp; &nbsp; rB.setText(myNames[i]);&nbsp; &nbsp; &nbsp; &nbsp; rB.setTag(i);&nbsp; &nbsp; &nbsp; &nbsp; myRadioGroup.addView(rB,i);&nbsp; &nbsp; }然后在您的听众中:&nbsp; &nbsp; myRadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {&nbsp; &nbsp; &nbsp; &nbsp; @Override&nbsp; &nbsp; &nbsp; &nbsp; public void onCheckedChanged(RadioGroup group, int checkedId) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; RadioButton radioButton = (RadioButton) group.findViewById(checkedId);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; int mySelectedIndex = (int) radioButton.getTag();&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; });
随时随地看视频慕课网APP

相关分类

Java
Android
我要回答