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

Android 自定義局部導航菜單:以自訂 View 實作可移動選單

編輯:關於 Android 程式設計

為什麼不用現成方案

實作導航的做法不少,常見的有兩種:一是 3.0 以上自帶的 Toolbar 搭配 Fragment,二是 TabHost。但兩者都有個明顯限制——位置太固定。Toolbar 只能待在標題欄處(除非改原始碼),TabHost 雖然比直接繼承 TabActivity 靈活,卻缺少選項切換動畫。

但有時候我們只是想在某個畫面的一角貼一小塊導航,用來切換內容或設定。這種時候搬出 Toolbar 或 TabHost 都有點大材小用。近期專案正好有此需求,於是查了些資料。

基本原理

其實思路很單純:上面一排 tab 用 Button 或 TextView 都能勝任,只要能響應點擊;下面擺一個 ImageView 作為指示器。預設停在 tab1,點了 tab3 之後,這個 ImageView 就從 tab1 的位置移動到 tab3 並停住。

為什麼選 Java 動態實作

這類需求一般有兩條路:寫在 XML 裡,或用 Java 程式碼動態建立。「XML 描述介面、Java 控制邏輯」的分離是 Android 的設計亮點,但在這個場景下卻有明顯侷限:今天專案有 3 個 tab,明天變成 4 個,除了改 XML 還得改底層實作(例如 ImageView 寬度的壓縮比例)。為了移植性與擴充性,我選擇直接繼承 LinearLayout,用程式碼生成。

步驟一:宣告自定義屬性

子類化 LinearLayout(換成其他 ViewGroup 也可以,看個人偏好):

public class CustomMenu extends LinearLayout implements OnClickListener

在 res/values/attrs.xml 中宣告:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="CustomMenu">
        <attr name="buttonNumber" format="integer" />
        <attr name="indexbitmap" format="reference" />
        <attr name="buttonHeight" format="dimension" />
    </declare-styleable>
</resources>
  • buttonNumber:tab 數量
  • indexbitmap:移動的指示圖片
  • buttonHeight:導航欄高度

步驟二:佈局檔中使用

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:custommenu="https://schemas.android.com/apk/res/com.example.fragmentdemo"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <TextView
        android:layout_width="match_parent"
        android:layout_height="30dp"
        android:text="@string/hello_world" />

    <com.example.fragmentdemo.fragmentmenu.CustomMenu
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        custommenu:buttonNumber="5"
        custommenu:buttonHeight="40dp"
        custommenu:indexbitmap="@drawable/a" >
    </com.example.fragmentdemo.fragmentmenu.CustomMenu>

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />
</LinearLayout>

刻意在上下各放一個 TextView,就是為了示範 CustomMenu 的寬高可自由使用 match_parent、wrap_content 或固定 dp,不會與外層佈局互相牽制。

步驟三:讀取自定義屬性

private void readXML(Context context, AttributeSet attr) {
    TypedArray a = context.obtainStyledAttributes(attr, R.styleable.CustomMenu);
    // 讀取按鈕數量
    buttonNumber = a.getInt(R.styleable.CustomMenu_buttonNumber, 4);
    // 讀取按鈕高度
    buttonHeight = (int) a.getDimension(R.styleable.CustomMenu_buttonHeight, 30);
    // 讀取指示圖片
    int bitmapID = a.getResourceId(R.styleable.CustomMenu_indexbitmap, R.drawable.a);
    bitmap = BitmapFactory.decodeResource(getResources(), bitmapID);
    bitmap_width = bitmap.getWidth();
    a.recycle();
}

注意 buttonNumber、buttonHeight、bitmap、bitmap_width 都是成員屬性,後續多處會用到。

步驟四:動態建立 tab

// 本身設為縱向
setOrientation(LinearLayout.VERTICAL);

// 建立一個橫向 LinearLayout,高度為指定值
LayoutParams p = new LayoutParams(LayoutParams.MATCH_PARENT, buttonHeight);
LinearLayout linearLayout = new LinearLayout(context);
linearLayout.setOrientation(LinearLayout.HORIZONTAL);
linearLayout.setPadding(0, 0, 0, 0);
linearLayout.setGravity(Gravity.CENTER);
addView(linearLayout, p);

