相對于多點觸摸,單點觸摸還是很簡單的。
新建一個工程,先看看布局文件:
<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; } }); }}就是這么簡單。
原文鏈接:http://blog.csdn.net/u012702547/article/details/45749107
源碼下載:單點觸摸
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網。
新聞熱點
疑難解答