编写布局资源文件
先准备一张图片放入drawable内
这里主要就是将图片显示出来并设置id(android:scaleType="fitXY"表示图片按原比例设置大小)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
<?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是为了看移动图片时的数据)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 |
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依次执行 } }); } } |
效果