自定義View系列教程01--常用工具介紹

在自定義View的時(shí)候,常常會(huì)用到一些Android系統(tǒng)提供的工具。這些工具封裝了我們經(jīng)常會(huì)用到的方法,比如拖拽View,計(jì)算滑動(dòng)速度,View的滾動(dòng),手勢(shì)處理等等。如果我們自己去實(shí)現(xiàn)這些方法會(huì)比較繁瑣,而且容易出一些bug。所以,作為自定義View系列教程的開(kāi)端,先介紹一下這些常用的工具,以便在后續(xù)的學(xué)習(xí)和工作中使用。

  • Configuration
  • ViewConfiguration
  • GestureDetector
  • VelocityTracker
  • Scroller
  • ViewDragHelper

嗯哼,它們都已經(jīng)躺在這里了,我們就來(lái)挨個(gè)瞅瞅
Configuration

This class describes all device configuration information that can impact the resources the application retrieves.

Configuration用來(lái)描述設(shè)備的配置信息。 比如用戶的配置信息:locale和scaling等等 比如設(shè)備的相關(guān)信息:輸入模式,屏幕大小, 屏幕方向等等 我們經(jīng)常采用如下方式來(lái)獲取需要的相關(guān)信息:

Configuration configuration=getResources().getConfiguration();
//獲取國(guó)家碼
int countryCode=configuration.mcc;
//獲取網(wǎng)絡(luò)碼
int networkCode=configuration.mnc;
//判斷橫豎屏
if(configuration.orientation==Configuration.ORIENTATION_PORTRAIT){
  } else { }

ViewConfiguration 看完Configuration再來(lái)瞅ViewConfiguration。這兩者的名字有些像,差了一個(gè)View;咋一看,還以為它倆是繼承關(guān)系,其實(shí)不然。 官方對(duì)于ViewConfiguration的描述是:

Contains methods to standard constants used in the UI for timeouts, sizes, and distances.

ViewConfiguration提供了一些自定義控件用到的標(biāo)準(zhǔn)常量,比如尺寸大小,滑動(dòng)距離,敏感度等等。 可以利用ViewConfiguration的靜態(tài)方法獲取一個(gè)實(shí)例
ViewConfiguration viewConfiguration=ViewConfiguration.get(context);

在此介紹ViewConfiguration的幾個(gè)對(duì)象方法。

ViewConfiguration viewConfiguration = ViewConfiguration.get(context);
//獲取touchSlop,該值表示系統(tǒng)所能識(shí)別出的被認(rèn)為是滑動(dòng)的最小距離
int touchSlop = viewConfiguration.getScaledTouchSlop();
//獲取Fling速度的最小值和最大值
int minimumVelocity = viewConfiguration.getScaledMinimumFlingVelocity();
int maximumVelocity = viewConfiguration.getScaledMaximumFlingVelocity();
//判斷是否有物理按鍵
boolean isHavePermanentMenuKey=viewConfiguration.hasPermanentMenuKey();

ViewConfiguration還提供了一些非常有用的靜態(tài)方法,比如:

//雙擊間隔時(shí)間.在該時(shí)間內(nèi)是雙擊,否則是單擊
int doubleTapTimeout = ViewConfiguration.getDoubleTapTimeout();
//按住狀態(tài)轉(zhuǎn)變?yōu)殚L(zhǎng)按狀態(tài)需要的時(shí)間
int longPressTimeout = ViewConfiguration.getLongPressTimeout();
//重復(fù)按鍵的時(shí)間
int keyRepeatTimeout = ViewConfiguration.getKeyRepeatTimeout();

GestureDetector 大家都知道,我們可以在onTouchEvent()中自己處理手勢(shì)。其實(shí)Android系統(tǒng)也給我們提供了一個(gè)手勢(shì)處理的工具,這就是GestureDetector手勢(shì)監(jiān)聽(tīng)類(lèi)。利用GestureDetector可以簡(jiǎn)化許多操作,輕松實(shí)現(xiàn)一些常用的功能。 嗯哼,來(lái)吧,一起瞅瞅它是怎么使用的。
第一步:實(shí)現(xiàn)OnGestureListener

