Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing navigation header elements using ButterKnife

I have a class which handles character selection from a RecyclerView and everything works, but I want to update text of the elements in the NavigationView header with the right information. So far I've been trying to use ButterKnife to solve this, but with no success. However, I've been able to make it work in this way:

private ImageView mImageView;
private TextViewTitle mTextViewName;
private TextViewRegular mTextViewTitle;
private static View mHeaderView;

public void setHeaderView(View headerView) {
    mHeaderView = headerView;
    selectedCharacterInstance.setHeaderViewElements();
}

private void setHeaderViewElements() {
    mImageView = mHeaderView.findViewById(R.id.selected_character_info1);
    mTextViewName = mHeaderView.findViewById(R.id.selected_character_info2);
    mTextViewTitle = mHeaderView.findViewById(R.id.selected_character_info3);
}

I pass the headerView from the MainActivity. I don't like this approach, but I might be wrong since I am fairly new to Android programming. Is this the right approach? Is there a way to solve this using ButterKnife? (I tried ButterKnife but the ImageView and the TextViews were always null)

like image 515
rock_crusher Avatar asked Mar 07 '23 12:03

rock_crusher


1 Answers

I use also Butter Knife for my navigation header. For the header, I create a view holder:

protected static class HeaderViewHolder {

    @BindView(R.id.user_name)
    protected TextView mUserNameTxt;

    @BindView(R.id.user_email)
    protected TextView mUserEmailTxt;

    HeaderViewHolder(View view) {
        ButterKnife.bind(this, view);
    }
}

Then in my activity's onCreate method:

View header = mNavigationView.getHeaderView(0);
mHeaderViewHolder = new HeaderViewHolder(header);

mHeaderViewHolder.mUserEmailTxt.setText(userEmail);

This allows me to use mHeaderViewHolder like any other RecyclerView holder.

like image 182
Anton Makov Avatar answered Mar 10 '23 10:03

Anton Makov