// 依指定數量加入 Button
LayoutParams btn_p = new LayoutParams(LayoutParams.MATCH_PARENT, buttonHeight, 1);
for (int i = 0; i < buttonNumber; i++) {
    Button button = new Button(context);
    button.setText("按鈕" + i);
    button.setTextSize(15);
    button.setBackgroundColor(getResources().getColor(R.color.defaultColor));
    button.setId(ID + i);
    button.setOnClickListener(this);
    button_container.add(button);
    linearLayout.addView(button, btn_p);
}

每個 Button 的 weight 設為 1,因此會自動等寬填滿。文字與背景色先給了預設值,實務上可以再往 XML 屬性擴充,或對外暴露 setter 讓呼叫方自訂。

這裡有個刻意安排的細節——ID 起始值:

private static final int ID = 0xcc33cc;

用來在 onClick 中辨識是哪個 tab。用 ID 而非其他標記的好處,稍後會看到。

步驟五:加入指示 ImageView

imageView = new ImageView(context);
LayoutParams iv_p = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
iv_p.setMargins(0, 5, 0, 0);
addView(imageView, iv_p);

此時先不設定圖片內容,因為尺寸必須依 tab 寬度動態決定,在建構子階段還無法確定。

步驟六:在 onMeasure 中取得自身尺寸

protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    // 此方法預設會被呼叫兩次,這裡只執行一次
    if (width == 0 || height == 0) {
        width = MeasureSpec.getSize(widthMeasureSpec);
        height = MeasureSpec.getSize(heightMeasureSpec);
        initial();
    }
}

onMeasure 是依傳入參數決定控件大小的時機,通常用來做動態伸縮。這裡只取出寬高,剩下的初始化交給 initial()。用 if 限制只跑一次,是因為此方法預設會被呼叫兩次(初次繪製與填充子控件後各一次)。

步驟七:完成初始化

// 若圖片比單個 tab 寬,則縮放圖片
if (bitmap_width > width / buttonNumber) {
    bitmap = dealBitmap(bitmap, (float) (width) / buttonNumber / bitmap_width);
}

private Bitmap dealBitmap(Bitmap bitmap, float bili) {
    Matrix matrix = new Matrix();
    matrix.postScale(bili, bili);
    return Bitmap.createBitmap(bitmap, 0, 0,
            bitmap.getWidth(), bitmap.getHeight(), matrix, true);
}

預設縮放到與 tab 等寬,這個範圍也可以自行調整,甚至透過回呼介面開放給外部設定。

// 計算置中偏移
imageView_offset = (width / buttonNumber - bitmap_width) / 2;
imageView.setImageBitmap(bitmap);
initialImageViewOffset();
private void initialImageViewOffset() {
    if (imageView_offset > 0) {
        Matrix matrix = new Matrix();
        matrix.postTranslate(imageView_offset, 0);
        imageView.setImageMatrix(matrix);
    }
}

這裡判斷 offset 是否大於 0,是因為若圖片原本就比 tab 寬,前面已被縮放到等寬,offset 自然為 0,可以省掉一次無效運算。

步驟八:處理點擊與移動動畫

public void onClick(View v) {
    // 從當前項移動到點擊項
    moveImageView(cur_index, v.getId() - ID);
    cur_index = v.getId() - ID;
}

用 ID 偏移量當索引的好處就在這裡——不必維護額外的對照表。

private void moveImageView(int start, int end) {
    // 需移動的距離
    int length = (2 * imageView_offset + bitmap_width) * (end - start);
    // 初始位置:預設 ImageView 距左側 imageView_offset 處
    int offset = (2 * imageView_offset + bitmap_width) * start;

    Animation animation = new TranslateAnimation(offset, offset + length, 0, 0);
    // 動畫結束後停留在終點
    animation.setFillAfter(true);
    animation.setDuration(300);
    imageView.startAnimation(animation);
}

其中 start 為當前 tab 索引(從 0 起算),end 為點擊的 tab 索引。舉例來說,一開始點 tab3 則 start=0、end=3;接著點 tab2 則 start=3、end=2。中間的位移有動畫過渡,而不是硬邦邦地瞬移。

可再擴充的方向

目前只做了最基本的呈現。若要更完整,還可以:為每個 tab 加上 selector 以呈現按下態、對外暴露監聽器回呼點擊事件、把指示圖片的縮放比例開放設定,或在 onMeasure 中進一步處理 wrap_content 情境下的尺寸計算。

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