private class GestureListenerImpl implements GestureDetector.OnGestureListener {
        //觸摸屏幕時(shí)均會(huì)調(diào)用該方法
        @Override
        public boolean onDown(MotionEvent e) {
            System.out.println("---> 手勢(shì)中的onDown方法");
            return false;
        }

        //手指在屏幕上拖動(dòng)時(shí)會(huì)調(diào)用該方法
        @Override
        public boolean onFling(MotionEvent e1,MotionEvent e2, float velocityX,float velocityY) {
            System.out.println("---> 手勢(shì)中的onFling方法");
            return false;
        }

        //手指長(zhǎng)按屏幕時(shí)均會(huì)調(diào)用該方法
        @Override
        public void onLongPress(MotionEvent e) {
            System.out.println("---> 手勢(shì)中的onLongPress方法");
        }

        //手指在屏幕上滾動(dòng)時(shí)會(huì)調(diào)用該方法
        @Override
        public boolean onScroll(MotionEvent e1,MotionEvent e2, float distanceX,float distanceY) {
            System.out.println("---> 手勢(shì)中的onScroll方法");
            return false;
        }

        //手指在屏幕上按下,且未移動(dòng)和松開(kāi)時(shí)調(diào)用該方法
        @Override
        public void onShowPress(MotionEvent e) {
            System.out.println("---> 手勢(shì)中的onShowPress方法");
        }

        //輕擊屏幕時(shí)調(diào)用該方法
        @Override
        public boolean onSingleTapUp(MotionEvent e) {
            System.out.println("---> 手勢(shì)中的onSingleTapUp方法");
            return false;
        }
    }

第二步:生成GestureDetector對(duì)象

GestureDetector gestureDetector = new GestureDetector(context,new
GestureListenerImpl());

這里的GestureListenerImpl就是GestureListener監(jiān)聽(tīng)器的實(shí)現(xiàn)。

第三步:將Touch事件交給GestureDetector處理 比如將Activity的Touch事件交給GestureDetector處理

@Override  
public boolean onTouchEvent(MotionEvent event) {  
     return mGestureDetector.onTouchEvent(event);  
} 

比如將View的Touch事件交給GestureDetector處理

mButton=(Button) findViewById(R.id.button);  
mButton.setOnTouchListener(new OnTouchListener() {            
   @Override  
   public boolean onTouch(View arg0, MotionEvent event) {  
          return mGestureDetector.onTouchEvent(event);  
      }  
});  

VelocityTracker 這個(gè)玩意兒一看名字,大概就可以猜到意思了。嗯哼,速度追蹤。 VelocityTracker用于跟蹤觸摸屏事件(比如,F(xiàn)linging及其他Gestures手勢(shì)事件等)的速率。 簡(jiǎn)單說(shuō)一下它的常用套路。
第一步:開(kāi)始速度追蹤

private void startVelocityTracker(MotionEvent event) {  
    if (mVelocityTracker == null) {  
         mVelocityTracker = VelocityTracker.obtain();  
     }  
     mVelocityTracker.addMovement(event);  
}  

在這里我們初始化VelocityTracker,并且把要追蹤的MotionEvent注冊(cè)到VelocityTracker的監(jiān)聽(tīng)中。
第二步:獲取追蹤到的速度

private int getScrollVelocity() {  
     // 設(shè)置VelocityTracker單位.1000表示1秒時(shí)間內(nèi)運(yùn)動(dòng)的像素  
     mVelocityTracker.computeCurrentVelocity(1000);  
     // 獲取在1秒內(nèi)X方向所滑動(dòng)像素值  
     int xVelocity = (int) mVelocityTracker.getXVelocity();  
     return Math.abs(xVelocity);  
    } 

同理可以獲取1秒內(nèi)Y方向所滑動(dòng)像素值

第三步:解除速度追蹤

private void stopVelocityTracker() {  
      if (mVelocityTracker != null) {  
          mVelocityTracker.recycle();  
          mVelocityTracker = null;  
      }  
}  

