bluePhlavio bluePhlavio - 5 months ago 56
Android Question

findViewById() from custom view return null

It seem similar to other questions but I doesn't found solutions. I have a layout defined by xml file:

main_layout.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
... >

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

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

</RelativeLayout>


where CustomView extends SurfaceView.

In onCreate I have setContentView(R.layout.main_layout). Now, If I want to inflate, for example, the TextView in the activity I have to add after setContentView(...)

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


and all works fine. But if I put this line in a method of my CustomView I got a null pointer. Why?

Answer

findViewById() will traverse only the given view and its children. It will not find sibling views. Your textview is a sibling to the custom view, not a child view.

In an activity, the root view where findViewById() traversal starts is the activity window (Activity.findViewById()). In a view, it is the view itself (View.findViewById()).

Comments