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

安卓自定義控件入門:三步寫出一個可復用的 TopBar

編輯:關於 Android 程式設計

作為一名自學安卓的新手,今天第一次發技術總結,還是有點小激動。廢話少說,直接進入主題——用一個自定義 TopBar 的 demo,把自定義控件的完整流程走一遍。

這個 TopBar 的結構很典型:左邊一個 Button、中間一個標題、右邊一個 Button。麻雀雖小五臟俱全,把這個例子吃透,自定義控件的基本套路就算掌握了。

先看效果:

整個過程可以拆成三步:

1. 在 XML 文件中定義控件需要的屬性

2. 編寫一個類,讀取這些屬性並組裝出 View

3. 在布局中引用這個自定義 View

第一步:定義自定義屬性

在 res/values 目錄下新建 attrs.xml:

<resources>
    <declare-styleable name="TopBar">
        <!-- 中間標題的文本內容、字號、顏色 -->
        <!-- 左邊按鈕的文本、文本顏色、背景 -->
        <!-- 右邊按鈕的文本、文本顏色、背景 -->
    </declare-styleable>
</resources>

每個屬性都需要通過 name 與 format 兩個字段聲明,format 用來指定屬性類型(string、color、dimension、reference 等)。上面為了精簡省略了具體的 attr 標簽,實際使用時需要逐一寫全,例如:

<attr name="leftText" format="string" />
<attr name="leftTextColor" format="color" />
<attr name="leftBackground" format="reference|color" />
<attr name="tittleTextSize" format="dimension" />

第二步:讀取屬性並組裝 View

新建 TopBar 類並繼承 RelativeLayout,實現帶兩個參數的構造方法 TopBar(Context context, AttributeSet attrs)。這個雙參數構造方法是必須的,否則在 XML 中引用時會直接報異常被 inflate 出來。

public class TopBar extends RelativeLayout {

    private Button leftButton, rightButton;
    private TextView tvTittle;

    private int leftTextColor;
    private Drawable leftBackground;
    private String leftText;

    private int rightTextColor;
    private Drawable rightBackground;
    private String rightText;

    private String tittle;
    private float tittleTextSize;
    private int tittleTextColor;

    private LayoutParams leftParams, rightParams, tittleParams;

    public TopBar(Context context, AttributeSet attrs) {
        super(context, attrs);

        // TypedArray 是讀取自定義屬性的關鍵數據結構
        TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.TopBar);

        leftTextColor = ta.getColor(R.styleable.TopBar_leftTextColor, 0);
        leftBackground = ta.getDrawable(R.styleable.TopBar_leftBackground);
        leftText = ta.getString(R.styleable.TopBar_leftText);

        rightTextColor = ta.getColor(R.styleable.TopBar_rightTextColor, 0);
        rightBackground = ta.getDrawable(R.styleable.TopBar_rightBackground);
        rightText = ta.getString(R.styleable.TopBar_rightText);

        tittle = ta.getString(R.styleable.TopBar_tittle);
        tittleTextColor = ta.getColor(R.styleable.TopBar_tittleTextColor, 0);
        tittleTextSize = ta.getDimension(R.styleable.TopBar_tittleTextSize, 0);

        ta.recycle();   // 及時回收資源

        // 自定義 View 內部不能用 findViewById,只能 new
        leftButton = new Button(context);
        rightButton = new Button(context);
        tvTittle = new TextView(context);

        leftButton.setTextColor(leftTextColor);
        leftButton.setBackground(leftBackground);
        leftButton.setText(leftText);

        rightButton.setTextColor(rightTextColor);
        rightButton.setBackground(rightBackground);
        rightButton.setText(rightText);

        tvTittle.setText(tittle);
        tvTittle.setTextColor(tittleTextColor);
        tvTittle.setTextSize(tittleTextSize);
        tvTittle.setGravity(Gravity.CENTER);

        setBackgroundColor(0xFFF59563);

        // 左按鈕:靠左對齊
        leftParams = new LayoutParams(
                ViewGroup.LayoutParams.WRAP_CONTENT,
                ViewGroup.LayoutParams.WRAP_CONTENT);
        leftParams.addRule(RelativeLayout.ALIGN_PARENT_LEFT, TRUE);
        addView(leftButton, leftParams);

        // 右按鈕:靠右對齊
        rightParams = new LayoutParams(
                ViewGroup.LayoutParams.WRAP_CONTENT,
                ViewGroup.LayoutParams.WRAP_CONTENT);
        rightParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT, TRUE);
        addView(rightButton, rightParams);

        // 標題:居中且撐滿高度
        tittleParams = new LayoutParams(
                ViewGroup.LayoutParams.WRAP_CONTENT,
                ViewGroup.LayoutParams.MATCH_PARENT);
        tittleParams.addRule(RelativeLayout.CENTER_IN_PARENT, TRUE);
        addView(tvTittle, tittleParams);
    }
}

這裡有兩個關鍵點值得記住:

一是 TypedArray。系統會把我們在 attrs.xml 中聲明的屬性自動生成為 R.styleable.TopBar_xxx 形式的常量,命名規則是「控件名 + 下劃線 + 屬性名」,取值時直接用即可。

二是 addRule 與 LayoutParams。由於父容器是 RelativeLayout,子 View 的擺放位置需要通過 LayoutParams 的規則來控制,而不是像 Activity 裡那樣依賴 XML 屬性。

第三步:在布局中引用

用法和系統控件幾乎一致,唯一要注意的是標簽必須寫完整的類名,同時在根布局上聲明自定義屬性的命名空間:

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:custom="https://schemas.android.com/apk/res/com.example.test"
    xmlns:android="https://schemas.android.com/apk/res/android">

    <com.example.test.TopBar
        android:id="@+id/topbar"
        android:layout_width="match_parent"
        android:layout_height="40dp"
        custom:leftBackground="@android:color/holo_purple"
        custom:leftText="LEFT"
        custom:leftTextColor="#FFFFFF"
        custom:rightBackground="@android:color/darker_gray"
        custom:rightText="right"
        custom:rightTextColor="#FFFFFF"
        custom:tittle="OKOKOK"
        custom:tittleTextColor="#FFFFFF"
        custom:tittleTextSize="10sp" />
</RelativeLayout>

寫到這裡,項目已經可以跑起來了。是不是比想象中簡單?

下一篇會繼續進階,講解如何給自定義控件設置監聽事件——通過接口回調機制,把左右兩個 Button 的點擊事件拋給外部 Activity 處理。敬請期待。

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