以上就是VelocityTracker的常用使用方式。
Scroller
Scroller挺常見(jiàn)的,用的比較多了。在此只強(qiáng)調(diào)幾個(gè)重要的問(wèn)題,別的就不再贅述了。
第一點(diǎn):scrollTo()和scrollBy()的關(guān)系 先看scrollBy( )的源碼

public void scrollBy(int x, int y) {   
       scrollTo(mScrollX + x, mScrollY + y);   
} 

這就是說(shuō)scrollBy( )調(diào)用了scrollTo( ),最終起作用的是scrollTo( )方法。

第二點(diǎn):scroll的本質(zhì) scrollTo( )和scrollBy( )移動(dòng)的只是View的內(nèi)容,而且View的背景是不移動(dòng)的。
第三點(diǎn):scrollTo( )和scrollBy( )方法的坐標(biāo)說(shuō)明
比如我們對(duì)于一個(gè)TextView調(diào)用scrollTo(0,25) ;那么該TextView中的content(比如顯示的文字:Hello)會(huì)怎么移動(dòng)呢? 向下移動(dòng)25個(gè)單位?不!恰好相反?。∵@是為什么呢? 因?yàn)檎{(diào)用該方法會(huì)導(dǎo)致視圖重繪,即會(huì)調(diào)用

public void invalidate(int l, int t, int r, int b)

此處的l,t,r,b四個(gè)參數(shù)就表示View原來(lái)的坐標(biāo). 在該方法中最終會(huì)調(diào)用:
tmpr.set(l - scrollX, t - scrollY, r - scrollX, b - scrollY); p.invalidateChild(this, tmpr);

其中tmpr是一個(gè)Rect,this是原來(lái)的View;通過(guò)這兩行代碼就把View在一個(gè)Rect中重繪。
請(qǐng)注意第一行代碼:
原來(lái)的l和r均減去了scrollX
原來(lái)的t和b均減去了scrollY
就是說(shuō)scrollX如果是正值,那么重繪后的View的寬度反而減少了;
反之同理 就是說(shuō)scrollY如果是正值,那么重繪后的View的高度反而減少了;
反之同理 所以,TextView調(diào)用scrollTo(0,25)和我們的理解相反
scrollBy(int x,int y)方法與上類(lèi)似,不再多說(shuō)了.

ViewDragHelper 在項(xiàng)目中很多場(chǎng)景需要用戶手指拖動(dòng)其內(nèi)部的某個(gè)View,此時(shí)就需要在onInterceptTouchEvent() 和 onTouchEvent()這兩個(gè)方法中寫(xiě)不少邏輯了,比如處理:拖拽移動(dòng),越界,多手指的按下,加速度檢測(cè)等等。

ViewDragHelper可以極大的幫我們簡(jiǎn)化類(lèi)似的處理,它提供了一系列用于處理用戶拖拽子View的輔助方法和與其相關(guān)的狀態(tài)記錄。比較常見(jiàn)的:QQ側(cè)滑菜單,Navigation Drawer的邊緣滑動(dòng),都可以由它實(shí)現(xiàn)。

ViewDragHelper的使用并不復(fù)雜,在此通過(guò)一個(gè)示例展示其常用的用法。

/**
 * ViewDragHelper使用示例
 * 原創(chuàng)作者:谷哥的小弟
 * 原創(chuàng)地址:http://blog.csdn.net/lfdfhl
 */
public class MyLinearLayout extends LinearLayout {
    private ViewDragHelper mViewDragHelper;

    public MyLinearLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
        initViewDragHelper();
    }

    //初始化ViewDragHelper
    private void initViewDragHelper() {
        mViewDragHelper = ViewDragHelper.create(this, 1.0f, new ViewDragHelper.Callback() {
            @Override
            public boolean tryCaptureView(View child, int pointerId) {
                return true;
            }

    22        //處理水平方向的越界
            @Override
            public int clampViewPositionHorizontal(View child, int left, int dx) {
                int fixedLeft;
                View parent = (View) child.getParent();
                int leftBound = parent.getPaddingLeft();
                int rightBound = parent.getWidth() - child.getWidth() - parent.getPaddingRight();

                if (left < leftBound) {
                    fixedLeft = leftBound;
                } else if (left > rightBound) {
                    fixedLeft = rightBound;
                } else {
                    fixedLeft = left;
                }
                return fixedLeft;
            }

            //處理垂直方向的越界
            @Override
            public int clampViewPositionVertical(View child, int top, int dy) {
                int fixedTop;
                View parent = (View) child.getParent();
                int topBound = getPaddingTop();
                int bottomBound = getHeight() - child.getHeight() - parent.getPaddingBottom();
                if (top < topBound) {
                    fixedTop = topBound;
                } else if (top > bottomBound) {
                    fixedTop = bottomBound;
                } else {
                    fixedTop = top;
                }
                return fixedTop;
    55        }

            //監(jiān)聽(tīng)拖動(dòng)狀態(tài)的改變
    58       @Override
            public void onViewDragStateChanged(int state) {
                super.onViewDragStateChanged(state);
                switch (state) {
                    case ViewDragHelper.STATE_DRAGGING:
                        System.out.println("STATE_DRAGGING");
                        break;
                    case ViewDragHelper.STATE_IDLE:
                        System.out.println("STATE_IDLE");
                        break;
                    case ViewDragHelper.STATE_SETTLING:
                        System.out.println("STATE_SETTLING");
                        break;
                }
     72       }

            //捕獲View
            @Override
            public void onViewCaptured(View capturedChild, int activePointerId) {
                super.onViewCaptured(capturedChild, activePointerId);
                System.out.println("ViewCaptured");
            }

            //釋放View
            @Override
            public void onViewReleased(View releasedChild, float xvel, float yvel) {
                super.onViewReleased(releasedChild, xvel, yvel);
                System.out.println("ViewReleased");
            }
        });
    }

    //將事件攔截交給ViewDragHelper處理
 91   @Override
 92   public boolean onInterceptTouchEvent(MotionEvent ev) {
 93     return mViewDragHelper.shouldInterceptTouchEvent(ev);
 94    }


    //將Touch事件交給ViewDragHelper處理
 98   @Override
 99   public boolean onTouchEvent(MotionEvent ev) {
 100       mViewDragHelper.processTouchEvent(ev);
 101      return true;
 102   }
}

