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

Android 自定義控件實作:打造一個可配置屬性的 TopBar

編輯:關於 Android 程式設計

每個 App 幾乎都有一條頂部標題列:左邊返回、中間標題、右邊操作。與其每個頁面重寫一次,不如封裝成自定義控件,透過 XML 屬性就能設定文字、顏色、背景。本文以 TopBar 為例走一遍完整流程。

第一步:定義屬性(attrs.xml)

在 res/values/ 下建立 attrs.xml,用 declare-styleable 宣告這組屬性:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="TopBar">
        <attr name="titleText" format="string" />
        <attr name="titleTextSize" format="dimension" />
        <attr name="titleTextColor" format="color" />
        <attr name="leftText" format="string" />
        <attr name="leftBackground" format="reference|color" />
        <attr name="leftTextColor" format="color" />
        <attr name="rightText" format="string" />
        <attr name="rightBackground" format="reference|color" />
        <attr name="rightTextColor" format="color" />
    </declare-styleable>
</resources>

format 決定這個屬性接受什麼型別:string 文字、dimension 尺寸(如 15sp)、color 顏色、reference|color 表示「資源參照或顏色值皆可」——後者讓你能同時寫 @drawable/blue 和 #ffffff。

第二步:實作控件(TopBar.java)

package com.cd.administrator.mytopbar;

import android.annotation.TargetApi;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class TopBar extends RelativeLayout {

    private Button leftButton, rightButton;
    private TextView tvTitle;

    private int leftTextColor, rightTextColor, titleTextColor;
    private Drawable leftBackground, rightBackground;
    private String leftText, rightText, titleText;
    private float titleTextSize;

    private topBarClickListener listener;

    /** 對外暴露的點擊回呼介面 */
    public interface topBarClickListener {
        void leftClick();
        void rightClick();
    }

    public void setOnTopBarClickListener(topBarClickListener listener) {
        this.listener = listener;
    }

    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    public TopBar(Context context, AttributeSet attrs) {
        super(context, attrs);

        // 1. 取出 XML 中宣告的自定義屬性
        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);
        titleTextColor   = ta.getColor(R.styleable.TopBar_titleTextColor, 0);
        titleTextSize    = ta.getDimension(R.styleable.TopBar_titleTextSize, 0);
        titleText        = ta.getString(R.styleable.TopBar_titleText);
        ta.recycle();   // 2. 用完務必回收

        // 3. 建立子 View 並套用屬性
        leftButton  = new Button(context);
        rightButton = new Button(context);
        tvTitle     = new TextView(context);

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

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

        tvTitle.setTextColor(titleTextColor);
        tvTitle.setTextSize(titleTextSize);
        tvTitle.setText(titleText);
        tvTitle.setGravity(Gravity.CENTER);

        setBackgroundColor(0xf59563);

        // 4. 用 LayoutParams 定位:左右靠邊、標題居中
        LayoutParams leftParams = new LayoutParams(
                ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        leftParams.addRule(RelativeLayout.ALIGN_PARENT_LEFT, TRUE);
        addView(leftButton, leftParams);

        LayoutParams rightParams = new LayoutParams(
                ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        rightParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT, TRUE);
        addView(rightButton, rightParams);

        LayoutParams titleParams = new LayoutParams(
                ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT);
        titleParams.addRule(RelativeLayout.CENTER_IN_PARENT, TRUE);
        addView(tvTitle, titleParams);

        // 5. 把內部點擊事件轉發給外部
        leftButton.setOnClickListener(new OnClickListener() {
            @Override public void onClick(View v) {
                if (listener != null) listener.leftClick();
            }
        });
        rightButton.setOnClickListener(new OnClickListener() {
            @Override public void onClick(View v) {
                if (listener != null) listener.rightClick();
            }
        });
    }
}

第三步:在版面中使用

這裡有個關鍵:根元素必須加上 xmlns:custom="https://schemas.android.com/apk/res-auto",否則自定義屬性無法解析。

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

    <com.cd.administrator.mytopbar.TopBar
        android:id="@+id/topBar"
        android:layout_width="match_parent"
        android:layout_height="40dp"
        custom:leftBackground="@drawable/blue"
        custom:leftText="Back"
        custom:leftTextColor="#ffffff"
        custom:rightBackground="@drawable/blue"
        custom:rightText="More"
        custom:rightTextColor="#ffffff"
        custom:titleTextColor="#121212"
        custom:titleTextSize="15sp"
        custom:titleText="自定義標題" />

</RelativeLayout>

第四步:在 Activity 中掛上事件

package com.cd.administrator.mytopbar;

import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
import android.support.v7.app.ActionBarActivity;

public class MainActivity extends ActionBarActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        TopBar topBar = (TopBar) findViewById(R.id.topBar);
        topBar.setOnTopBarClickListener(new TopBar.topBarClickListener() {
            @Override
            public void leftClick() {
                Toast.makeText(MainActivity.this, "cd--left", Toast.LENGTH_SHORT).show();
                finish();
            }

            @Override
            public void rightClick() {
                Toast.makeText(MainActivity.this, "cd--right", Toast.LENGTH_SHORT).show();
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}

自定義控件的四個要點

  1. 用 declare-styleable 宣告屬性,並在 name 屬性標籤上與控件類名保持一致。
  2. 在帶 AttributeSet 的建構子中透過 obtainStyledAttributes 讀取,用完呼叫 recycle()。
  3. 版面根元素加上 xmlns:custom="https://schemas.android.com/apk/res-auto"。
  4. 內部事件透過自訂介面回呼對外,讓使用者自行決定行為,而不是在控件裡寫死業務邏輯。

進階一點的做法,還可以把 setBackgroundColor(0xf59563) 這種寫死的顏色也抽成 custom:background 屬性,並提供 setter 方法以便在程式碼中動態修改標題——這樣控件的可複用性會更高。

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