这篇文章主要为大家详细介绍了Android通过单点触摸移动图片,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
本文实例为大家分享了Android通过单点触摸移动图片的具体代码,供大家参考,具体内容如下
编写布局资源文件
先准备一张图片放入drawable内

这里主要就是将图片显示出来并设置id(android:scaleType="fitXY"表示图片按原比例设置大小)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/root"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/bk019"
android:gravity="center"
android:orientation="vertical"
tools:context=".MainActivity">
<ImageView
android:id="@+id/ivImages"
android:layout_width="100dp"
android:layout_height="120dp"
android:scaleType="fitXY"
android:src="@drawable/bk031" />
</LinearLayout>编写主布局文件
(tag是为了看移动图片时的数据)
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
private static final String TAG = "move_images_by_touch";
private ImageView ivImages;
private LinearLayout root;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//利用布局资源文件设置用户界面
setContentView(R.layout.activity_main);
//通过资源标识符获取控件实例
ivImages = findViewById(R.id.ivImages);
root = findViewById(R.id.root);
//设置根布局可以获取焦点
root.setFocusable(true);
//让布局获取焦点
root.requestFocus();
//给根布局注册完触摸监听器,实现触摸监听器接口,编写触摸事件代码
root.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View view, MotionEvent event) {
//根据触摸动作执行不同的操作
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN: //触点按下
Log.d(TAG, "ACTION_DOWN"+event.getX() + "," + event.getY());
break;
case MotionEvent.ACTION_MOVE: //触点移动
Log.d(TAG, "ACTION_MOVE"+event.getX() + "," + event.getY());
break;
case MotionEvent.ACTION_UP: //触点放开
Log.d(TAG, "ACTION_UP"+event.getX() + "," + event.getY());
break;
}
//设置图像控件坐标
ivImages.setX(event.getX()-ivImages.getWidth()/2);
ivImages.setY(event.getY()-ivImages.getHeight()/2);
return true;//设置为真,三个事件:down-->move-->up依次执行
}
});
}
}效果

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程学习网。
织梦狗教程
本文标题为:Android通过单点触摸移动图片
基础教程推荐
猜你喜欢
- android studio按钮监听的5种方法实例详解 2023-01-12
- IOS应用内跳转系统设置相关界面的方法 2022-11-20
- Flutter绘图组件之CustomPaint使用详解 2023-05-12
- Android中的webview监听每次URL变化实例 2023-01-23
- iOS开发教程之XLForm的基本使用方法 2023-05-01
- Flutter手势密码的实现示例(附demo) 2023-04-11
- Android多返回栈技术 2023-04-15
- IOS 播放系统提示音使用总结(AudioToolbox) 2023-03-01
- 解决Android Studio突然不显示logcat日志的问题 2023-02-04
- Android开发使用RecyclerView添加点击事件实例详解 2023-06-15
