簡體   English   中英

錯誤:無法為最終變量賦值

[英]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));
         }
     });
 } }

錯誤:無法為最終變量 numeroHomem 賦值
錯誤:無法為最終變量 numeroPessoas 賦值

初始化后不能更改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));
            }
          });
    }
}

如果您將numeroHomemnumeroPessoas聲明為最終變量,則以后不能使用numeroHomem++numeroPessoas++增加它們的值。 只需刪除最終關鍵字。

您不能更改 final 變量的值,只需從變量中刪除 final。

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

正如您的評論所暗示的那樣, the compiler requires all the variables, used in lambdas, to be effectively final意味着您需要將變量設置為實例屬性,因此編譯器將知道在哪里查找。

這通常不是 Android Studio 或 Android 的問題。 一旦你將一個對象聲明為final你就不能改變它。 例如,創建一個實用程序類,在該類中將numeroHomemnumeroPessoaspublic static並在onClick方法中修改它們。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM