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

前端 未结 18 1426
情歌与酒
情歌与酒 2020-11-28 10:36

I have a res/layout/main.xml including these elements and others:



        
相关标签:
18条回答
  • 2020-11-28 11:16

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

    0 讨论(0)
  • 2020-11-28 11:16

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

    0 讨论(0)
  • 2020-11-28 11:18

    Same issue, but different solution: I didn't call

    setContentView(R.layout.main)
    

    BEFORE I tried to find the view as stated here

    0 讨论(0)
  • 2020-11-28 11:20

    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.

    0 讨论(0)
  • 2020-11-28 11:20

    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.

    0 讨论(0)
  • 2020-11-28 11:25

    To add another trivial mistake to the answers to look out for:

    Check that you're actually editing the right layout XML file...

    0 讨论(0)
提交回复
热议问题