Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

findViewById() returns null for custom component in layout XML, not for other components

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?

like image 226
Chris Boyle Avatar asked Nov 07 '09 01:11

Chris Boyle


People also ask

Why is findViewById returning 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.

What does findViewById return?

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 .

What is the purpose of the findViewById () method?

FindViewById<T>(Int32)Finds a view that was identified by the id attribute from the XML layout resource.

How does findViewById work on Android?

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?


2 Answers

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

like image 112
Chris Boyle Avatar answered Oct 09 '22 00:10

Chris Boyle


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!

like image 34
Alexander Korolchuk Avatar answered Oct 09 '22 00:10

Alexander Korolchuk