findViewById()正在为自定义视图返回null-Android

findViewById()正在为自定义视图返回null-Android,android,nullpointerexception,android-custom-view,Android,Nullpointerexception,Android Custom View,首先,我要说的是:我已经浏览了关于这个问题的所有其他帖子,并梳理了谷歌的答案,但没有任何帮助 我有一个包含在运行时添加的自定义视图的布局。我的自定义视图具有super(context,attrs)构造函数 自定义视图: public CustomLinearLayout(Context context, AttributeSet attrs) { super(context, attrs); initialize some variables... } 我使用以下方法将视图添加

首先,我要说的是:我已经浏览了关于这个问题的所有其他帖子,并梳理了谷歌的答案,但没有任何帮助

我有一个包含在运行时添加的自定义视图的布局。我的自定义视图具有
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++;
    }
    }
}
以下是我的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>

…更多android子视图

调用的
addNewView()方法在哪里?根据我的理解,如果在自定义视图的构造函数中执行
findViewById()
,则可能会得到
null
。我还没有找到一个权威引用,该引用说明在自定义视图中调用
findViewById()
何时是安全的,但我通常在
onfinishflate()
或更高版本中这样做。

您确定setContentView分配正确并且没有引发未捕获的异常吗?发布logcat的输出和所有代码。@据我所知,Kerry的setContentView赋值正确。当我尝试使用findViewById时,引发的唯一异常是空指针。您希望我发布哪种代码?包含此内容的活动有450多行代码。请将xml粘贴到声明自定义视图的位置。谢谢,看起来不错,但我不确定是否理解您的问题。您想在运行时添加许多自定义线性布局及其内容吗?或者你想在你的自定义线性布局中添加一些孩子的吗?@MichałZ.当然。对不起,我不是很清楚。我有几个类似于上面的XML布局。在我的活动中,我有根布局。我想要的是在运行时将类似上面的布局添加到活动的根布局中,然后在稍后的代码中引用它们。但是,当我尝试在自定义视图(甚至上面布局中的android视图)上使用findViewById时,我得到了一个空指针。我认为这可能与LayoutFlater有关,但我不确定。单击按钮将调用
addNewView()
方法。因此,布局应该膨胀。我差不多解决了这个问题。我最终发现这与我的自定义视图有关。然而,我不知道在我的自定义视图中会发生什么-我有正确的构造函数,并且该视图没有什么特别之处。谢谢你的帮助!
<?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>