Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發實例

Android 自定義控件與自定義屬性完整教學:從 attrs.xml 到自訂 View

編輯:Android 開發實例

自定義控件在 Android 中無所不在。假設某個 UI 是一塊圖片、一個按鈕、一行說明文字的固定組合,而這個組合在 App 裡出現十幾次——難道每次都要重寫三個 tag?既浪費時間、效率又低,還容易寫錯。

更好的做法是封裝成一個自定義 View:既提升效率,在 XML 中使用時也更乾淨美觀。本文分兩部分:屬性定義的語法,以及自定義控件的完整實作。

一、自定義屬性的 format 類型

以下代碼均定義於 values/attrs.xml,屬性名稱可自行命名。

1. reference:參考某一資源 ID

<declare-styleable name = "名稱">
    <attr name = "background" format = "reference" />
    <attr name = "src" format = "reference" />
</declare-styleable>

2. color:顏色值

<attr name = "textColor" format = "color" />

3. boolean:布爾值

<attr name = "focusable" format = "boolean" />

4. dimension:尺寸值

<attr name = "layout_width" format = "dimension" />

5. float:浮點值

<attr name = "fromAlpha" format = "float" />
<attr name = "toAlpha" format = "float" />

6. integer:整型值

<attr name = "frameDuration" format = "integer" />
<attr name = "framesCount" format = "integer" />

7. string:字串

<attr name = "text" format = "string" />

8. fraction:百分比

<attr name = "pivotX" format = "fraction" />
<attr name = "pivotY" format = "fraction" />

9. enum:列舉值

<attr name="orientation">
    <enum name="horizontal" value="0" />
    <enum name="vertical" value="1" />
</attr>

10. flag:位元或運算

<attr name="windowSoftInputMode">
    <flag name = "stateUnspecified" value = "0" />
    <flag name = "stateUnchanged" value = "1" />
    <flag name = "stateHidden" value = "2" />
    <flag name = "stateAlwaysHidden" value = "3" />
</attr>

flag 與 enum 的差別在於:enum 只能選一個,flag 可以用 | 組合成多個,例如 stateHidden|stateAlwaysHidden。因此 flag 的值通常會設計成 1、2、4、8 這類可組合的位元值。

11. 多種類型並存

<attr name = "background" format = "reference|color" />

這樣一來,這個屬性既能接受 @drawable/xxx 也能接受 #FFFFFF。

二、屬性定義與控件實作

目標:做一個「帶陰影的按鈕,按鈕正下方有文字說明」的複合控件(類似九宮格入口)。

步驟一:定義屬性

新建 values/attrs.xml:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="custom_view">
        <attr name="custom_id" format="integer" />
        <attr name="src" format="reference" />          <!-- 按鈕圖 -->
        <attr name="background" format="reference" />   <!-- 陰影背景 -->
        <attr name="text" format="string" />            <!-- 按鈕說明 -->
        <attr name="textColor" format="color" />
        <attr name="textSize" format="dimension" />
    </declare-styleable>
</resources>

步驟二:撰寫 CustomView

public class CustomView extends FrameLayout implements OnClickListener {
    private CustomListener customListener = null;
    private Drawable mSrc = null, mBackground = null;
    private String mText = "";
    private int mTextColor = 0;
    private float mTextSize = 20;
    private int mCustomId = 0;

    private ImageView mBackgroundView = null;
    private ImageButton mButtonView = null;
    private TextView mTextView = null;
    private LayoutParams mParams = null;

    public CustomView(Context context) {
        super(context);
    }

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

