Android 5.0之后推出了Design新特性,大大方便了開發者,以前編寫抽屜使用DrawerLayout,現在使用DrawerLayout包含NavigatorView。NavigationView需要接收幾個必要的參數、一個用于顯示頭部的布局(可選)以及用于建立導向選項的菜單,這些都設置完之后,你就只添加監聽選中事件的listener就行了。
(1)在Res文件夾下新建menu文件夾,創建navigator_menu.xml文件
<menu xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" tools:context=".main.widget.MainActivity"> <group android:checkableBehavior="single"> <item android:id="@+id/navigation_item_news" android:icon="@m頭布局可以按照你自己的要求創建 如<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="200dp" android:orientation="vertical" android:background="?attr/color接下來在你的Activity initView()方法中找到控件并設置監聽 actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.open, R.string.close); actionBarDrawerToggle.syncState(); drawerLayout.setDrawerListener(actionBarDrawerToggle); //側邊欄 setupDrawerContent(navigatorView);監聽方法
private void setupDrawerContent(NavigationView navigatorView) { navigatorView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() { @Override public boolean onNavigationItemSelected(@NonNull MenuItem item) { mainPresenter.switchNavigation(item.getItemId()); item.setChecked(true); drawerLayout.closeDrawers(); return true; } }); }activity_main.xml
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" xmlns:app="http://schemas.android.com/apk/res-auto" android:id="@+id/drawer_layout" android:layout_width="match_parent" android:layout_height="match_parent" android:fitsSystemWindows="true" > <android.support.design.widget.CoordinatorLayout android:id="@+id/main_content" android:layout_width="match_parent" android:layout_height="match_parent"> <include android:id="@+id/appbar" layout="@layout/init_toolbar_title"/> <FrameLayout android:id="@+id/fragment" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_below="@+id/appbar" android:scrollbars="none" android:elevation="5dp" app:layout_behavior="@string/appbar_scrolling_view_behavior" /> </android.support.design.widget.CoordinatorLayout> <android.support.design.widget.NavigationView android:id="@+id/navigator_view" android:layout_width="wrap_content" android:layout_height="match_parent" android:layout_gravity="start" app:headerLayout="@layout/navigation_header" app:menu="@menu/navigation_menu" /></android.support.v4.widget.DrawerLayout>新聞熱點
疑難解答