当前位置: 移动技术网 > IT编程>移动开发>Android > Android基础知识之单点触摸

Android基础知识之单点触摸

2019年07月24日  | 移动技术网IT编程  | 我要评论

相对于多点触摸,单点触摸还是很简单的。
新建一个工程,先看看布局文件:

<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;
  }
 });
 }
}

就是这么简单。

原文链接:

源码下载:

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网