<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:menu="@menu/drawer_menu" app:headerLayout="@layout/header_layout" /> <menu xmlns:android="http://schemas.android.com/apk/res/android"> <group android:checkableBehavior="single"> <item android:id="@+id/nav_home" android:icon="@drawable/ic_home" <item android:id="@+id/nav_message" android:icon="@drawable/ic_message" <item android:id="@+id/nav_setting" android:icon="@drawable/ic_setting" </group> </menu> public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener { private DrawerLayout drawerLayout; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); drawerLayout = findViewById(R.id.drawer_layout); NavigationView navigationView = findViewById(R.id.navigation_view); navigationView.setNavigationItemSelectedListener(this); } @Override public boolean onNavigationItemSelected(@NonNull MenuItem item) { int id = item.getItemId(); switch (id) { case R.id.nav_home: replaceFragment(new HomeFragment()); break; case R.id.nav_message: replaceFragment(new MessageFragment()); break; case R.id.nav_setting: replaceFragment(new SettingFragment()); break; } drawerLayout.closeDrawer(GravityCompat.START); return true; } private void replaceFragment(Fragment fragment) { FragmentManager fragmentManager = getSupportFragmentManager(); fragmentManager.beginTransaction().replace(R.id.fragment_container, fragment).commit(); } } <android.support.v4.widget.DrawerLayout android:id="@+id/drawer_layout" android:layout_width="match_parent" android:layout_height="match_parent"> <FrameLayout android:id="@+id/fragment_container" android:layout_width="match_parent" android:layout_height="match_parent" /> <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:menu="@menu/drawer_menu" app:headerLayout="@layout/header_layout" /> </android.support.v4.widget.DrawerLayout>


上一篇:
下一篇:
切换中文