首先:是的,我阅读了有关该主题的所有其他主题。不仅是来自这个网站的那些……(你看,我有点沮丧)
他们中的大多数都建议在 XML 文件中使用 android:id
而不仅仅是 id
。我做到了。
从其他人那里,我了解到 View.findViewById
与 Activity.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.findViewById
和 View.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 许可协议
可能是因为你打电话太早了。等到
onFinishInflate()
。 这是一个示例项目, 演示了自定义View
访问其内容。