相对于多点触摸,单点触摸还是很简单的。
新建一个工程,先看看布局文件:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.touchevent.MainActivity" >
<ImageView
android:id="@+id/iv"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="@drawable/jiafeimao"
android:scaleType="matrix" />
</RelativeLayout>
就一个简单的ImageView,一会我们将在Activity中移动这个ImageView:
public class MainActivity extends Activity {
private ImageView iv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
iv = (ImageView) this.findViewById(R.id.iv);
iv.setOnTouchListener(new OnTouchListener() {
private float x;
private float y;
// 用来操作图片的模型
private Matrix oldMatrix = new Matrix();
private Matrix newMatrix = new Matrix();
@Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) { // 判断操作类型
case MotionEvent.ACTION_DOWN:
//按下时记住x,y的坐标
x = event.getX();
y = event.getY();
oldMatrix.set(iv.getImageMatrix());
break;
case MotionEvent.ACTION_MOVE://移动时
//用另一个模型记住按下时的位置
newMatrix.set(oldMatrix);
//移动模型
newMatrix.setTranslate(event.getX()-x, event.getY()-y);
break;
}
//把图片放入移动后的模型中
iv.setImageMatrix(newMatrix);
return true;
}
});
}
}
就是这么简单。