彈性滑動(二)--使用ViewHelper

使用nineoldandroids開源動畫庫.

  1. 通過getRawX和getRawY獲得手指當前座標A(x,y).
  2. 與上一次移動後的控件座標B(mLastX,mLastY)相減得到偏移量座標C(deltaX,deltaY),B初始化爲(0,0).
  3. 使用ViewHelper類將控件進行動畫偏移,偏移C.
  4. 將手指座標即當前座標A賦值給B.
  5. 循環上述操作.

例子:將button隨手指移動而移動

自定義button

package com.example.test;

import com.nineoldandroids.view.ViewHelper;

import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.widget.Button;

public class MyView extends Button {
    int mLastX = 0; // 上次移動後最終的橫座標
    int mLastY = 0; // 上次移動後最重的縱座標

    public MyView(Context context, AttributeSet attrs) {
        super(context, attrs);
        // TODO Auto-generated constructor stub
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        // 當前手指座標
        int x = (int) event.getRawX();
        int y = (int) event.getRawY();

        switch (event.getAction()) {
        case MotionEvent.ACTION_DOWN:

            break;
        case MotionEvent.ACTION_MOVE:

            int deltaX = x - mLastX; // x方向移動量
            int deltaY = y - mLastY; // y方向移動量

            int translationX = (int) (ViewHelper.getTranslationX(this) + deltaX); // x方向平移deltaX
            int translationY = (int) (ViewHelper.getTranslationY(this) + deltaY); // y方向平移deltaY
            ViewHelper.setTranslationX(this, translationX);
            ViewHelper.setTranslationY(this, translationY);

            break;
        case MotionEvent.ACTION_UP:

            break;
        }
        // 更新位置
        mLastX = x;
        mLastY = y;
        return true;
    }

}

佈局

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <com.example.test.MyView
        android:id="@+id/btn"
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:text="qqq" />

</LinearLayout>

Demo下載地址:

http://pan.baidu.com/s/1jIdfhPk

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章