关于android:findViewById()从自定义视图返回null

findViewById() from custom view return null

似乎与其他问题相似,但我没有找到解决方案。 我有一个由xml文件定义的布局:

main_layout.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    ... >

       <package.CustomView
       ... >
       </package.CustomView>

       <TextView
       android:id="@+id/text_view"
       ... >
       </TextView>

    </RelativeLayout>

CustomView扩展SurfaceView的位置。

在onCreate中,我有setContentView(R.layout.main_layout)。 现在,例如,如果要充气,必须在setContentView(...)之后添加的活动中添加TextView

1
    TextView textView = (TextView) findViewbyId(R.id.text_view);

一切正常。 但是,如果我将此行放入CustomView的方法中,则会得到一个空指针。 为什么?


findViewById()将仅遍历给定视图及其子级。 它不会找到同级视图。 您的textview是自定义视图的兄弟,而不是子视图。

在活动中,开始遍历findViewById()的根视图是活动窗口(Activity.findViewById())。 在视图中,它是视图本身(View.findViewById())。


理解上面的有用解释后,我想提供一种简单的方法来通过CustomViews的ID查找视图:

1
(Activity)getContext()).findViewById(R.id.youViewToBeFound);

在您的CustomView类中。

此代码必须在构造函数代码之后运行,例如 内部onAttachedToWindow()