手势识别兼容Android 1.x和2.x的代码
2011-01-05 10:14:23 来源:本站整理核心提示:有关调用方法,我们可以自定义一个View,手势识别兼容Android 1.x和2.x的代码(2),取名为TouchExampleView类,这里来处理触控相关的问题public class TouchExampleView extends View { private Drawable mIcon; //我们以一
有关调用方法,我们可以自定义一个View,取名为TouchExampleView类,这里来处理触控相关的问题
public class TouchExampleView extends View {
private Drawable mIcon; //我们以一个图片为参照物,根据手势控制
private float mPosX;
private float mPosY;
private VersionedGestureDetector mDetector;
private float mScaleFactor = 1.f; //原始缩放比例为1.0
public TouchExampleView(Context context) {
this(context, null, 0);
}
public TouchExampleView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public TouchExampleView(Context context, AttributeSet attrs, int defStyle) { //实现我们自定义View的构造
super(context, attrs, defStyle);
mIcon = context.getResources().getDrawable(R.drawable.icon);
mIcon.setBounds(0, 0, mIcon.getIntrinsicWidth(), mIcon.getIntrinsicHeight());
mDetector = VersionedGestureDetector.newInstance(context, new GestureCallback()); //实例化刚才的版本自适应手势控制类
}
@Override
public boolean onTouchEvent(MotionEvent ev) { //重写onTouchEvent方法,使用VersionedGestureDetector类得出的数据。
mDetector.onTouchEvent(ev);
return true;
}
@Override
public void onDraw(Canvas canvas) { //处理自定义View绘制方法
super.onDraw(canvas);
canvas.save();
canvas.translate(mPosX, mPosY); //进行平移操作,根据mPosX和mPosY坐标
canvas.scale(mScaleFactor, mScaleFactor); //进行缩放操作,参数就是刚才定义的float类型的缩放比例
mIcon.draw(canvas); //直接绘制图片变化到画布中
canvas.restore();
}
private class GestureCallback implements VersionedGestureDetector.OnGestureListener {
public void onDrag(float dx, float dy) { //这里Android123提示大家在2.2中这个回调方法将可以支持拖拽的坐标处理
mPosX += dx;
mPosY += dy;
invalidate();
}
public void onScale(float scaleFactor) {
mScaleFactor *= scaleFactor; //缩放控制
mScaleFactor = Math.max(0.1f, Math.min(mScaleFactor, 5.0f)); //限制最小缩放比例为1.0最大为5.0倍数
invalidate();
}
}
}
有关调用我们的自定义的TouchExampleView可以在Activity的onCreate方法中加入以下代码
TouchExampleView view = new TouchExampleView(this); view.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.MATCH_PARENT)); setContentView(view); //替换掉原始的res.layout.main
最后需要给大家说明的是使用本例子,直接使用Android 2.2的SDK创建工程,即API Level为8,发布时在androidmanifest.xml中加入uses-sdk android
更多精彩
赞助商链接
