代码之家  ›  专栏  ›  技术社区  ›  Goji Berry

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

  •  2
  • Goji Berry  · 技术社区  · 8 年前

    我在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赋值

    5 回复  |  直到 8 年前
        1
  •  9
  •   Ali Faris    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));
                }
              });
        }
    }
    
        2
  •  0
  •   asalamon74    8 年前

    如果你申报 numeroHomem numeroPessoas 作为最终变量,以后不能使用 numeroHomem++ numeroPessoas++ 。只需删除最后的关键字。

        3
  •  0
  •   clabe45    8 年前

    the compiler requires all the variables, used in lambdas, to be effectively final 这意味着您需要将变量设置为实例属性,以便编译器知道在哪里查找。

        4
  •  0
  •   anemomylos    8 年前

    这不是Android Studio或一般Android的问题。一旦将对象声明为 final numeroHomem numeroPessoas public static onClick 方法

        5
  •  0
  •   OzgurG    6 年前

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