首页 > 解决方案 > 我如何知道在 Android Studio 中选择了哪个单选按钮

问题描述

我有 3 个单选按钮,一旦我单击其中任何一个按钮,它应该更新 2 个文本视图。名称的一个文本视图和价格的其他文本视图。当我单击单选按钮时,名称会更新,但我面临如何从数组中获取商品价格的问题。每个单选按钮都有不同的定价。

代码:

     pizzaSizeRadioGroup = (RadioGroup) findViewById(R.id.radioGroup);
        pizzaSizeRadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
//                Radio button checked
                sizeSelect = (RadioButton) findViewById(checkedId);
                selectedSize.setText(sizeSelect.getTag().toString());

//                how to display the price from array
                sizePrice = array_price_list[].getItem_price();
                totalPriceDisplay.setText(sizePrice);

            }
        });

标签: javaandroidandroid-studiotextviewradio-button

解决方案


你可以实现 switch Radiogroup checkedId

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

    pizzaSizeRadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() 
    {
        public void onCheckedChanged(RadioGroup group, int checkedId) {
            switch(checkedId){
                case R.id.radio0://Radio button id
                    // do operations specific to this selection
                    break;
                case R.id.radio1://Radio button id
                    // do operations specific to this selection
                    break;
                case R.id.radio2://Radio button id
                    // do operations specific to this selection
                    break;
            }   
        }
    });

或选中选中的单选按钮

     int selectedId = pizzaSizeRadioGroup.getCheckedRadioButtonId();

推荐阅读