只需为平板电脑提供备用布局文件。这样就可以保存NavigationView的所有默认行为。
第一步
只需为平板设备创建一个与此类似的备用布局文件,并将其放在layout-w600dp-land 资源目录中。
<?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">
<!--
NavigationView and the content is placed in a horizontal LinearLayout
rather than as the direct children of DrawerLayout.
This makes the NavigationView always visible.
-->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<android.support.design.widget.NavigationView
android:id="@+id/nav"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
app:headerLayout="@layout/nav_header_main"
app:menu="@menu/activity_main_drawer"/>
<include
layout="@layout/app_bar_main"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
</android.support.v4.widget.DrawerLayout>
第 2 步
在此步骤中,我们将进行足够的更改以确保抽屉的打开和关闭仅适用于非平板设备。
步骤 2.1
在values目录下新建一个value资源文件,命名为config_ui.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<bool name="isDrawerFixed">false</bool>
</resources>
这适用于非平板设备。对于平板设备,创建另一个具有相同名称的设备并将其放在values-w600dp-land。
<?xml version="1.0" encoding="utf-8"?>
<resources>
<bool name="isDrawerFixed">true</bool>
</resources>
在抽屉所属的活动类中创建一个新字段
private boolean isDrawerFixed;
并将其初始化为
isDrawerFixed = getResources().getBoolean(R.bool.isDrawerFixed);.
现在我们可以像if (isDrawerFixed){} 一样简单地检查设备是平板电脑还是非平板电脑。
步骤 2.2
用这样的if 语句包装在操作栏上设置切换按钮的代码。
if (!isDrawerFixed) {
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
}
使用像这样的另一个if 语句包装当单击项目时关闭抽屉的代码。
if (!isDrawerFixed) {
drawer.closeDrawer(GravityCompat.START);
}
最终的结果会有点像这样。