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

Android 自定義 TitleView 實作:一次封裝,處處複用的標題欄

編輯:關於 Android 程式設計

專案裡常常需要重複定義相同樣式的標題欄。Android 先後推出了 ActionBar 與 ToolBar,但實務上難免遇到不合用的地方——例如標題需要置中時,就得自己改 ToolBar 的 XML。

與其每個頁面重寫一次,不如封裝一個自定義 TitleView。以下示範如何打造一個能符合常見設計稿風格、同時支援左右多按鈕組合的標題欄。

先看成果

前期準備一:預定義 id

在 values 下的 ids.xml 中預先配置各元素 id:

<?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>

可以看到:左側有兩種形態(ImageView/TextView),右側則可同時存在圖片按鈕與文字按鈕的組合。

前期準備二:定義自訂屬性

在 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:layout_height="50dp"
    android:background="#0093fe"
    title:title_name="標題"
    title:title_text_color="@android:color/white"
    title:title_text_size="20sp"
    title:small_text_size="15sp"
    title:left_text="返回"
    title:left_text_drawable_left="@mipmap/back_normal"
    title:right_text="@string/more"
    title:right_text_drawable_right="@mipmap/bar_button_right"
    title:right_image_two="@mipmap/icon_crop_rotate"/>

自訂類別繼承 RelativeLayout,選擇它的原因是相對定位更方便控制各元素的相對關係。

第一步是取得 TypedArray,所有自訂屬性的值都從它讀取:

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

接著處理左側返回按鈕。文字可能來自 string 資源,也可能是直接賦值,因此需要分兩種情況取值:

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);

大於 0 表示定義在 string 中,用 getResources().getText() 取值;等於 0 則直接取值。取到之後,任何 View 要加入容器都得先設定寬高:

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

抽成獨立方法後,後續用 LayoutParams params = initLayoutParams(); 即可取得預設寬高——高度填滿父容器,寬度自適應。接著建立 TextView:

/**
 * 建立 TextView
 * @param context Context
 * @param id TextView 的 id
 * @param charSequence 要顯示的文字
 * @param params 相對布局參數
 * @return 已初始化的 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;
}

建立好之後,透過自訂屬性 left_text_drawable_left/right 設定左右圖示(上下同理):

/**
 * 設定 TextView 的 Drawable
 */
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);
}

呼叫方式:

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

由於用的是相對布局,必須明確指定位置規則:

params.addRule(RelativeLayout.ALIGN_PARENT_LEFT);   // 靠左對齊

字型大小則用 small_text_size(兩側文字)與 title_text_size(標題文字)兩個屬性控制:

/**
 * 從 TypedArray 取得 dimension 像素值
 */
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);

文字顏色同理:

/**
 * 取得文字顏色
 */
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));

至此,左側的文字按鈕(含圖文組合)已完成。其餘按鈕依相同模式逐一加入容器即可,這裡不再贅述。

封裝的價值

這個元件做完之後,標題欄就成了一個可宣告式設定的黑盒子:要幾顆按鈕、文字還是圖示、置中還是靠右,全部在 XML 裡決定,不必每個頁面重複 coding。這也是自定義 View 相對於複製貼上最大的意義——樣式一改,全站同步。

以上就是本次分享,若有任何疑問歡迎留言,我會盡快回覆。也非常感謝大家對本站的支持!

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