本文实例为大家分享了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依次执行
            }
        });
    }
}

效果

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