bluePhlavio
bluePhlavio

Reputation: 547

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?

Upvotes: 0

Views: 1358

Answers (2)

Understanding helpful explanation above I would like to give an easy way to find a view by its ID from CustomViews:

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

inside your CustomView class.

This code must be run AFTER constructor code e.g. inside onAttachedToWindow()

Upvotes: 0

laalto
laalto

Reputation: 152807

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

Upvotes: 1

Related Questions