bluePhlavio bluePhlavio - 1 year ago 259
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:


<RelativeLayout xmlns:android=""
... >

... >

... >


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(;

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

Answer Source

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()).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download