【问题标题】:private fields in android studioandroid studio中的私有字段
【发布时间】:2020-01-24 16:31:35
【问题描述】:

当我在我的代码中使用 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();
        }
    }
}

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

【问题讨论】:

  • 您的按钮和文本视图在onCreate 中使用。即使将字段设为私有,这仍然应该有效。您的代码中是否还有其他未包含在问题中的内容?
  • 我没有其他代码,除了布局 XML,它是一个图像视图、文本视图和 2 个按钮。问题是当我将字段设为私有时为什么会出错?还有我制作点击监听器的方式是否有效?
  • 请遵循一些好的安卓教程。您正在使用空对象,它们使用 this.findViewById(R.id.buttonFalse); 进行初始化R.id.buttonFals 这是您在 activity_main.xml 文件中定义的 ID。
  • 对不起,我不明白你的陈述@manmohan 我正在上 Udemy 课程,除了我的布局是约束布局而他的线性布局之外,代码是相同的。他的工作正常,但我的却报错
  • 使用你的代码部分:falseButton = findViewById(R.id.buttonFalse); trueButton = findViewById(R.id.buttonTrue); questionTextView = findViewById(R.id.textView);希望它会工作

标签: java android field private


【解决方案1】:

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

我有

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

但我应该有 = 而不是 .

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

【讨论】:

    猜你喜欢
    • 2014-06-19
    • 2011-12-02
    • 2021-08-27
    • 2013-03-08
    • 1970-01-01
    • 2013-12-25
    • 1970-01-01
    • 2010-09-29
    相关资源
    最近更新 更多