I have a res/layout/main.xml
including these elements and others:
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. :-)
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. :(
Same issue, but different solution: I didn't call
setContentView(R.layout.main)
BEFORE I tried to find the view as stated here
If you have multiple layout versions (depending on screen densities, SDK versions) make sure that all of them include the element you are looking for.
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.
To add another trivial mistake to the answers to look out for:
Check that you're actually editing the right layout XML file...