我相信,我已经达到了预期的效果:
![enter image description here](https://istack.dev59.com/DWakN.gif)
这个想法的背后是每次用户点击菜单项时都清除现有菜单并重新填充菜单,以便导航到子菜单。 (回退时-做同样的事情)
作为根菜单(activity_main_drawer.xml),我使用了以下内容:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<group android:checkableBehavior="single">
<item
android:id="@+id/action_item1"
android:icon="@drawable/ic_menu_camera"
android:title="Item 1" />
<item
android:id="@+id/action_expand"
android:icon="@drawable/ic_menu_gallery"
android:title="Sub Menu to expand" />
</group>
</menu>
这是一个子菜单(
activity_submenu_drawer.xm
):
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:title="Go Back"
android:icon="@drawable/ic_back"
android:id="@+id/back_to_main"/>
<item
android:id="@+id/sub_item1"
android:icon="@drawable/ic_menu_share"
android:title="Subitem 1" />
<item
android:id="@+id/sub_item2"
android:icon="@drawable/ic_menu_send"
android:title="Subitem 2" />
</menu>
MainActivity.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:headerLayout="@layout/nav_header_main" />
</android.support.v4.widget.DrawerLayout>
这里是MainActivity
类(实现了切换):
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
NavigationView navigationView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
.....
navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.inflateMenu(R.menu.activity_main_drawer);
navigationView.setNavigationItemSelectedListener(this);
}
....
@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_expand) {
navigationView.getMenu().clear();
navigationView.inflateMenu(R.menu.activity_submenu_drawer);
} else if (id == R.id.back_to_main) {
navigationView.getMenu().clear();
navigationView.inflateMenu(R.menu.activity_main_drawer);
}
return true;
}
}
我已经将我的测试项目上传到了我的Dropbox - 随意查看
希望可以帮到你