I have a res/layout/main.xml
including these elements and others:
<some.package.MyCustomView android:id="@+id/foo" (some other params) /> <TextView android:id="@+id/boring" (some other params) />
In my Activity's onCreate, I do this:
setContentView(R.layout.main); TextView boring = (TextView) findViewById(R.id.boring); // ...find other elements... MyCustomView foo = (MyCustomView) findViewById(R.id.foo); if (foo == null) { Log.d(TAG, "epic fail"); }
The other elements are found successfully, but foo
comes back null. MyCustomView has a constructor MyCustomView(Context c, AttributeSet a)
and a Log.d(...)
at the end of that constructor appears successfully in logcat just before the "epic fail".
Why is foo
null?
FindViewById can be null if you call the wrong super constructor in a custom view. The ID tag is part of attrs, so if you ignore attrs, you delete the ID.
findViewById returns an instance of View , which is then cast to the target class. All good so far. To setup the view, findViewById constructs an AttributeSet from the parameters in the associated XML declaration which it passes to the constructor of View . We then cast the View instance to Button .
FindViewById<T>(Int32)Finds a view that was identified by the id attribute from the XML layout resource.
In the case of an Activity , findViewById starts the search from the content view (set with setContentView ) of the activity which is the view hierarchy inflated from the layout resource. So the View inflated from R. layout. toast is set as child of content view?
Because in the constructor, I had super(context)
instead of super(context, attrs)
.
Makes sense, if you don't pass in the attributes, such as the id, then the view will have no id and therefore not be findable using that id. :-)
I had the same problem, because in my custom view I have overridden the constructor, but invoked the super constructor without the attrs
parameter. (That was a copy/paste mistake.)
My previous constructor version:
public TabsAndFilterRelativeLayout(Context context, AttributeSet attrs) { super(context); }
Now I have:
public TabsAndFilterRelativeLayout(Context context, AttributeSet attrs) { super(context, attrs); }
And that works!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With