[英]findViewById() is returning null for custom view - 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++;
}
}
}
如果我在上面的addNewView()
方法中使用findViewById作为我的自定义视图,那么一切都很好。 但是,如果我在视图充气后尝试在活动中的任何其他地方使用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>
调用addNewView()
方法在哪里? 根据我的理解,如果在自定义视图的构造函数中执行findViewById()
,则可以获得null
。 我没有找到一个权威的参考,说明何时在自定义视图中调用findViewById()
是安全的,但我通常在onFinishInflate()
或更高版本中执行此操作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.