【问题标题】:get settext value from radio button从单选按钮获取 settext 值
【发布时间】:2019-09-11 22:02:56
【问题描述】:

如何从单选按钮获取值到字符串,因为我想将它作为文本保存到我的火力库中。我将把这个单选按钮实现为带有条件的饮料类别。但我想先试试。我认为这是错误的。有什么建议么?谢谢。

RadioGroup radioGroup;
RadioButton radioButton,radio1,radio2,radio3;
EditText textView;
Button button;

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_input_drinks);


    radioGroup=findViewById(R.id.radiogroup);
    textView=findViewById(R.id.textspinner);
    radio1=findViewById(R.id.radio_one);
    radio2=findViewById(R.id.radio_two);
    radio3=findViewById(R.id.radio_three);
    button=findViewById(R.id.btn_test);

    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if(radio1.isChecked()) {
                textView.setText(radioButton.getText());
            }else if(radio2.isChecked()){
                textView.setText(radioButton.getText());
            }if(radio3.isChecked()){
                textView.setText(radioButton.getText());
            }

        }
    });

}

【问题讨论】:

  • 您在 radioButton 而不是相应的 RadioButton 上获取文本。改变它,你会得到你想要的结果。

标签: java android radio-button


【解决方案1】:
if(radio1.isChecked()) {
            textView.setText(radio1.getText());
        }else if(radio2.isChecked()){
            textView.setText(radio2.getText());
        }if(radio3.isChecked()){
            textView.setText(radio3.getText());
        }

编辑您的代码

【讨论】:

  • 尝试动态的方式来做到这一点@MrMD
【解决方案2】:

这是实现这一目标的有效方法

radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(RadioGroup radioGroup, int i) {
            int selectedId = radioGroup.getCheckedRadioButtonId();

            //no need to call each of radiobutton id 

            radiobutton = (RadioButton) findViewById(selectedId);
            if(selectedId==-1){

            }
            else{
                textView.setText(drinkbutton.getText());
            }
        }
    });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-01-06
    • 2013-06-14
    • 2018-10-07
    • 2014-12-05
    • 2017-02-06
    • 2016-11-09
    • 2012-01-04
    • 2019-05-11
    相关资源
    最近更新 更多