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

Question!

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?



Answers

My problem was a typo. I had written android.id (dot) instead of android:id. :P

Apparently there is no syntax check within my custom component xml. :(

By : JOG


Had the same problem.

I had layout with few children. From constructor of one them I was trying to get reference (by using context.findViewById) to other child. It wasn't working because the second child was defined further in layout.

I've resolved it like this:

setContentView(R.layout.main);
MyView first = findViewById(R.layout.first_child);
first.setSecondView(findViewById(R.layout.second_child));

It would work as well if the order of children was opposite,but I guess it generally should be done like above.

By : Kangur


The findViewById() method sometimes returns null when the root of layout has no android:id attribute. Eclipse wizard for generating layout xml file does not automatically generate android:id attribute for the root element.

By : Santosh


This video can help you solving your question :)
By: admin