问题
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)
回答1:
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.
来源:https://stackoverflow.com/questions/49593446/accessing-navigation-header-elements-using-butterknife