Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

DrawerLayout 抽屜式側邊菜單完整實作範例

編輯:關於 Android 程式設計

DrawerLayout 是 Android 官方支援庫提供的側滑抽屜容器, Gmail、微信這類應用都很常見。它需要搭配 ActionBarDrawerToggle 才能讓 ActionBar 上的 App 圖示變成開關抽屜的漢堡選單,並在選單被點擊時同步狀態。

一、版面配置

activity_main.xml

<!-- android.support.v4.widget.DrawerLayout 為抽屜容器 -->
<android.support.v4.widget.DrawerLayout
    xmlns:android="https://schemas.android.com/apk/res/android"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <!-- 主要內容區 -->
    <FrameLayout
        android:id="@+id/content_frame"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <!-- 抽屜內容,layout_gravity 決定從左側或右側滑出 -->
    <ListView
        android:id="@+id/left_drawer"
        android:layout_width="240dp"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:choiceMode="singleChoice"
        android:divider="@android:color/transparent"
        android:dividerHeight="0dp" />
</android.support.v4.widget.DrawerLayout>

fragment_content.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <TextView
        android:id="@+id/textView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="25sp" />
</LinearLayout>

二、主要程式碼

MainActivity.java

package com.xuliugen.drawerlayout;

import java.util.ArrayList;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.content.Intent;
import android.content.res.Configuration;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.widget.DrawerLayout;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class MainActivity extends Activity implements OnItemClickListener {
    private DrawerLayout mDrawerLayout;   // 抽屜容器
    private ListView mDrawerList;         // 左側抽屜的清單
    private ArrayList<String> menuLists;
    private ArrayAdapter<String> adapter;
    private ActionBarDrawerToggle mDrawerToggle;  // 負責 ActionBar 圖示的開關切換
    private String mTitle;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mTitle = (String) getTitle();
        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        mDrawerList = (ListView) findViewById(R.id.left_drawer);

        menuLists = new ArrayList<String>();
        for (int i = 0; i < 5; i++) {
            menuLists.add("item" + i);
        }

        // 初始化並綁定資料
        adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, menuLists);
        mDrawerList.setAdapter(adapter);
        mDrawerList.setOnItemClickListener(this);

        // 抽屜開關與 ActionBar 的整合
        mDrawerToggle = new ActionBarDrawerToggle(
                this,
                mDrawerLayout,
                R.drawable.ic_drawer,
                R.string.drawer_open,
                R.string.drawer_close) {

            /** 抽屜被拉開時 */
            @Override
            public void onDrawerOpened(View drawerView) {
                super.onDrawerOpened(drawerView);
                getActionBar().setTitle("請選擇");
                invalidateOptionsMenu(); // 觸發 onPrepareOptionsMenu()
            }

            /** 抽屜被關閉時 */
            @Override
            public void onDrawerClosed(View drawerView) {
                super.onDrawerClosed(drawerView);
                getActionBar().setTitle(mTitle);
                invalidateOptionsMenu(); // 重繪 ActionBar 上的選單項
            }
        };

        mDrawerLayout.setDrawerListener(mDrawerToggle);

        // 啟用 ActionBar 上 App 圖示的點擊:點擊可開關抽屜
        getActionBar().setDisplayHomeAsUpEnabled(true);
        getActionBar().setHomeButtonEnabled(true);
    }

    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        boolean isDrawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
        menu.findItem(R.id.action_websearch).setVisible(!isDrawerOpen);
        return super.onPrepareOptionsMenu(menu);
    }

    /** 選單項設定 */
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    /** ActionBar 圖示的點擊事件 */
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // 把 ActionBar 上的圖示點擊交給 DrawerToggle 處理
        if (mDrawerToggle.onOptionsItemSelected(item)) {
            return true;
        }
        switch (item.getItemId()) {
            case R.id.action_websearch:
                Intent intent = new Intent();
                intent.setAction(Intent.ACTION_VIEW);
                Uri uri = Uri.parse("https://blog.csdn.net/xlgen157387");
                intent.setData(uri);
                startActivity(intent);
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    /** 依官方文件建議,把 syncState() 放進 onPostCreate */
    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        // 同步 ActionDrawerToggle 與 DrawerLayout 的狀態,
        // 並把 drawer 圖示設為 ActionBar 的 Home 按鈕圖示
        mDrawerToggle.syncState();
    }

    /** 螢幕旋轉時也需要同步設定 */
    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        mDrawerToggle.onConfigurationChanged(newConfig);
    }

    /** 點擊選單項時切換對應的 Fragment */
    @Override
    public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
        // 動態建立 Fragment 並塞進 FrameLayout
        Fragment contentFragment = new ContentFragment();
        Bundle bundle = new Bundle();
        bundle.putString("text", menuLists.get(position));
        contentFragment.setArguments(bundle);

        FragmentManager fm = getFragmentManager();
        fm.beginTransaction().replace(R.id.content_frame, contentFragment).commit();

        mDrawerLayout.closeDrawer(mDrawerList);
    }
}

ContentFragment.java

package com.xuliugen.drawerlayout;

import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

/** 用於填充內容區的 Fragment */
public class ContentFragment extends Fragment {
    private TextView textView;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_content, container, false);
        textView = (TextView) view.findViewById(R.id.textView);
        // 取得傳入的參數並顯示
        String text = getArguments().getString("text");
        textView.setText(text);
        return view;
    }
}

三、幾個實務提醒

DrawerLayout 的抽屜寬度建議不要超過螢幕寬度,官方指引是以 320dp 為上限,實務上常用 240dp 到 300dp,太寬會讓內容區看起來像被切掉一半。

onPostCreate() 裡的 syncState() 不能省,少了它,抽屜拉開後 ActionBar 的漢堡圖示不會變成箭頭。

另外,抽屜打開時建議呼叫 invalidateOptionsMenu() 讓選單依狀態調整,這也是範例裡在 onDrawerOpened 與 onDrawerClosed 都呼叫它的原因。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved