views:

1994

answers:

2

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 = 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?

+7  A: 

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

Chris Boyle
Always nice to be able to answer your own questions :) Make sure to mark yours as the accepted answer too.
MattC
Indeed. Will do so when SO lets me ("You can accept your own answer in 2 days.")
Chris Boyle
Also, shouldn't you lines like `(MyCustomView) foo = findViewById(R.id.foo);` be `MyCustomView foo = (MyCustomView) findViewById(R.id.foo);`?
fiXedd
Yes, thanks. Edited.
Chris Boyle
Had the same problem, in my case I had forgotten the setContentView().. XD
Tom Brito
A: 

For me, the problem was solved when I added the res folder to the Source in Java Build Path in project Settings.

Jiwon Park