用安卓实现一个可拖拽的浮动按钮
时间: 2023-05-20 21:01:05 浏览: 99
可以使用 Android 的 WindowManager 和 View 来实现一个可拖拽的浮动按钮。首先,创建一个自定义的 View,然后使用 WindowManager 将该 View 添加到屏幕上。在 View 中实现 onTouchEvent 方法,处理触摸事件,实现拖拽功能。具体实现可以参考以下代码:
```
public class FloatButton extends View {
private WindowManager mWindowManager;
private WindowManager.LayoutParams mLayoutParams;
private int mLastX, mLastY;
public FloatButton(Context context) {
super(context);
mWindowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
mLayoutParams = new WindowManager.LayoutParams();
mLayoutParams.type = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;
mLayoutParams.format = PixelFormat.TRANSLUCENT;
mLayoutParams.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
mLayoutParams.width = 100;
mLayoutParams.height = 100;
mLayoutParams.gravity = Gravity.TOP | Gravity.LEFT;
mLayoutParams.x = 0;
mLayoutParams.y = 0;
mWindowManager.addView(this, mLayoutParams);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
int x = (int) event.getRawX();
int y = (int) event.getRawY();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
mLastX = x;
mLastY = y;
break;
case MotionEvent.ACTION_MOVE:
int deltaX = x - mLastX;
int deltaY = y - mLastY;
mLayoutParams.x += deltaX;
mLayoutParams.y += deltaY;
mWindowManager.updateViewLayout(this, mLayoutParams);
mLastX = x;
mLastY = y;
break;
case MotionEvent.ACTION_UP:
break;
}
return true;
}
}
```
然后在 Activity 中创建 FloatButton 实例即可:
```
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new FloatButton(this);
}
}
```
这样就可以在屏幕上看到一个可拖拽的浮动按钮了。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)