2013-02-16 57 views
1

讓我先說這個:我已經瀏覽了關於此問題的所有其他主題,並且仔細研究了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> 
+0

你確定setContentView是否正確分配並且不拋出未捕獲的異常?發佈logcat的輸出和您的所有代碼。 – Kerry 2013-02-16 08:10:55

+0

@Kerry據我所知,setContentView正確地分配。當我嘗試使用findViewById時,唯一引發的異常是空指針。您希望我發佈哪些代碼?包含這個的活動是450多行代碼。 – Don 2013-02-16 18:16:15

+0

請在您聲明自定義視圖的位置粘貼您的xml。 – 2013-02-16 18:26:55

回答

3

哪裏addNewView()方法被調用?根據我的理解,如果您在自定義視圖的構造函數中執行findViewById(),則可以獲得null。我還沒有找到一個權威性的參考資料,說明何時可以在自定義視圖中調用findViewById(),但通常我會在onFinishInflate()或更高版本中執行此操作。

+0

'addNewView()'方法是通過點擊按鈕來調用的。所以,佈局應該是膨脹的。我有點解決了這個問題。我最終發現它與我的自定義視圖有關。但是,我不知道在我的自定義視圖中會發生什麼 - 我擁有正確的構造函數,而且沒有其他任何關於視圖的特殊情況。儘管感謝您的幫助! – Don 2013-02-28 05:40:35