編寫可複用的自定義按鈕

Android的佈局,要比iOS複雜的多。如果想寫出和iOS類似的交互體驗,付出的代價往往要增加一個數量級。

現在有個正在開發的Android項目,裏面已經有了一些不合理的UI實現方式。比如按鈕是一張圖:

可以看出,應該用編程的方式來實現這個按鈕,比如xml聲明drawable,一個矩形框,四個邊是圓角,要有個很細的邊框,黑色的,背景色使用漸進色效果。登錄使用文字而不是在圖形裏。

這樣的好處很多:

  • 自由的在不同分辨率屏幕下做適配,不必考慮圖形的長寬比;
  • 當文字改動後,不必喊上美工一起加班處理;
  • 文字的國際化。

不過,本文只想對原項目做稍微的改動,而不想推倒重來,我打算另寫一篇文章來說明上述方案的實現。

本文方案的基本思路是,還是用這個圖,但是增加複用性,開發者只需在佈局中使用自定義按鈕,就可以讓已經存在的這種佈局具備點擊後高亮的效果,而不必準備多張圖,寫冗長的xml文件做selector。

實現後的效果,在手指觸碰到該按鈕的時候:

擡起或者移動到按鈕外區域恢復原來的樣子。

這裏佈局還是在xml中,類似這樣:

<com.witmob.CustomerButton
    android:id=”@+id/login”
    android:layout_width=”wrap_content”
    android:layout_height=”wrap_content”
    android:layout_alignParentLeft=”true”
    android:layout_centerVertical=”true”
    android:layout_marginLeft=”26dp”
    android:background=”@drawable/login_login_but”/>

實現的按鈕代碼:

package com.witmob;

import android.content.Context;
import android.graphics.LightingColorFilter;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;

public class CustomerButton extends Button {
   
    public CustomerButton(Context context) {
        super(context);
        this.init();
    }

    public CustomerButton(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        this.init();
    }

    public CustomerButton(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.init();
    }
   
    private void init(){
        this.setOnTouchListener(new OnTouchListener() {
           
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                int action=event.getActionMasked();
                switch (action) {
                case MotionEvent.ACTION_DOWN:
                    getBackground().setColorFilter(new LightingColorFilter(0xFFFFFFFF, 0x000000FF));
                    getBackground().invalidateSelf();
                    break;
                case MotionEvent.ACTION_UP:
                    getBackground().clearColorFilter();
                    getBackground().invalidateSelf();
                    break;
                case MotionEvent.ACTION_MOVE:
                    Rect rect=new Rect();
                    v.getDrawingRect(rect);
                   
                    if(!rect.contains((int)event.getX(),(int)event.getY())){
                        getBackground().clearColorFilter();
                        getBackground().invalidateSelf();
                    }
                    break;
                default:
                    break;
                }
                return false;
            }
        });
    }

}

代碼要點:

  • 需要使用OnTouchListener,處理手指按下,擡起和移動到區域外的處理;
  • 使用ColorFilter,獲取背景色的Drawable對象,增加顏色過濾;
  • 操作Rect,結合手指座標,判斷是否在區域內部;
  • 另外,需要返回false,在OnTouchListener,否則按鈕的OnClickListener將不能生效。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章