这篇文章主要介绍了Android实现悬浮可拖拽的按钮,具有一定借鉴价值,感兴趣的朋友可以参考下,希望大家阅读完这篇文章之后大有收获、下面让小编带着大家一起了解一下。
<强> 1,简介强>
最近,因为项目需要,需要制作一个界面上可拖拽的按钮,网上也有多实例,看了下大部分都是示例不全或讲解不清晰,效果图也不明显,借此自己记录一番自己的实现方案,以备不时之需,同时也为广大学者可以直接通过拷贝方式完成项目所需。
<强> 2,效果图强>
在开始代码之前,首先看看效果图,如下:
public class DraggingButton extends android.support.v7.widget.AppCompatButton { , private 才能int lastX =, 0; private 才能int lastY =, 0; private 才能int beginX =, 0; private 才能int beginY =, 0; , private 才能int screenWidth =, 720; private 才能int screenHeight =, 1280; , , public 才能DraggingButton (Context 上下文),{ ,,,这(上下文,null); ,,} , public 才能;DraggingButton (Context 上下文,@Nullable AttributeSet attrs), { ,,,(上下文,attrs,, 0); ,,} , public 才能;DraggingButton (Context 上下文,@Nullable AttributeSet attrs,, int defStyleAttr), { ,,,超级(上下文,attrs, defStyleAttr); , ,,,initData(上下文); ,,} , private 才能;void  initData (Context 上下文){ ,,,WindowManager wm =, (WindowManager), context.getSystemService (Context.WINDOW_SERVICE); ,,,DisplayMetrics dm =, new DisplayMetrics (); ,,,wm.getDefaultDisplay () .getMetrics (dm); ,,,screenWidth =, dm.widthPixels; ,,,screenHeight =, dm.heightPixels; ,,} , @Override才能 public 才能;boolean  onTouchEvent (MotionEvent 事件) {才能 , ,,,switch (event.getAction ()) ,,,{ ,,,,,case MotionEvent.ACTION_DOWN: ,,,,,,,lastX =, (int), event.getRawX();,,,//,触摸点与屏幕左边的距离 ,,,,,,,lastY =, (int), event.getRawY();,,,//,触摸点与屏幕上边的距离 ,,,,,,,beginX =, lastX; ,,,,,,,beginY =, lastY; ,,,,,,,休息; ,,,,,case MotionEvent.ACTION_MOVE: , ,,,,,,,int dx =(int) event.getRawX(),安康;lastX;,,,,//, x轴拖动的绝对距离 ,,,,,,,int dy =(int) event.getRawY(),安康;lastY;,,,,//, y轴拖动的绝对距离 , ,,,,,,,//,getLeft():,子视图的左边界到父视图的左边界的距离,,getRight():子视图的右边界到父视图的左边界的距离 ,,,,,,,//,如下几个数据表示视图应该在布局中的位置 ,,,,,,,int left =, getLeft (), +, dx; ,,,,,,,int top =, getTop (), +, dy; ,,,,,,,int right =, getRight (), +, dx; ,,,,,,,int bottom =, getBottom (), +, dy; ,,,,,,,如果(left & lt;, 0) { ,,,,,,,,,left =, 0; ,,,,,,,,,right =, left +, getWidth (); ,,,,,,,} ,,,,,,,如果(right 祝辞,screenWidth) { ,,,,,,,,,right =, screenWidth; ,,,,,,,,,left =, right 作用;getWidth (); ,,,,,,,} ,,,,,,,如果(top & lt;, 0) { ,,,,,,,,,top =, 0; ,,,,,,,,,bottom =, top +,获得(); ,,,,,,,} ,,,,,,,如果(bottom> screenHeight) { ,,,,,,,,,bottom =, screenHeight; null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null