首页 > 解决方案 > android studio中的私有字段

问题描述

当我在我的代码中使用 private 时,它​​会给我一个错误,说该字段从未被分配,然后模拟器崩溃。

我看到了来自 stackoverflow 的其他信息以及有相同问题但他们实际上没有使用他们的字段的人,这就是他们出现错误的原因,所以我从不同的角度发布。

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

            Button falseButton; //this works
    private Button trueButton; //when i add private it then says true button field is not being used
    private TextView questionTextView; //this also gets an error when i use private

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

        falseButton.findViewById(R.id.buttonFalse);
        trueButton.findViewById(R.id.buttonTrue);
        questionTextView.findViewById(R.id.textView);

        falseButton.setOnClickListener(this);

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.buttonFalse:
                Toast.makeText(MainActivity.this, "False", Toast.LENGTH_SHORT).show();
                break;
            case R.id.buttonTrue:
                Toast.makeText(MainActivity.this, "True", Toast.LENGTH_SHORT).show();
        }
    }
}

然后我应该能够打开模拟器,按下按钮并弹出吐司,但应用程序失败。

标签: javaandroidfieldprivate

解决方案


@Saadat 解决了它。这是我的错,一个简单的错字:

我有

falseButton.findViewById(R.id.buttonFalse);
trueButton.findViewById(R.id.buttonTrue);
questionTextView.findViewById(R.id.textView);

但我应该有 = 而不是 a 。

falseButton = findViewById(R.id.buttonFalse); 
trueButton = findViewById(R.id.buttonTrue); 
questionTextView = findViewById(R.id.textView);

推荐阅读