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?
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!
I had the same problem. My mistake was that: I wrote
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View layout=inflater.inflate(R.layout.dlg_show_info, null);
alertDlgShowInfo.setView(layout);
TableRow trowDesc=(TableRow)findViewById(R.id.trowDesc);
and as I used an inflater to "load" the view from an XML file, the last line was wrong. To solve it, I had to write:
TableRow trowDesc=(TableRow)layout.findViewById(R.id.trowDesc);
I wrote my solution, in case someone have the same problem.
Seems there is a variety of reasons. I just used "Clean..." in Eclipse to solve a similar problem. (FindViewByID had worked before and for some reason started to return null.)