目的
在Android里面实现将一个图形可以任意的移动到任何位置
要实现的基本功能
手指点到屏幕的哪,图形的中心就跟到哪
具体实现
1.在xml文件里重写,删掉TextView,写View,设置图形的id,宽和高,还有颜色
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:id="@+id/root">
<View
android:id="@+id/view"
android:layout_width="100dp"
android:layout_height="100dp"
android:background="#9999"
android:tag="1"/>
</RelativeLayout>
2.在MainActivity里重写onCreate方法
View redView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//通过id找到控件
redView=findViewById(R.id.view);
}
3.重写onTouchEvent方法
@Override
public boolean onTouchEvent(MotionEvent event) {
//获取事件对应的类型
int action=event.getAction();
//获取屏幕的大小
Point p=new Point();
//通过getSize方法得到屏幕的大小
getWindowManager().getDefaultDisplay().getSize(p);
RelativeLayout rl=findViewById(R.id.root);
float padding = p.y - rl.getHeight();
if (action==MotionEvent.ACTION_DOWN){
//按下
//获取触摸点的坐标
float x=event.getX();
float y=event.getY()-padding;
//改变控件的位置
redView.setX(x-(int)(redView.getWidth()*0.5));
redView.setY(y-(int)(redView.getHeight()*0.5));
}else if (action==MotionEvent.ACTION_MOVE){
//滑动
//按下
//获取触摸点的坐标
float x=event.getX();
float y=event.getY()-padding;
//改变控件的位置
redView.setX(x-(int)(redView.getWidth()*0.5));
redView.setY(y-(int)(redView.getHeight()*0.5));
}else if (action==MotionEvent.ACTION_UP){
//离开屏幕
}else{
}
return true;
}
还可以通过重写onTouch方法实现颜色的变化
@Override
public boolean onTouchEvent(MotionEvent event) {
//改变控件的颜色
//redView.setBackgroundColor(Color.BLACK);
RelativeLayout rl=findViewById(R.id.root);
//通过tag值查找父容器下面的子控件
View iv=rl.findViewWithTag("1");
iv.setBackgroundColor(Color.BLACK);
return true;
}
小结
虽然是一个小Demo,但是从中我能学到很多东西,比如说用getSize方法获取屏幕的大小,运行之后发现问题,因为没有减去状态栏的高度所以导致位置不正确,知道了按下时ACTION_DOWN,滑动是ACTION_MOVE等等,小小的知识点往往是一项大工程的某部分不可或缺的零件。