在android.support.v4.widget.DrawerLayout中的包含了两个部分:
1. 主界面
通过include一个layout布局进来作为主界面。
2. 侧滑界面
用NavigationView,其中包括了两部分:headerLayout和menu。
自己做的app实现从headerLayout中获取(findViewById())某个View(比如TextVIew),然后在Java代码中动态更改(setText())其值。
但是 Android Design Support Library NavitationView更新到v23之后的findViewById的NullPointerException
解决方案:
不要通过在xml文件中设置headerLayout(见fragment_device.xml中被注释掉的那行代码),而是通过在Java代码中来动态填充获取(如下所示)。
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
View headerLayout = LayoutInflater.from(this).inflate(R.layout.nav_header_main,navigationView,false);
navigationView.addHeaderView(headerLayout);
navigationView.setNavigationItemSelectedListener(this);
TextView usernameView = (TextView) headerLayout.findViewById(R.id.username_text);
usernameView.setText(Globals.nowUsername);
MainActivity中fragment_device.xml:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:openDrawer="start">
<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:headerLayout="@layout/nav_header_main"-->
</android.support.v4.widget.DrawerLayout>
nav_header_main.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="@dimen/nav_header_height"
android:background="@drawable/side_nav_bar"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:theme="@style/ThemeOverlay.AppCompat.Dark"
android:orientation="vertical"
android:gravity="bottom">
<ImageView
android:id="@+id/user_image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingTop="@dimen/nav_header_vertical_spacing"
android:src="@drawable/user_logo" />
<TextView
android:id="@+id/username_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="@dimen/nav_header_vertical_spacing"
android:text="@string/username_default"
android:textAppearance="@style/TextAppearance.AppCompat.Body1" />
</LinearLayout>