I have a NavigationView
nested inside a DrawerLayout
.
activity_main.xml
<android.support.v4.widget.DrawerLayout
android:id="@+id/drawer_layout"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true">
.......
<android.support.design.widget.NavigationView
android:id="@+id/navigation_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
app:headerLayout="@layout/drawer_header"
app:menu="@menu/drawer"/>
</android.support.v4.widget.DrawerLayout>
drawer_header.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="150dp"
android:background="?attr/colorPrimaryDark"
android:gravity="bottom"
android:orientation="vertical"
android:padding="16dp"
android:theme="@style/ThemeOverlay.AppCompat.Dark">
<TextView
android:id="@+id/drawerHeaderTitle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/drawer_header_text"
android:textAppearance="@style/TextAppearance.AppCompat.Body1"/>
</LinearLayout>
How can I access the drawer header's title in Java code ? I tried to:
access it directly using its id
(drawerHeaderTitle) but I get a NullPointerException
access it via the NavigationView.findViewById
: same error
How can I overcome this problem ?
Using this approach
mNavigationView.addOnLayoutChangeListener(new View.OnLayoutChangeListener() {
@Override
public void onLayoutChange(View view, int i, int i1, int i2, int i3, int i4, int i5, int i6, int i7) {
mNavigationView.removeOnLayoutChangeListener( this );
TextView textView = (TextView) mNavigationView.findViewById(R.id.drawerHeaderTitle);
textView.setText("title");
}
});
If you compile with 'com.android.support:design:23.1.1' you can access your header in this way:
private NavigationView mNavigation;
private View mHeaderView;
private TextView mDrawerHeaderTitle;
mNavigation = (NavigationView) findViewById(R.id.navigation_view);
mHeaderView = mNavigation.getHeaderView(0);
mDrawerHeaderTitle = (TextView) mHeaderView.findViewById(R.id.drawerHeaderTitle);
More info about this: http://developer.android.com/intl/es/tools/support-library/index.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With