控件的拖动,使用到一个监听事件
setOnTouchListener:
XML代码:
1 <?xml version="1.0" encoding="utf-8"?> 2 <LinearLayout 3 xmlns:android="http://schemas.android.com/apk/res/android" 4 xmlns:app="http://schemas.android.com/apk/res-auto" 5 xmlns:tools="http://schemas.android.com/tools" 6 android:layout_width="match_parent" 7 android:layout_height="match_parent" 8 tools:context=".MainActivity"> 9 10 <ImageView 11 android:id="@+id/textview" 12 android:src="@drawable/ic_launcher_foreground" 13 android:layout_width="wrap_content" 14 android:layout_height="wrap_content" 15 android:background="@color/colorPrimaryDark" 16 android:text="www.baidu.com"/> 17 18 </LinearLayout>
JAVA代码
1 package com.example.a11658.textviewdrag; 2 3 import android.annotation.SuppressLint; 4 import android.os.Bundle; 5 import android.support.v7.app.AppCompatActivity; 6 import android.view.MotionEvent; 7 import android.view.View; 8 import android.widget.ImageView; 9 10 public class MainActivity extends AppCompatActivity { 11 private ImageView tv; 12 private int x; 13 private int y; 14 15 @SuppressLint("ClickableViewAccessibility") 16 @Override 17 protected void onCreate(Bundle savedInstanceState) { 18 super.onCreate(savedInstanceState); 19 setContentView(R.layout.activity_main); 20 21 tv = findViewById(R.id.textview); 22 tv.setOnTouchListener(new View.OnTouchListener() { 23 @Override 24 public boolean onTouch(View v, MotionEvent event) { 25 switch (event.getAction()) { 26 case MotionEvent.ACTION_DOWN: 27 //手指按下 28 //获取第一次接触屏幕 29 x = (int) event.getRawX(); 30 y = (int) event.getRawY(); 31 break; 32 case MotionEvent.ACTION_MOVE: 33 //手指拖动 34 //获取距离差 35 int dx = (int) event.getRawX() - x; 36 int dy = (int) event.getRawY() - y; 37 //更改Imageview在窗体的位置 38 v.layout(v.getLeft() + dx, v.getTop() + dy, 39 v.getRight() + dx, v.getBottom() + dy); 40 //获取移动后的位置 41 x = (int) event.getRawX(); 42 y = (int) event.getRawY(); 43 break; 44 case MotionEvent.ACTION_UP: 45 //手指弹起 46 x = (int) event.getRawX(); 47 y = (int) event.getRawY(); 48 break; 49 } 50 return true; 51 } 52 }); 53 } 54 }
view.layout(left, top, right, bottom)实现拖动。
1.按下图搞懂几个坐标
视图宽度 view.getWidth();
视图高度 view.getHeight()
橘色线:view.getLeft()
蓝色线:view.getRight()
红色线:view.getTop()
粉色线:view.getBottom()
上下左右的偏移都是相对于(0.0)来说