尽管对它有价值,但仍获得nullpointerexception

时间:2016-02-09 15:02:48

标签: java android

我正在创建一个基本的Android应用程序。我正在创建一个名为TextView的{​​{1}}对象,并指定我希望它引用的textview的id值。

mathexpresionTV

我还有一个按钮,如果用户按下它,它会在文本视图中显示1。

TextView mathExpressionTV = (TextView) findViewById(R.id.mathexpressiontextview);

我将在课程中使用 Button oneButton = (Button) findViewById(R.id.button1) oneButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mathExpressionTV.append("0"); } }); 因此我将其视为全局变量,而不是我的mathExpressionTV方法,但onCreate();在我的{{1}中声明}}

这是错误输出:oneButton

2 个答案:

答案 0 :(得分:2)

您可以将其声明为全局,但您需要在TextView中投射为onCreate。您不能在活动

中的方法之外使用findViewById
TextView mathExpressionTV;

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

    mathExpressionTV = (TextView) findViewById(R.id.mathexpressiontextview);

    ...
}

答案 1 :(得分:0)

您有3个选项:

  1. findViewById方法
  2. 中使用onCreate
  3. textView创建一个全局变量,并在onCreate方法
  4. 中指定它
  5. 传递活动对象,或获取活动对象并使用它:activity.findViewById