In android studio 1.4.1, I have created new Navigation Drawer Project which is default.My issue is in this project there is nav_header_main.xml file which is for navigation
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
View hView = navigationView.getHeaderView(0);
TextView nav_user = (TextView)hView.findViewById(R.id.nav_name);
nav_user.setText(user);
hope this help!
don't add header in xml add using code by inflating layout
View hView = navigationView.inflateHeaderView(R.layout.nav_header_main);
ImageView imgvw = (ImageView)hView.findViewById(R.id.imageView);
TextView tv = (TextView)hView.findViewById(R.id.textview);
imgvw .setImageResource();
tv.settext("new text");
Also you can use Kotlinx features
val hView = nav_view.getHeaderView(0)
hView.textViewName.text = "lorem ipsum"
hView.imageView.setImageResource(R.drawable.ic_menu_gallery)
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.addHeaderView(yourview);
Here is my code below perfectly working Do not add the header in NavigationView tag in activity_main.xml
<include
layout="@layout/app_bar_main"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<android.support.design.widget.NavigationView
android:id="@+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:menu="@menu/activity_main_drawer"
app:itemBackground="@drawable/active_drawer_color" />
add header programmatically with below code
View navHeaderView = navigationView.inflateHeaderView(R.layout.nav_header_main);
headerUserName = (TextView) navHeaderView.findViewById(R.id.nav_header_username);
headerMobileNo = (TextView) navHeaderView.findViewById(R.id.nav_header_mobile);
headerMobileNo.setText("+918861899697");
headerUserName.setText("Anirudh R Huilgol");
nav = ( NavigationView ) findViewById( R.id.navigation );
if( nav != null ){
LinearLayout mParent = ( LinearLayout ) nav.getHeaderView( 0 );
if( mParent != null ){
// Set your values to the image and text view by declaring and setting as you need to here.
SharedPreferences prefs = getSharedPreferences("user_data", MODE_PRIVATE);
String photoUrl = prefs.getString("photo_url", null);
String user_name = prefs.getString("name", "User");
if(photoUrl!=null) {
Log.e("Photo Url: ", photoUrl);
TextView userName = mParent.findViewById(R.id.user_name);
userName.setText(user_name);
ImageView user_imageView = mParent.findViewById(R.id.avatar);
RequestOptions requestOptions = new RequestOptions();
requestOptions.placeholder(R.drawable.ic_user_24dp);
requestOptions.error(R.drawable.ic_user_24dp);
Glide.with(this).load(photoUrl)
.apply(requestOptions).thumbnail(0.5f).into(user_imageView);
}
}
}
Hope this helps.