首先:是的,我閱讀了關於此主題的所有其他主題。而且不僅是從本網站......(你看,我有點沮喪)findViewByID返回null
他們大多與建議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
應該工作的設想。驚喜:它沒有解決任何問題。
那麼,我做錯了什麼?
我會感謝您的任何意見。
如果項目也被破壞,可能會發生這種情況。我通過清理項目來解決它 – Pacerier 2012-02-14 10:07:51
通過錯誤的上下文視圖謝謝 – izzy 2015-04-13 09:59:59
@Pacerier謝謝。這解決了我的問題。我開始討厭Xamarin中的android編程) – Artiom 2015-08-16 17:58:38