# Android Studio漢堡選單(左側選單)1 {%hackmd bVWcIzSWRcOp-bzo6RbA9A %} ## 主線任務-先做好選單的模板 ### 在XML建立左側選單 先建立選單底 圖 先在activity_main.xml檔 ![image](https://hackmd.io/_uploads/HytFBqxsT.png) ![image](https://hackmd.io/_uploads/SyjcrcgjT.png) ``` <androidx.drawerlayout.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/drawerLayout" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <com.google.android.material.navigation.NavigationView android:id="@+id/navigation_view" android:background="@color/white" android:layout_width="240dp" android:layout_gravity="start" android:layout_height="match_parent" app:headerLayout="@layout/navigation_header" app:menu="@menu/menu" tools:ignore="MissingConstraints" /> </androidx.drawerlayout.widget.DrawerLayout> ``` 用drawerLayout去包NavigationView(漢堡選單) 通常會在drawerLayout裡加RelativeLayout>用來處理當頁內容 圖 ``` <RelativeLayout android:layout_width="match_parent" android:layout_height="match_parent"> ...//新增內容 <FrameLayout android:id="@+id/fl_container" android:layout_width="match_parent" android:layout_height="match_parent"/>//範例:我新增FrameLayout到時候換頁在這換 </RelativeLayout> ``` ### 建立menu 建立漢堡選單裡的選項 圖 新增menu ![image](https://hackmd.io/_uploads/ryaofcxiT.png) res>new>android resource sirectory ![image](https://hackmd.io/_uploads/SkDWmqloT.png) 在menu裡新增xml檔 ![image](https://hackmd.io/_uploads/HkhXm5gi6.png) ![image](https://hackmd.io/_uploads/B1DVyVuTp.png) ``` <?xml version="1.0" encoding="utf-8"?> <menu xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto"> <group android:checkableBehavior="single" >//單選 //建立每個選項 <item android:id="@+id/action_home" android:icon="@drawable/location_map" android:title="首頁" /> <item android:id="@+id/action_book" android:icon="@drawable/bookmark" android:title="書籤" /> <item android:id="@+id/action_history" android:icon="@drawable/clock" android:title="歷史紀錄" /> <item android:id="@+id/action_setting" android:icon="@drawable/setting" android:title="設定" /> </group> </menu> ``` ### 建立title 建立漢堡選單裡的title 圖 在layout新增xml檔做title ![image](https://hackmd.io/_uploads/BJJRQ9es6.png) ![image](https://hackmd.io/_uploads/H1wBxNOpT.png) ``` <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="160dp" android:background="#619B8A" android:gravity="bottom" android:orientation="vertical"> <ImageView android:layout_width="64dp" android:layout_height="64dp" android:contentDescription="@null" android:src="@drawable/anya062516" /> <TextView android:id="@+id/txtHeader" android:layout_width="wrap_content" android:layout_height="wrap_content" android:ellipsize="end" android:paddingTop="4dp" android:text="估狗在搞我" android:textColor="#ffffff" /> </LinearLayout> ```