首先,是的,我读了关于这个话题的所有其他帖子。不仅仅是这个网站的人…(你看,我有点沮丧)

大多数都建议使用android:id,而不是XML文件中的id。我做到了。

我从别人那里了解到,这种观点。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而不是视图,并改变了location_layout.xml,让TextView是我的自定义视图的直接子,以便视图。findViewById应该正常工作。令人惊讶的是:它并没有解决任何问题。

我到底做错了什么?

欢迎任何意见。


当前回答

对于那些使用ExpandableListView并根据它的标题遇到这个问题的人来说,这是一个答案。

我有这个错误试图与TextViews在我的孩子和组视图作为一个expandabelistview实现的一部分。

您可以在getChildView()和getGroupView()方法的实现中使用如下内容。

        if (convertView == null) {
            LayoutInflater inflater =  (LayoutInflater) myContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = inflater.inflate(R.layout.child_layout, null);
        }

我在这里找到了这个。

其他回答

膨胀布局!!(包含id)

在我的例子中,findViewById()返回null,因为元素被写入的布局没有被膨胀…

如。 fragment_layout.xml

<ListView
android:id="@+id/listview">

findViewById(R.id.listview)返回null,因为我没有做 inflater.inflate (R.layout.fragment_layout……,……); 在这之前。

希望这个答案能帮助到你们。

我的情况不像上面那样,没有解决方案。我认为我的观点过于深入布局层次结构。我向上移动了一层,它就不再是空了。

我对Android/Eclipse很新,我错误地将UI的东西添加到activity_main.xml而不是fragment_main.xml。我花了好几个小时才弄明白……

对于那些使用ExpandableListView并根据它的标题遇到这个问题的人来说,这是一个答案。

我有这个错误试图与TextViews在我的孩子和组视图作为一个expandabelistview实现的一部分。

您可以在getChildView()和getGroupView()方法的实现中使用如下内容。

        if (convertView == null) {
            LayoutInflater inflater =  (LayoutInflater) myContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = inflater.inflate(R.layout.child_layout, null);
        }

我在这里找到了这个。

我也有同样的问题,但我认为值得和你们分享。 如果你必须在自定义布局中找到viewbyid,例如:

public class MiniPlayerControllBar extends LinearLayout {
    //code
}

你不能在构造函数中得到视图。 你应该在视图膨胀后调用findViewById。 他们是一个方法,你可以覆盖onfinishinflation