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

自定義組合控件 Titlebar 完整實踐:從自定義屬性到代碼布局

編輯:關於 Android 程式設計

前言:我相信「天生我才必有用」這句話。每個人都有自己的作用,也許相對別人不明顯,也許只是為了取悅他人,但請別忘了,我們可以透過持續努力把價值提上來。

日常 Android 開發裡有個反覆出現的困擾:每次都要自己寫一份標題欄布局,或者引入了布局之後每次都得重複初始化裡面的控件。為了解決這個問題,Google 先後推出了 ActionBar 與後來的 Toolbar,讓開發變得輕鬆不少——比如 Toolbar 搭配 DrawerLayout,很快就能做出側滑選單效果。這類控件的出現大幅減輕了開發者的負擔,相信未來會有更多類似的好東西出現。

本文要介紹一個自己組合出來的 Titlebar 控件,用來簡化日常開發。老實說這是個體力活(技術含量有限),所以先看看效果,如果你閉著眼睛都能寫出來,可以直接跳到文末。

實現思路是:自定義屬性 + 繼承 ViewGroup + 在建構子中用程式碼添加子 View。先從屬性開始。

一、定義自定義屬性

<declare-styleable name="Titlebar">
    <attr name="leftButtonText" format="string" />
    <attr name="leftButtonTextColor" format="color" />
    <attr name="leftButtonTextSize" format="dimension" />
    <attr name="leftButtonImage" format="reference" />
    <attr name="titleText" format="string" />
    <attr name="titleColor" format="color" />
    <attr name="titleSize" format="dimension" />
    <attr name="rightButtonText" format="string" />
    <attr name="rightButtonTextColor" format="color" />
    <attr name="rightButtonTextSize" format="dimension" />
    <attr name="rightButtonImage" format="reference" />
</declare-styleable>

幾點補充:

1. 技術上你可以直接在 attrs.xml 的 resources 節點下定義屬性並在布局中使用,但這種做法不推薦——把屬性收攏到一個 declare-styleable 集合裡,管理與維護都更方便。
2. 如果自定義屬性與系統屬性重名,且型別一致,可以直接在 declare-styleable 中引用系統屬性(加一個 attr 節點但不寫 format)。
3. 別忘了在布局中引入命名空間:xmlns:lt="https://schemas.android.com/apk/res-auto"。

二、繼承 ViewGroup 完成控件組合

觀察效果圖,用 RelativeLayout 是最省事的做法。新建一個類繼承它,覆寫三個建構子,並在建構子中讀出自定義屬性:

private void init(Context context, AttributeSet attrs) {
    TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.Titlebar);

    mLeftButtonText = typedArray.getString(R.styleable.Titlebar_leftButtonText);
    mLeftButtonTextColor = typedArray.getColor(
            R.styleable.Titlebar_leftButtonTextColor, Color.GRAY);
    mLeftButtonSize = typedArray.getDimension(
            R.styleable.Titlebar_leftButtonTextSize,
            TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 16,
                    getResources().getDisplayMetrics()));
    mLeftButtonImage = typedArray.getDrawable(R.styleable.Titlebar_leftButtonImage);

    mTitleButtonText = typedArray.getString(R.styleable.Titlebar_titleText);
    mTitleButtonTextColor = typedArray.getColor(
            R.styleable.Titlebar_titleColor, Color.GRAY);
    mTitleButtonSize = typedArray.getDimension(
            R.styleable.Titlebar_titleSize,
            TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 16,
                    getResources().getDisplayMetrics()));

    mRightButtonText = typedArray.getString(R.styleable.Titlebar_rightButtonText);
    mRightButtonTextColor = typedArray.getColor(
            R.styleable.Titlebar_rightButtonTextColor, Color.GRAY);
    mRightButtonSize = typedArray.getDimension(
            R.styleable.Titlebar_rightButtonTextSize,
            TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 16,
                    getResources().getDisplayMetrics()));
    mRightButtonImage = typedArray.getDrawable(R.styleable.Titlebar_rightButtonImage);

    typedArray.recycle();
}

注意最後那句 recycle()。用過的 TypedArray 一定要回收,就像用過資料庫連線要關閉、用過 IO 串流要關得一樣,養成習慣。

屬性拿到了,接著用程式碼把左側按鈕、中間標題、右側按鈕建起來:

private void initView(Context context) {
    // 左側:未提供圖片但提供了文字時,建立文字按鈕
    if (mLeftButtonImage == null && mLeftButtonText != null) {
        mLeftTextView = new TextView(context);
        mLeftTextView.setText(mLeftButtonText);
        mLeftTextView.setTextColor(mLeftButtonTextColor);
        mLeftTextView.setTextSize(mLeftButtonSize);
        RelativeLayout.LayoutParams leftParams = new RelativeLayout.LayoutParams(
                LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        leftParams.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
        leftParams.addRule(RelativeLayout.CENTER_VERTICAL);
        addView(mLeftTextView, leftParams);
    } else if (mLeftButtonImage != null) {
        // 提供了圖片,建立圖片按鈕
        RelativeLayout.LayoutParams leftParams = new RelativeLayout.LayoutParams(
                LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        leftParams.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
        leftParams.addRule(RelativeLayout.CENTER_VERTICAL);
        mLeftButton = new ImageView(context);
        mLeftButton.setImageDrawable(mLeftButtonImage);
        addView(mLeftButton, leftParams);
    }

    // 中間標題
    if (mTitleButtonText != null) {
        TextView titleTextView = new TextView(context);
        titleTextView.setText(mTitleButtonText);
        titleTextView.setTextColor(mTitleButtonTextColor);
        titleTextView.setTextSize(mTitleButtonSize);
        RelativeLayout.LayoutParams titleParams = new RelativeLayout.LayoutParams(
                LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        titleParams.addRule(RelativeLayout.CENTER_IN_PARENT);
        addView(titleTextView, titleParams);
    }

    // 右側邏輯與左側對稱
    if (mRightButtonImage == null && mRightButtonText != null) {
        mRightTextView = new TextView(context);
        mRightTextView.setText(mRightButtonText);
        mRightTextView.setTextColor(mRightButtonTextColor);
        mRightTextView.setTextSize(mRightButtonSize);
        RelativeLayout.LayoutParams rightParams = new RelativeLayout.LayoutParams(
                LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        rightParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
        rightParams.addRule(RelativeLayout.CENTER_VERTICAL);
        addView(mRightTextView, rightParams);
    } else if (mRightButtonImage != null) {
        RelativeLayout.LayoutParams rightParams = new RelativeLayout.LayoutParams(
                LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        rightParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
        rightParams.addRule(RelativeLayout.CENTER_VERTICAL);
        mRightButton = new ImageView(context);
        mRightButton.setImageDrawable(mRightButtonImage);
        addView(mRightButton, rightParams);
    }
}

說明:左右兩側按鈕都支援文字與圖片兩種形態,所以我用兩組控件分別承載;一旦設定了圖片,就不會再添加文字按鈕。

三、為按鈕加上事件監聽

先定義一個回呼介面:

public interface OnButtonClickListener {
    void onLeftClick();
    void onRightClick();
}

再統一綁定監聽,把文字與圖片兩種形態都涵蓋進去:

public void setOnButtonClickListener(final OnButtonClickListener onButtonClickListener) {
    if (onButtonClickListener == null) {
        return;
    }
    if (mLeftTextView != null) {
        mLeftTextView.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                onButtonClickListener.onLeftClick();
            }
        });
    }
    if (mLeftButton != null) {
        mLeftButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                onButtonClickListener.onLeftClick();
            }
        });
    }
    if (mRightTextView != null) {
        mRightTextView.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                onButtonClickListener.onRightClick();
            }
        });
    }
    if (mRightButton != null) {
        mRightButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                onButtonClickListener.onRightClick();
            }
        });
    }
}

四、在布局中使用

include_titlebar.xml:

<com.lt.titlebar.Titlebar
    xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:lt="https://schemas.android.com/apk/res-auto"
    android:id="@+id/titlebar"
    android:layout_width="match_parent"
    android:layout_height="60dp"
    android:background="#ea8010"
    android:padding="10sp"
    lt:leftbuttontext="返回"
    lt:leftbuttontextcolor="@android:color/white"
    lt:leftbuttontextsize="8sp"
    lt:rightbuttontext="完成"
    lt:rightbuttontextcolor="@android:color/white"
    lt:rightbuttontextsize="8sp"
    lt:titletext="標題"
    lt:titlecolor="@android:color/white"
    lt:titlesize="8sp" />

左右兩側各有文字與圖片兩種形態,因此共有四種組合:文字+文字、文字+圖片、圖片+文字、圖片+圖片。需要標題欄時,直接 include 這個布局即可。

在 Activity 中初始化並設定監聽:

Titlebar titlebar = (Titlebar) findViewById(R.id.titlebar);
titlebar.setOnButtonClickListener(new Titlebar.OnButtonClickListener() {
    @Override
    public void onLeftClick() {
        Toast.makeText(MainActivity.this, "左側按鈕被點擊了", 0).show();
    }

    @Override
    public void onRightClick() {
        Toast.makeText(MainActivity.this, "右側按鈕被點擊了", 0).show();
    }
});

寫下來確實就是體力活,但它鍛鍊的是「用程式碼建立並佈置控件」這項基本功,而這項能力在做定製化控件時隨時都用得上。

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