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

Android 自定義 TitleView:打造可重複使用、樣式彈性的標題欄

編輯:關於 Android 開發

Android 自定義 TitleView:打造可重複使用、樣式彈性的標題欄

在 Android 開發過程中,經常會遇到同一個專案裡需要重複定義相同樣式的標題欄。Android 先後推出了 actionBar、toolBar,相信用過的朋友也會遇到一些不如意的時候,例如想讓標題置中時,就得自訂 XML 交給 toolBar 處理。本文要介紹的是另一條路——自定義一個 TitleBar,以滿足國內常見主題風格的樣式需求。

先上效果圖:

前期準備

1. 為標題欄的元件預先定義 id,放在 values 下的 ids.xml 中:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <item name="tv_title_name" type="id"/>
    <item name="tv_left_text" type="id"/>
    <item name="iv_left_image" type="id"/>
    <item name="iv_right_image" type="id"/>
    <item name="iv_right_image_two" type="id"/>
    <item name="tv_right_text" type="id"/>
    <item name="tv_right_text_two" type="id"/>
</resources>

可以看到這裡定義了左側返回按鈕、標題、右側按鈕等 id。左側分 ImageView/TextView 兩種情況,右側則可同時存在圖片按鈕與文字按鈕的組合。

2. 自定義標題欄屬性,放在 values 下的 attr.xml 中:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <!-- 標題屬性 -->
    <declare-styleable name="TitleAttr">
        <attr name="title_name" format="reference|string"/>
        <attr name="title_text_color" format="reference|color"/>
        <attr name="title_drawable_right" format="reference"/>
        <attr name="title_drawable_left" format="reference"/>
        <attr name="title_text_size" format="reference|dimension"/>
        <attr name="left_text" format="reference|string"/>
        <attr name="left_image" format="reference"/>
        <attr name="small_text_size" format="reference|dimension"/>
        <attr name="title_gravity">
            <enum name="left" value="3"/>
            <enum name="center" value="17"/>
            <enum name="right" value="5"/>
        </attr>
        <attr name="right_image" format="reference"/>
        <attr name="right_text" format="reference|string"/>
        <attr name="right_image_two" format="reference"/>
        <attr name="right_text_two" format="reference|string"/>
        <attr name="title_height" format="dimension"/>
        <attr name="right_text_drawable_right" format="reference"/>
        <attr name="right_text_drawable_left" format="reference"/>
        <attr name="right_text_two_drawable_right" format="reference"/>
        <attr name="right_text_two_drawable_left" format="reference"/>
        <attr name="left_text_drawable_right" format="reference"/>
        <attr name="left_text_drawable_left" format="reference"/>
    </declare-styleable>
</resources>

編碼實作

有了前面的準備後,就可以開始實作。先看看在 XML 中如何引入我們自定義的控制項:

<com.jarek.library.TitleView
    android:id="@+id/title_main"
    android:layout_width="match_parent"
    android:background="#0093fe"
    title:title_name="標題"
    title:right_text="@string/more"
    title:title_text_color="@android:color/white"
    title:right_image_two="@mipmap/icon_crop_rotate"
    title:title_text_size="20sp"
    title:small_text_size="15sp"
    title:left_text="返回"
    title:left_text_drawable_left="@mipmap/back_normal"
    title:right_text_drawable_right="@mipmap/bar_button_right"
    android:layout_height="50dp"/>

這裡的 title 標籤就是我們自定義的。首先建立一個類別繼承自 RelativeLayout(選它當父容器,是因為 RelativeLayout 便於控制相對位置)。接著要取得 TypedArray 物件,所有自定義屬性的值都透過它來讀取:

TypedArray typeArray = context.obtainStyledAttributes(attrs, R.styleable.TitleAttr);

取得 typedArray 後,就能開始把按鈕加入容器中。先看左邊第一個返回按鈕如何加上去:

int leftText = typeArray.getResourceId(R.styleable.TitleAttr_left_text, 0);
CharSequence charSequence = leftText > 0
        ? typeArray.getResources().getText(leftText)
        : typeArray.getString(R.styleable.TitleAttr_left_text);

