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

Android 自定義圖片按鈕:重寫 ImageButton 實作按下變色

編輯:關於 Android 程式設計

專案裡若大量使用圖片按鈕,還逐一準備 pressed 狀態的圖會很麻煩。這裡的做法是重寫 ImageButton,在按下時用 ColorMatrix 把圖片降飽和成灰階,放開後還原,一套素材就能應付所有按鈕。

package me.henji.widget;

import android.content.Context;
import android.graphics.ColorMatrix;
import android.graphics.ColorMatrixColorFilter;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnFocusChangeListener;
import android.view.View.OnTouchListener;
import android.widget.ImageButton;

/**
 * 自定義圖片按鈕(ImageButton),按下顏色改變
 * @author Leo
 * @created 2013-3-15
 */
public class CmButton extends ImageButton implements OnTouchListener, OnFocusChangeListener {

  public CmButton(Context context) {
    super(context);
    this.setOnTouchListener(this);
    this.setOnFocusChangeListener(this);
  }

  public CmButton(Context context, AttributeSet attrs) {
    this(context, attrs, android.R.attr.imageButtonStyle);
    this.setOnTouchListener(this);
    this.setOnFocusChangeListener(this);
  }

  public CmButton(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
    setFocusable(true);
    this.setOnTouchListener(this);
    this.setOnFocusChangeListener(this);
  }

  @Override
  public void onFocusChange(View v, boolean hasFocus) {
    // 灰色效果
    ColorMatrix cm = new ColorMatrix();
    cm.setSaturation(0);
    if (hasFocus) {
        ((ImageButton) v).getDrawable().setColorFilter(new ColorMatrixColorFilter(cm));
    } else {
        ((ImageButton) v).getDrawable().clearColorFilter();
    }
  }

  @Override
  public boolean onTouch(View v, MotionEvent event) {
    // 灰色效果
    ColorMatrix cm = new ColorMatrix();
    cm.setSaturation(0);
    if (event.getAction() == MotionEvent.ACTION_DOWN) {
        ((ImageButton) v).getDrawable().setColorFilter(new ColorMatrixColorFilter(cm));
    } else if (event.getAction() == MotionEvent.ACTION_UP) {
        ((ImageButton) v).getDrawable().clearColorFilter();
    }
    return false;
  }
}

版面檔中的使用方式

<me.henji.widget.CmButton
    android:id="@+id/btn_login"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="#00000000"
    android:src="@drawable/button_login"
    android:text="@string/login_login" />

ColorMatrix 的原理

ColorMatrix 是一個 4×5 的矩陣,用來對每個像素的 RGBA 值做線性變換。setSaturation(0) 把飽和度設為 0,等價於套用亮度作為灰階值,視覺效果就是「按下去變灰」。設為 1 則是完全不變。這比準備兩套圖片省下大量素材與 APK 體積。

三個建構子的意義

自定義 View 必須實作三個建構子,因為 Android 會依使用情境選擇呼叫哪一個:

  • 程式碼中 new CmButton(context) 時呼叫第一個
  • 從 XML 版面 inflate 時呼叫第二個
  • 第三個帶 defStyle 的版本供內部 this() 串接,指定預設樣式

漏掉任何一個,在該情境下就會出現 inflate 失敗的例外。

這份實作可以改進的地方

onTouch 回傳值建議改為 super

這裡 onTouch() 回傳 false,表示不消費事件,讓事件繼續往下傳遞給 OnClickListener。這麼做是對的——若回傳 true,點擊事件會被吃掉,setOnClickListener() 就永遠不會觸發。但更穩健的寫法是呼叫 super.onTouchEvent(event) 並回傳其結果,能保留 ImageButton 原有的行為。

ACTION_CANCEL 沒有處理

目前只處理 ACTION_DOWN 與 ACTION_UP。使用者按下按鈕後手指滑出範圍再放開,會觸發 ACTION_CANCEL 而非 UP,此時 colorFilter 不會被清除,按鈕會卡在灰色狀態。應該補上:

else if (event.getAction() == MotionEvent.ACTION_UP
        || event.getAction() == MotionEvent.ACTION_CANCEL) {
    ((ImageButton) v).getDrawable().clearColorFilter();
}

ColorMatrix 應提為物件常量

每次 onTouch 都 new 一個 ColorMatrix 與 ColorMatrixColorFilter,在頻繁觸碰時會造成不必要的 GC。改成類別層級的 static final 成員即可。

Drawable 需實作 ConstantState 才能共用

直接對 getDrawable() 設 filter,會改動到該 Drawable 的所有使用者。若同一個 drawable 資源被多個按鈕共用,一個按下去可能導致其他按鈕一起變色。這在預設情況下不會發生(因為 Drawable 已 implicitly mutate),但顯式呼叫 drawable.mutate() 才是保證正確的做法。

更省事的替代方案:selector

如果你的需求只是「按下換圖」,其實不需要自定義 View。用 ImageButton 搭配 selector 即可:

<selector xmlns:android="https://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/button_login_pressed"
          android:state_pressed="true" />
    <item android:drawable="@drawable/button_login" />
</selector>

自定義 CmButton 的價值在於「不想準備第二張圖」——用程式化方式產生的視覺回饋,這才是 ColorMatrix 方案的真正優勢所在。

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