我建议你使用简单的方案——一Activity
,多Fragments
。
例如 - 您可以在Android Studio中创建新项目(尽管它在新版本的Android StudioNavigation Drawer Activity
活动中显示“导航抽屉”将使用创建) - 它会为您创建一个。NavigationView
MainActivity
为了支持Fragment
s 方案,你需要在你Activity
的这个片段的内容上使用特殊的容器。让我们添加FrameLayout
到layout/content_main.xml
文件中:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
tools:context=".MainActivity"
tools:showIn="@layout/app_bar_main">
<!-- The main content view -->
<FrameLayout
android:id="@+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
请注意,我FrameLayout
使用content_frame
id 创建 - 我们稍后将使用它。
然后,例如,创建两个空白片段 -BlankFragment1
和BlankFragment2
.
现在查看 中的代码MainActivity
,而不是onNavigationItemSelected
方法。默认情况下,它看起来像:
@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_camara) {
// Handle the camera action
} else if (id == R.id.nav_gallery) {
} else if (id == R.id.nav_slideshow) {
} else if (id == R.id.nav_manage) {
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
每个if
语句都帮助我们区分导航视图中的菜单项。让我们通过单击更改此代码以离开并通过BlankFragment1
单击R.id.nav_camara
离开:BlankFragment2
R.id.nav_gallery
@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
Fragment fragment;
switch (item.getItemId()) {
case R.id.nav_camara:
fragment = BlankFragment1.newInstance("param1", "param2");
break;
case R.id.nav_gallery:
fragment = BlankFragment2.newInstance("param3", "param4");
break;
default:
fragment = BlankFragment1.newInstance("param1", "param2");
}
// Insert the fragment by replacing any existing fragment
FragmentManager fragmentManager = this.getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.content_frame, fragment)
.commit();
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
并启动应用程序。现在,您可以通过单击这两个图标(相机和画廊)来更改片段。希望它可以帮助你。