【问题标题】:Null Pointer Exception when Setting View's Color设置视图颜色时出现空指针异常
【发布时间】:2012-10-04 04:59:18
【问题描述】:

我正在尝试将视图的背景设置为红色,只是为了尝试一些东西。我在活动布局中添加了一个视图,并给它一个 id,“gradientView”。在我的 Java 代码中,我创建了一个像这样的新视图:

    View gradientView = (View) findViewById(R.id.gradientView);

在 onCreate 我这样做:

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_clean_weather);
    gradientView.setBackgroundColor(Color.RED);

由于某种原因,它在 findViewById 处给了我一个空指针异常。当我将它引用到我的 XML 视图时,我以为我让它“不为空”?!

有人知道怎么回事吗?

谢谢。

【问题讨论】:

  • 如果您尝试将“gradientView”初始化并声明为全局成员,那将无法正常工作。您可以声明它,但必须在设置 contentview 后进行初始化。

标签: java android view nullpointerexception


【解决方案1】:

您的findviewById 应该在setContentView(..) 之后;

例子:

 super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_clean_weather);
    View gradientView = (View) findViewById(R.id.gradientView);
    gradientView.setBackgroundColor(Color.RED);

否则gradientView 将为空,并且对null 引用的任何操作都会导致NullPointerException

【讨论】:

  • 请将您的示例更改为调用setBackgroundColor() 之后 findViewById(),否则也是NPE。
  • 这是正确答案。对findViewById 的隐式调用而不是someOtherView.findViewById 将使用当前布局的上下文(又名this)。不过,您需要先使用 setContentView 设置布局,否则将没有任何 XML 可供搜索。
  • 为什么在 setContentView() 之前调用它会使其为空?
  • 参考 mrres 评论。它解释得很好。
猜你喜欢
  • 2013-09-02
  • 2021-06-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多