從這個(gè)例子可以看出來(lái)ViewDragHelper是作用在ViewGroup上的(比如LinearLayout)而不是直接作用到某個(gè)被拖拽的子View。其實(shí)這也不難理解,因?yàn)樽覸iew在布局中的位置是其所在的ViewGroup決定的。
在該例中ViewDragHelper做了如下主要操作:
(1) ViewDragHelper接管了ViewGroup的事件攔截,請(qǐng)參見(jiàn)代碼第91-94行
(2) ViewDragHelper接管了ViewGroup的Touch事件,請(qǐng)參見(jiàn)代碼第98-102行
(3) ViewDragHelper處理了拖拽子View時(shí)的邊界越界,請(qǐng)參見(jiàn)代碼第22-55行
(4) ViewDragHelper監(jiān)聽(tīng)拖拽子View時(shí)的狀態(tài)變化,請(qǐng)參見(jiàn)代碼第58-72行
除了這些常見(jiàn)的操作,ViewDragHelper還可以實(shí)現(xiàn):抽屜拉伸,拖拽結(jié)束松手后子View自動(dòng)返回到原位等復(fù)雜操作。
好了,了解完這些非常有用的工具,我們就正式進(jìn)入自定義View。


who is the next one? ——> onMeasure源碼分析

自定義View系列教程01--常用工具介紹
自定義View系列教程02--onMeasure源碼詳盡分析
自定義View系列教程03--onLayout源碼詳盡分析
自定義View系列教程04--Draw源碼分析及其實(shí)踐
自定義View系列教程05–示例分析
自定義View系列教程06–詳解View的Touch事件處理
自定義View系列教程07–詳解ViewGroup分發(fā)Touch事件
自定義View系列教程08–滑動(dòng)沖突的產(chǎn)生及其處理

原文地址:http://blog.csdn.net/lfdfhl/article/details/51324275

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容