为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

跃然一笑 2019-10-28 14:19:01
我有一段代码,其中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>
查看完整描述

3 回答

?
慕哥9229398

TA贡献1877条经验 获得超6个赞

对于以编程方式填充并希望获取索引的任何人,您可能会注意到,当您返回到活动/片段并重新添加这些单选按钮时,checkedId会更改。解决该问题的一种方法是使用索引设置标签:


    for(int i = 0; i < myNames.length; i++) {

        rB = new RadioButton(getContext());

        rB.setText(myNames[i]);

        rB.setTag(i);

        myRadioGroup.addView(rB,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();

        }

    });


查看完整回答
反对 回复 2019-10-28
  • 3 回答
  • 0 关注
  • 800 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信