讓我先說這個:我已經瀏覽了關於此問題的所有其他主題,並且仔細研究了Google的答案,但沒有任何幫助。findViewById()返回null用於自定義視圖 - Android
我有一個佈局,其中包含在運行時添加的自定義視圖。我的自定義視圖具有super(context, attrs)
構造函數。
自定義視圖:
public CustomLinearLayout(Context context, AttributeSet attrs) {
super(context, attrs);
initialize some variables...
}
我想補充意見,我的活動有以下方法:
public void addNewView (boolean isEmpty) {
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
for (int i = 0; i < amount; i++) {
if (isEmpty) {
View v = (ViewGroup) inflater.inflate(R.layout.my_custom_layout, layoutContainer, true);
viewTracker++;
}
}
}
如果我使用findViewById在addNewView()
方法上面,然後我的自定義視圖一切都很好。然而,如果我試圖在活動後的任何其他位置使用findViewById(顯然在setContentView
之後),我會得到一個空指針。我也試過someView.findViewById()
,這是行不通的。我很難過。有任何想法嗎?
logcat中顯示了一個空指針,但僅此而已:
02-16 06:56:10.681: E/AndroidRuntime(11360): FATAL EXCEPTION: main
02-16 06:56:10.681: E/AndroidRuntime(11360): java.lang.NullPointerException
02-16 06:56:10.681: E/AndroidRuntime(11360): at com.nutrifit.Fragments.WorkoutPlannerPopup.resetOtherView(WorkoutPlannerPopup.java:404)
02-16 06:56:10.681: E/AndroidRuntime(11360): at com.nutrifit.customviews.CustomLinearLayout.onTouchEvent(CustomLinearLayout.java:43)
02-16 06:56:10.681: E/AndroidRuntime(11360): at android.view.View.dispatchTouchEvent(View.java:7239)
02-16 06:56:10.681: E/AndroidRuntime(11360): at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2168)
02-16 06:56:10.681: E/AndroidRuntime(11360): at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:1903)
02-16 06:56:10.681: E/AndroidRuntime(11360): at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2174)
下面是XML我的自定義視圖:
<?xml version="1.0" encoding="utf-8"?>
<com.nutrifit.customviews.CustomLinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/exercise_container_0"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:background="@drawable/wpp_background_border" >
<ImageView android:id="@+id/delete_button_1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/wpp_background_border" />
...more android child views
</com.nutrifit.customviews.CustomLinearLayout>
你確定setContentView是否正確分配並且不拋出未捕獲的異常?發佈logcat的輸出和您的所有代碼。 – Kerry 2013-02-16 08:10:55
@Kerry據我所知,setContentView正確地分配。當我嘗試使用findViewById時,唯一引發的異常是空指針。您希望我發佈哪些代碼?包含這個的活動是450多行代碼。 – Don 2013-02-16 18:16:15
請在您聲明自定義視圖的位置粘貼您的xml。 – 2013-02-16 18:26:55