java - 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();
}
}
}
然后我应该能够打开模拟器,按下按钮并弹出吐司,但应用程序失败。
解决方案
@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);
推荐阅读
- ruby - Docker 构建失败 - 无法找到包
- python - Python websocket 多个消息监听器
- google-play - Google Play 商品详情实验持续时间
- android - 我想在提示中显示主题名称,然后标记
- python - python - 如何在Pyplot中绘制一个具有n个偶数面积切片的圆?
- optimization - fsolve 在 python 中的差分进化函数中非常慢收敛
- logistic-regression - 关于逻辑回归
- javascript - 如何在电子中显示打印预览?
- sql - 如何指望加入具有 2 个条件的表?
- java - Jsoup - 如何使用自动关闭创建我自己的标签