DrawerLayout側滑菜單的簡單使用:
activity_main.xml:android
<?xml version="1.0" encoding="utf-8"?> <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.fitsoft.MainActivity"> <android.support.v4.widget.DrawerLayout android:layout_width="match_parent" android:layout_height="match_parent"> <!-- 第一個子View會做爲內容顯示區 --> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent"> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_gravity="center" android:gravity="center" android:text="這裏是主界面"/> </LinearLayout> <!-- 第二個子View會做爲側滑菜單 --> <LinearLayout android:layout_width="200dp" android:layout_height="match_parent" android:layout_gravity="start" android:background="#fff"> <ListView android:id="@+id/list_view" android:layout_width="match_parent" android:layout_height="match_parent"/> </LinearLayout> <!-- 第三個子View會做爲側滑菜單 --> <LinearLayout android:layout_width="200dp" android:layout_height="match_parent" android:layout_gravity="end" android:orientation="vertical" android:background="#fff"> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_gravity="center" android:gravity="center" android:layout_marginTop="200dp" android:text="用戶信息"/> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:layout_marginTop="40dp" android:text="退出登陸" /> </LinearLayout> </android.support.v4.widget.DrawerLayout> </android.support.constraint.ConstraintLayout>
主界面的DrawerLayout嵌套了三個LinearLayout,第一個做爲主界面顯示的內容,第二個做爲左側滑菜單,第三個做爲右側滑菜單。
MainActivity:app
package com.fitsoft; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.widget.ArrayAdapter; import android.widget.ListView; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ListView listView = findViewById(R.id.list_view); ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, new String[]{"菜單1","菜單2","菜單3","菜單4","菜單5"}); listView.setAdapter(adapter); } }
爲左側滑菜單的ListView配置數據源。
效果圖:ide