我是靠谱客的博主 冷艳御姐,最近开发中收集的这篇文章主要介绍android自定义随手指移动Button,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

定义随手指滑动按钮,限制按钮不可滑动超出屏幕。解决与点击事件冲突问题.

public class MoveButton extends AppCompatButton {
private int lastX;
private int lastY;
private int screenWidth, screenHeight;
public MoveButton(Context context) {
super(context);
}
public MoveButton(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
DisplayMetrics displayMetrics = getResources().getDisplayMetrics();
screenWidth = displayMetrics.widthPixels;
screenHeight = displayMetrics.heightPixels;
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
private int firstX;
private int firstY;
@Override
public boolean onTouchEvent(MotionEvent event) {
super.onTouchEvent(event);
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN: // 按下
lastX = (int) event.getRawX();
lastY = (int) event.getRawY();
firstX = (int) event.getRawX();
firstY = (int) event.getRawY();
break;
case MotionEvent.ACTION_MOVE:
int dx = (int) (event.getRawX() - lastX);
int dy = (int) (event.getRawY() - lastY);
int left = getLeft() + dx;
int top = getTop() + dy;
int right = getRight() + dx;
int bottom = getBottom() + dy;
if (left < 0) {
left = 0;
right = left + getWidth();
}
if (right > screenWidth) {
right = screenWidth;
left = right - getWidth();
}
if (top < 0) {
top = 0;
bottom = top + getHeight();
}
if (bottom > screenHeight) {
bottom = screenHeight;
top = bottom - getHeight();
}
layout(left, top, right, bottom);
Log.v("TAG", "left=" + left + "top" + top + "right" + right + "bottom" + bottom);
Log.v("TAG", "screenWidth=" + screenWidth + "screenHeight=" + screenHeight);
lastX = (int) event.getRawX();
lastY = (int) event.getRawY();
return true;
case MotionEvent.ACTION_UP:
int moveX = (int) (event.getRawX() - firstX);
int moveY = (int) (event.getRawY() - firstY);
if (moveX > 4 || moveX < -4 || moveY > 4 || moveY < -4) {
return true;
}
if (listener != null) {
listener.onClick(this);
}
break;
default:
break;
}
return true;
}
/**
* 点击事件监听,解决滑动与点击冲突
*
* @param listener
*/
public void setMoveOnClickListener(OnClickListener listener) {
this.listener = listener;
setOnClickListener(listener);
}
/**
* 屏蔽点击事件
*
* @param l
*/
@Override
public void setOnClickListener(@Nullable OnClickListener l) {
super.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Log.v("MoveButton", "不准用这个方法!!!");
}
});
}

**用法:在布局文件

`moveButton = view.findViewById(R.id.btn_play_video);
moveButton.setMoveOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
}
});

最后

以上就是冷艳御姐为你收集整理的android自定义随手指移动Button的全部内容,希望文章能够帮你解决android自定义随手指移动Button所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(67)

评论列表共有 0 条评论

立即
投稿
返回
顶部