Error: cannot assign a value to final variable

Error: cannot assign a value to final variable

我在使用 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));
         }
     });
 } }

error: cannot assign a value to final variable numeroHomem
error: cannot assign a value to final variable numeroPessoas

如果您将 numeroHomemnumeroPessoas 声明为最终变量,则您以后无法使用 numeroHomem++numeroPessoas++ 增加它们的值。只需删除最后的关键字。

您不能更改 final 变量的值,只需从您的变量中删除 final。

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

您无法在初始化后更改 final 变量

你可以做的是在 class 而不是 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));
            }
          });
    }
}

正如您的评论所暗示的,消息 the compiler requires all the variables, used in lambdas, to be effectively final 暗示您需要将变量设置为实例属性,以便编译器知道在哪里查找。

这通常不是 Android Studio 或 Android 的问题。一旦将对象声明为 final,就无法更改它。例如,创建一个实用程序 class,在 class 中将 numeroHomemnumeroPessoas 声明为 public static 并在 onClick 方法中修改它们.