Android Fundamentals Single Touch

  • 2021-07-24 11:45:49
  • OfStack

Compared with multi-touch, single-touch is very simple.
To build a new project, look at the layout file first:


<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>

For a simple ImageView, 1 we will move this ImageView in Activity:


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;
  //  Models used to manipulate pictures 
  private Matrix oldMatrix = new Matrix();
  private Matrix newMatrix = new Matrix();

  @Override
  public boolean onTouch(View v, MotionEvent event) {
  switch (event.getAction()) { //  Determine the type of operation 
  case MotionEvent.ACTION_DOWN:
   // Remember when you press x,y Coordinates of 
   x = event.getX();
   y = event.getY();
   oldMatrix.set(iv.getImageMatrix());
   break;
  case MotionEvent.ACTION_MOVE:// When moving 
   // Use another 1 Remember the position when pressing the model 
   newMatrix.set(oldMatrix);
   // Moving model 
   newMatrix.setTranslate(event.getX()-x, event.getY()-y);
   break;
  }
  // Put the picture into the moved model 
  iv.setImageMatrix(newMatrix);
  return true;
  }
 });
 }
}

It's as simple as that.

Original link: http://blog.csdn.net/u012702547/article/details/45749107

Source download: Single touch


Related articles: