Search code examples
androidexpandablelistviewlayout-inflaterandroid-annotationsfindviewbyid

How to use @ViewById for an inflated view outside of @EActivity(R.layout.activity_x)


I am using Android Annotations 3.1 in my project in Android Studio and I am using an Expandable List View.

I am adding a header to my list like this:

View header = getLayoutInflater().inflate(R.layout.list_view_header, null);
txt_user = (TextView) header.findViewById(R.id.txt_user);
txt_user.setText(" ... "); 
mExpandableListView.addHeaderView(header);

Question:

How can I use @ViewById to set my TextView to:

    - avoid using findViewById

    - changing its text

    - and then adding that as a header during:

@AfterViews
protected void init() {
 ....

}

If I do this inside my Activity when using my text view inside init:

@ViewById
TextView txt_user;

It gives null pointer exception.


Solution

  • Why don't you create a custom view like this :

    @EViewGroup(R.layout.list_view_header)
    public class MyHeader extends LinearLayout {
    
         @ViewById(R.id.txt_user)
         protected TextView mTextView;
    
         public void setText(String text) {
             mTextView.setText(text);
         }
         public MyHeader(Context context) {
             super(context);
         }
    }
    

    Then, in your Activity, write this :

    @EActivity(R.layout.activity_xxx)
    public class MyActivity extends Activity {
    
        private MyHeader mHeader;
    
        @AfterViews
        protected void init() {
            mHeader = MyHeader_.build(this);
            mHeader.setText("...");
            mExpandableListView.addHeaderView(mHeader);
        }
    }