错误:无法为最终变量赋值

Goj*_*rry 0 java android final button

我正面临Android Studio的以下问题

public class MainActivity extends AppCompatActivity {

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

    final int numeroHomem = 0;
    final int numeroMulher = 0;
    final int numeroPessoas = 0;

    final TextView campoTexto = (TextView) findViewById(R.id.pessoas);
    final Button botaoHomem = (Button) findViewById(R.id.homem);
    final Button botaoMulher = (Button) findViewById(R.id.mulher);
    final Button botaoReset = (Button) findViewById(R.id.reset);

     botaoHomem.setOnClickListener(new Button.OnClickListener(){
        public void onClick(View v){
            numeroHomem++;
            numeroPessoas++;
            String mensagem = Integer.toString(numeroPessoas);
            campoTexto.setText("Total: " + mensagem + " pessoas");
            botaoHomem.setText(Integer.toString(numeroHomem));
         }
     });
 } }
Run Code Online (Sandbox Code Playgroud)

错误:无法为最终变量numeroHomem
错误赋值:无法为最终变量numeroPessoas赋值

Ali*_*Ali 8

final初始化后无法更改变量

你可以做的是在你的班级中声明你的变量而不是 onCreate()

public class MainActivity extends AppCompatActivity {

    int numeroHomem = 0;
    int numeroMulher = 0;
    int numeroPessoas = 0;

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


      final TextView campoTexto = (TextView) findViewById(R.id.pessoas);
      final Button botaoHomem = (Button) findViewById(R.id.homem);
      final Button botaoMulher = (Button) findViewById(R.id.mulher);
      final Button botaoReset = (Button) findViewById(R.id.reset);

      botaoHomem.setOnClickListener(new Button.OnClickListener(){
            public void onClick(View v){
                numeroHomem++;
                numeroPessoas++;
                String mensagem = Integer.toString(numeroPessoas);
                campoTexto.setText("Total: " + mensagem + " pessoas");
                botaoHomem.setText(Integer.toString(numeroHomem));
            }
          });
    }
}
Run Code Online (Sandbox Code Playgroud)