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

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

Asked on January 3, 2019 in XML.
Add Comment


  • 3 Answer(s)

         ViewById()  will returns the null for custom component in layout XML, not for other components because in the constructor, it have super(context) instead of super(context, attrs). If we did not pass in the attributes, such as the id, then the view will have no id and so it will not be findable using that id.

    Answered on January 3, 2019.
    Add Comment

         In the custom view, we can override the constructor but invoked super contructor withot attrs paramete.

    Previous custom version,

       public TabsAndFilterRelativeLayout(Context context, AttributeSet attrs) {
          super(context);
    }
    

    Then,

       public TabsAndFilterRelativeLayout(Context context, AttributeSet attrs) {
          super(context, attrs);}
    
    Answered on January 3, 2019.
    Add Comment

         Some may have the same problem so the below code may fix it,

       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 use an inflater to “load” the view from an XML file, the last line was not correct. To make it solve, write,

    TableRow trowDesc=(TableRow)layout.findViewById(R.id.trowDesc);
    
    Answered on January 3, 2019.
    Add Comment


  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.