最佳答案
首先,是的,我读了关于这个话题的所有其他帖子。不仅仅是这个网站的人…(你看,我有点沮丧)
它们中的大多数都建议在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.findViewById
和View.findViewById
的差异。所以我存储上下文传递给本地的海关视图构造函数,并尝试:
...
TextView tv = (TextView) ((Activity) context).findViewById( R.id.txtLat );
它也返回null
。
然后,我更改了自定义视图,扩展了ViewGroup
而不是View
,并更改了location_layout.xml
,让TextView
成为自定义视图的直接子视图,这样View.findViewById
就应该像假设的那样工作。令人惊讶的是:它并没有解决任何问题。
我到底做错了什么?
欢迎任何意见。