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

大多数都建议使用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应该正常工作。令人惊讶的是:它并没有解决任何问题。

我到底做错了什么?

欢迎任何意见。


当前回答

对我来说,它返回null,因为给定的控件是(以编程方式)隐藏的。当我只在控件可见时调用findViewByID(id)时,它又开始工作了。

其他回答

我试过以上所有的方法,但都没有效果。所以我必须让我的ImageView static public static ImageView texture;然后texture = (ImageView) findViewById(R.id.texture_back);,我不认为这是一个好方法,但这确实对我的情况有效:)

在我的情况下,我使用ExpandableListView,我设置了android:transcriptMode="normal"。这导致可扩展组中的几个孩子消失,我习惯了在我使用滚动列表时得到NULL异常。

当我试图为ListView做一个自定义视图时,我也面临着类似的问题。

我的解决方法很简单:

public View getView(int i, View view, ViewGroup viewGroup) {

    // Gets the inflater
    LayoutInflater inflater = LayoutInflater.from(this.contexto);

    // Inflates the layout
    ConstraintLayout cl2 = (ConstraintLayout) 
    inflater.inflate(R.layout.custom_list_view, viewGroup, false);

    //Insted of calling just findViewById, I call de cl2.findViewById method. cl2 is the layout I have just inflated. 
     TextView tv1 = (TextView)cl2.findViewById(cl2);

对我来说,问题是我有两个具有相同文件名activity_main.xml的布局。(布局在不同的库中,但在同一个应用程序中)通过将其中一个重命名为唯一的名称解决了这个问题。

如果在自定义视图中调用了错误的超级构造函数,FindViewById可以为空。ID标记是attrs的一部分,因此如果忽略attrs,则删除ID。

这是错误的

public CameraSurfaceView(Context context, AttributeSet attrs) {
        super(context);
}

这是正确的

public CameraSurfaceView(Context context, AttributeSet attrs) {
        super(context,attrs);
}