        // 讀取 XML 中宣告的自定義屬性
        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.custom_view);
        mSrc = a.getDrawable(R.styleable.custom_view_src);
        mBackground = a.getDrawable(R.styleable.custom_view_background);
        mText = a.getString(R.styleable.custom_view_text);
        mTextColor = a.getColor(R.styleable.custom_view_textColor, Color.WHITE);
        mTextSize = a.getDimension(R.styleable.custom_view_textSize, 20);
        mCustomId = a.getInt(R.styleable.custom_view_custom_id, 0);

        mTextView = new TextView(context);
        mTextView.setTextSize(mTextSize);
        mTextView.setTextColor(mTextColor);
        mTextView.setText(mText);
        mTextView.setGravity(Gravity.CENTER);
        mTextView.setLayoutParams(new LayoutParams(
                LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));

        mButtonView = new ImageButton(context);
        mButtonView.setImageDrawable(mSrc);
        mButtonView.setBackgroundDrawable(null);
        mButtonView.setLayoutParams(new LayoutParams(
                LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
        mButtonView.setOnClickListener(this);

        mBackgroundView = new ImageView(context);
        mBackgroundView.setImageDrawable(mBackground);
        mBackgroundView.setLayoutParams(new LayoutParams(
                LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));

        addView(mBackgroundView);
        addView(mButtonView);
        addView(mTextView);
        this.setOnClickListener(this);

        a.recycle();     // 用完務必回收,否則會浪費記憶體
    }

    @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();
        // 陰影與按鈕靠上置中,說明文字靠下置中
        mParams = (LayoutParams) mButtonView.getLayoutParams();
        if (mParams != null) {
            mParams.gravity = Gravity.CENTER_HORIZONTAL | Gravity.TOP;
            mButtonView.setLayoutParams(mParams);
        }
        mParams = (LayoutParams) mBackgroundView.getLayoutParams();
        if (mParams != null) {
            mParams.gravity = Gravity.CENTER_HORIZONTAL | Gravity.TOP;
            mBackgroundView.setLayoutParams(mParams);
        }
        mParams = (LayoutParams) mTextView.getLayoutParams();
        if (mParams != null) {
            mParams.gravity = Gravity.CENTER_HORIZONTAL | Gravity.BOTTOM;
            mTextView.setLayoutParams(mParams);
        }
    }

    public void setCustomListener(CustomListener l) {
        customListener = l;
    }

    @Override
    public void onClick(View v) {
        if (customListener != null) {
            customListener.onCuscomClick(v, mCustomId);
        }
    }

    public interface CustomListener {
        void onCuscomClick(View v, int custom_id);
    }
}

兩個關鍵點:obtainStyledAttributes() 是讀取自定義屬性的入口,而 a.recycle() 是必須的收尾;CustomListener 介面則讓控件能把點擊事件連同 custom_id 往外拋,呼叫方就能分辨是哪一個實例被點擊。

步驟三:在布局中使用

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:nanlus="https://schemas.android.com/apk/res/com.nanlus.custom"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:orientation="horizontal">

        <com.nanlus.custom.CustomView
            android:id="@+id/custom1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            nanlus:background="@drawable/background"
            nanlus:custom_id="1"
            nanlus:src="@drawable/style_button"
            nanlus:text="按鈕1" />
    </LinearLayout>
</RelativeLayout>

這裡有兩行需要解釋:

· xmlns:nanlus="https://schemas.android.com/apk/res/com.nanlus.custom"——nanlus 是你在 XML 中使用自定義屬性的前綴(名稱可自取),而 com.nanlus.custom 必須是控件所在的套件名稱。這個 URI 的格式是固定的,最後一段就是 package name。
· 標籤本身要用社完整類名 <com.nanlus.custom.CustomView>,因為它是自定義類別而非內建控件。

步驟四:在 Activity 中掛上監聽

public class CustomActivity extends BaseActivity implements CustomListener {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        ((CustomView) this.findViewById(R.id.custom1)).setCustomListener(this);
    }

    @Override
    public void onCuscomClick(View v, int custom_id) {
        switch (custom_id) {
            case 1:
                Toast.makeText(this, "hello !!!", Toast.LENGTH_LONG).show();
                break;
            default:
                break;
        }
    }
}

小結與提醒

自定義控件的價值在於「一次封裝,到處複用」。定義屬性時依資料性質挑選正確的 format,能讓 XML 在編譯期就幫你檢查型別錯誤;而透過自訂 Listener 介面把事件往外拋,則是讓複合控件保持彈性的標準手法。

補充一個實務建議:宣告 <declare-styleable> 時,名稱必須與控件類別的簡單類名一致(本例中 CustomView 對應 custom_view,這是 Android 工具鏈的約定),否則 R.styleable 中不會生成對應的常數。若一個 attrs.xml 裡有多個控件,各自用一組 declare-styleable 即可。

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