findViewByID 返回 null

新手上路,请多包涵

首先:是的,我阅读了有关该主题的所有其他主题。不仅是来自这个网站的那些……(你看,我有点沮丧)

他们中的大多数都建议在 XML 文件中使用 android:id 而不仅仅是 id 。我做到了。

从其他人那里,我了解到 View.findViewByIdActivity.findViewById 的工作方式不同。我也处理过。

在我的 location_layout.xml 中,我使用:

 <FrameLayout .... >
    <some.package.MyCustomView ... />

    <LinearLayout ... >
        <TextView ...
            android:id="@+id/txtLat" />
        ...
    </LinearLayout>
</FrameLayout>

在我的活动中,我这样做:

 ...
setContentView( R.layout.location_layout );

在我的自定义视图类中:

 ...
TextView tv = (TextView) findViewById( R.id.txtLat );

返回 null这样做,我的 Activity 工作正常。 所以可能是因为 Activity.findViewByIdView.findViewById 差异。所以我在本地存储了传递给海关视图构造函数的上下文并尝试了:

 ...
TextView tv = (TextView) ((Activity) context).findViewById( R.id.txtLat );

它还返回 null

Then, I changed my custom view to extend ViewGroup instead View and changed the location_layout.xml to let the TextView be a direct child of my自定义视图,以便 View.findViewById 应该按预期工作。惊喜:它没有解决任何问题。

那么我到底做错了什么?

我会很感激任何评论。

原文由 Thomas 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 711
2 个回答

返回 null

可能是因为你打电话太早了。等到 onFinishInflate()这是一个示例项目, 演示了自定义 View 访问其内容。

原文由 CommonsWare 发布,翻译遵循 CC BY-SA 3.0 许可协议

对我来说,只有在使用 Evaluate Expression 或 IDE 的 Debug Watch View 时它才为空。

原文由 Jennifer Kiesel 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题