1

我在广播组中创建了 2 个组,其中一个问你踢足球好吗?另一个关于篮球的。如果它们很好,我给了 3 分,我想计算我的程序中的总分,但我不能。我需要帮助

private void addListenerOnButton() {
    final RadioGroup football = (RadioGroup) findViewById(R.id.radioGroup1);
    Button calc = (Button) findViewById(R.id.diabetriskbutton1);
    final RadioGroup basketball = (RadioGroup) findViewById(R.id.radioGroup2);
    calc.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View arg0) {
            int IDfootball = football.getCheckedRadioButtonId();
            RadioButton football = (RadioButton) findViewById(IDfootball);
            if (IDfootball == R.id.item1yes) {
                int scorefootball = 3;

            } else if (IDfootball == R.id.item1no) { 
                int scorefootball = 2;

            } 

            int IDbasketball = basketball.getCheckedRadioButtonId();
            RadioButton basketball = (RadioButton) findViewById(IDbasketball);
            if (IDbasketball == R.id.item1yes) {
                int scorebasketball = 3;

            } else if (IDbasketball == R.id.item1no) { 
                int scorebasketball = 2;

            } 
            scoretotal = scorefootball + scorebasketball ;


        }
    });

}`  
4

1 回答 1

1

尝试删除这些行。我认为您的编译器将 RadioGroup football|basketball 变量与您的 onClick 方法中的相同局部变量混淆了。

我也认为它们是不必要的,因为它们在声明后从未使用过。(您已经将从 getCheckedRadioButtonId() 获得的 ID 与 R.id.itemYes|No 进行比较

        RadioButton football = (RadioButton) findViewById(IDfootball);

        RadioButton basketball = (RadioButton) findViewById(IDbasketball);

还有一点。您在 if 和 else 块中声明了 scorefootball 和 scorebasketball。编译器不会在它们各自的块之外看到这些变量。此行将引发错误:

        scoretotal = scorefootball + scorebasketball;

请在外面声明它们:

        int scorefootball = 2;//default value
        int scorebasketball = 2;//default value

        ...

        if (IDfootball == R.id.item1yes) {
            scorefootball = 3;

        } else if (IDfootball == R.id.item1no) { 
            scorefootball = 2;

        } 

        ...

        if (IDbasketball == R.id.item1yes) {
            scorebasketball = 3;

        } else if (IDbasketball == R.id.item1no) { 
            scorebasketball = 2;

        }

        scoretotal = scorefootball + scorebasketball ;

您也可以发布您的xml吗?我想知道您为什么要将来自不同 RadioGroups 的 getCheckedRadioButtonId 获得的 ID 与相同的 R.id.item1Yes|No 进行比较

于 2013-08-23T02:50:20.147 回答