如何在 Android Studio 中将 RadioGroup 元素的 ID 转换为字符串?

下面的代码显示了 toast 中 RadioButton 的 id 以及按钮中的名称,但我想转换为字符串。


  radioGroup = (RadioGroup) findViewById(R.id.radioGroup);


    radioGroup.clearCheck();


    radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {

        @Override

        public void onCheckedChanged(RadioGroup group, int checkedId) {

            RadioButton rb = (RadioButton) group.findViewById(checkedId);

            if (null != rb && checkedId > -1) {


                Toast.makeText(activity.this, rb.getText(), Toast.LENGTH_SHORT).show();

           p1_button.setText(rb.getText());



            }


        }

    });

我想以字符串形式获取单选按钮的值。


繁星淼淼
浏览 340回答 2
2回答

哆啦的时光机

很简单,如果你想将值转换为字符串,你可以使用这样的toString()方法rb.getText().toString();你也可以使用这样的String.valueOf()方法String.valueOf(rb.getText);所以在你的情况下 p1_button.setText(rb.getText().toString());

繁星点点滴滴

实际上 rb.getText() 返回一个字符串。您可以将其值分配给字符串变量,例如String str=rb.getText();为了更安全:String str=""+rb.getText();在上面的行中,来自 rb.getText() 的值与 "" 连接(+ 用于连接字符串)。使用 ""+ 将 + 的 RHS 上的任何值转换为字符串要么String str=rb.getText().toString();现在 'str' 包含您要求的字符串值
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java