這裡的 left_text 表示左側 TextView 顯示的文字,可以是 string 資源,也可以是直接輸入的字串。判斷策略是:值大於 0 代表定義在 string 中,用 getText() 取值;等於 0 則直接取值,表示是直接賦值。取到值後要賦給 TextView,得先給它寬高(所有控制項都需要):

/** LayoutParams of RelativeLayout */
private LayoutParams initLayoutParams() {
    return new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);
}

單獨抽成一個方法後,後續就能直接透過 LayoutParams params = initLayoutParams(); 取得預設寬高——高度填滿父容器、寬度自適應。接著 new 一個 TextView:

/** create TextView */
@NonNull
private TextView createTextView(Context context, int id, CharSequence charSequence, LayoutParams params) {
    TextView textView = new TextView(context);
    textView.setLayoutParams(params);
    textView.setGravity(Gravity.CENTER);
    textView.setId(id);
    textView.setMinWidth((int) getPixelSizeByDp(minViewWidth));
    textView.setText(charSequence);
    return textView;
}

可以看到我們傳入了預設 id、要顯示的內容,以及前面給定的 LayoutParams。建立好 TextView 後,還可以透過自定義屬性 left_text_drawable_right、left_text_drawable_left 設定左右(以及上下)的 Drawable:

/** drawable of TextView */
private void setTextViewDrawable(TypedArray typeArray, int leftDrawableStyleable, int rightDrawableStyleable, TextView textView) {
    int leftDrawable = typeArray.getResourceId(leftDrawableStyleable, 0);
    int rightDrawable = typeArray.getResourceId(rightDrawableStyleable, 0);
    textView.setCompoundDrawablePadding((int) getPixelSizeByDp(drawablePadding));
    textView.setCompoundDrawablesWithIntrinsicBounds(leftDrawable, 0, rightDrawable, 0);
}

同樣抽成方法,呼叫時只要傳入對應的 styleable 即可:

setTextViewDrawable(typeArray, R.styleable.TitleAttr_left_text_drawable_left, R.styleable.TitleAttr_left_text_drawable_right, mLeftBackTextTv);

建立好 TextView 後,因為用的是相對布局,需要指定位置規則:

params.addRule(RelativeLayout.ALIGN_PARENT_LEFT);

這裡是居左顯示。同時還可以透過 small_text_size(兩側文字)與 title_text_size(標題文字)來設定字體大小:

/** get the dimension pixel size from typeArray which is defined in attr */
private float getDimensionPixelSize(TypedArray typeArray, int stylable, int defaultSize) {
    int sizeStyleable = typeArray.getResourceId(stylable, 0);
    return sizeStyleable > 0
            ? typeArray.getResources().getDimensionPixelSize(sizeStyleable)
            : typeArray.getDimensionPixelSize(stylable, (int) getPiselSizeBySp(defaultSize));
}

然後這樣設定字體大小:

float textSize = getDimensionPixelSize(typeArray, R.styleable.TitleAttr_small_text_size, defaultSmallTextSize);
mLeftBackTextTv.setTextSize(TypedValue.COMPLEX_UNIT_PX, textSize);

文字顏色也同理:

/** get textColor */
private int getTextColorFromAttr(TypedArray typeArray) {
    int textColorStyleable = typeArray.getResourceId(R.styleable.TitleAttr_title_text_color, 0);
    if (textColorStyleable > 0) {
        return typeArray.getResources().getColor(textColorStyleable);
    } else {
        return typeArray.getColor(R.styleable.TitleAttr_title_text_color, textColor);
    }
}

呼叫方法設定顏色:

mLeftBackTextTv.setTextColor(getTextColorFromAttr(typeArray));

到這裡為止,左側的第一個文字按鈕(或文字帶圖片的按鈕)就建立完成了。其他按鈕依同樣的道理逐一加入容器即可,不再贅述。至此,我們需要的 titleView 就完成了,以後各處都能直接引用,不必每個地方重複 coding。

專案地址:github 源碼下載

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