Android之图片浮动随意拖拽的效果实现

时间:2022-07-02 14:50:29

-----------------转载请注明出处:http://blog.csdn.net/android_cll

一:一般都是先上效果图,这个是可以在这个界面随意拖动的、

Android之图片浮动随意拖拽的效果实现


Android之图片浮动随意拖拽的效果实现

二:实现步骤、

1.先自定义一个浮动工具类、

public class MoveImage extends ImageView {

/**
*
* 浮动工具类
*
*/
private int lastX = 0;
private int lastY = 0;

private int dx;
private int dy;
private float movex = 0;
private float movey = 0;

private int screenWidth;
private int screenHeight;

public MoveImage(Context context, AttributeSet attrs) {
super(context, attrs);
screenWidth = ScreenUtils.getWidth(context);
screenHeight = ScreenUtils.getHeight(context);
}

@Override
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
lastX = (int) event.getRawX();
lastY = (int) event.getRawY();
movex = lastX;
movey = lastY;
break;
case MotionEvent.ACTION_MOVE:
dx = (int) event.getRawX() - lastX;
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);
lastX = (int) event.getRawX();
lastY = (int) event.getRawY();
break;
case MotionEvent.ACTION_UP:
//避免滑出触发点击事件
if ((int) (event.getRawX() - movex) != 0
|| (int) (event.getRawY() - movey) != 0) {
return true;
}
break;
default:
break;
}
return super.onTouchEvent(event);
}

}

2.xml布局的引用、

<com.zjtd.bzcommunity.text.MoveImage
android:id="@+id/iv_phone_bar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_marginBottom="70dp"
android:src="@drawable/my_qiandao_icon" />


3.activity的实现、

private MoveImage iv_phone_bar;//签到图片
iv_phone_bar = (MoveImage) view.findViewById(R.id.iv_phone_bar);
iv_phone_bar.setOnClickListener(this);
// 签到
case R.id.iv_phone_bar:
startActivity(new Intent(getActivity(), SignAcitvity.class));//点击跳转页面
break;

简单除暴超炫,你值得拥有。。。。看了帮我顶一下哦!

-------------------最后附上源码:http://download.csdn.net/download/android_cll/9803439