##1、Android控件跟随手指移动方法补充
在工作中遇到了这个问题,然后百度了下大致方法多为一种,即通过重写onTouchEvent()记录前后移动的相对坐标,然后根据相对坐标设置控件位置.我们先来看看这个方法,先贴代码
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
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.yxf.removeablewidget.MainActivity">
<Button
android:layout_width="100dp"
android:layout_height="100dp"
android:id="@+id/button_1"
android:background="@android:color/holo_green_dark"
/>
</RelativeLayout>
MainActivity.java
package com.yxf.removeablewidget;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity implements View.OnTouchListener {
Button btn1;//第一个按钮
float lastRawX, lastRawY;//用于记录按钮上一次状态坐标
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn1 = (Button) findViewById(R.id.button_1);
btn1.setOnTouchListener(this);
}
@Override
public boolean onTouch(View v, MotionEvent event) {
switch (v.getId()) {
case R.id.button_1:
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
lastRawX = event.getRawX();
lastRawY = event.getRawY();
break;
case MotionEvent.ACTION_MOVE:
int dx = (int) (event.getRawX() - lastRawX);//相对坐标
int dy = (int) (event.getRawY() - lastRawY);//相对坐标
btn1.layout(btn1.getLeft() + dx, btn1.getTop() + dy, btn1.getRight() + dx, btn1.getBottom() + dy);//设置按钮位置
lastRawX = event.getRawX();
lastRawY = event.getRawY();
break;
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_CANCEL:
break;
}
break;
default:
break;
}
return false;//一般这个保留false,若为true,此控件其他事件会被截断
}
}
运行结果如图
发现其对鼠标的跟随效果并不明显,有一定的位置偏差,那这是什么造成的呢?
原因是实际上相对坐标是float型的,但是
View.layout(int left,int top,int right,int bottom)