变量在内部类中访问,需要声明为final

时间:2018-04-07 13:25:55

标签: android button onclick

我试图按一个按钮将其值与其他变量进行比较。在onClick方法中,我得到一个错误,说在内部类中访问变量,需要声明为final。问题是变量应该被改变,所以我不能把它变成最终的。我怎样才能解决这个问题?这是我的代码:

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class GameActivity extends Activity implements View.OnClickListener {

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

        int partA = 9;
        int partB = 9;
        int correctAnswer = partA * partB;
        int wrongAnswer1 = correctAnswer++;
        int wrongAnswer2 = correctAnswer--;

        TextView textObjectA = (TextView)findViewById(R.id.textPartA);
        TextView textObjectB = (TextView)findViewById(R.id.textPartB);

        Button buttonObjectChoice1 = (Button)findViewById(R.id.buttonChoice1);
        Button buttonObjectChoice2 = (Button)findViewById(R.id.buttonChoice2);
        Button buttonObjectChoice3 = (Button)findViewById(R.id.buttonChoice3);


        buttonObjectChoice1.setText("" + correctAnswer);
        buttonObjectChoice2.setText("" + wrongAnswer1);
        buttonObjectChoice3.setText("" + wrongAnswer2);    

        buttonObjectChoice1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                int answerGiven = Integer.parseInt("" + buttonObjectChoice1.getText());

                if(correctAnswer==answerGiven)  {

                }
            }
        });
        buttonObjectChoice1.setOnClickListener(this);
        buttonObjectChoice1.setOnClickListener(this);


    }

    public void onClick(View view)  {}

}

2 个答案:

答案 0 :(得分:1)

两种方法:

  1. 制作buttonObjectChoice1 final

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        ...
        final Button buttonObjectChoice1 =(Button)findViewById(R.id.buttonChoice1);
        ...
        buttonObjectChoice1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
    
               int answerGiven = Integer.parseInt("" + buttonObjectChoice1.getText());
    
                ...
            }
        });
    }
    
  2. 在运行时转换视图:

    buttonObjectChoice1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            final Button btn = (Button)v;
    
            int answerGiven = Integer.parseInt("" + btn.getText());
    
            ...
         }
    });
    
  3. 方法2的优点是,它将减少编译器生成访问器方法以访问buttonObjectChoice1对象的工作量。

答案 1 :(得分:0)

尝试将变量声明为类的私有字段,并在方法中相应地更新它。