Android realizes the effect of floating pictures and dragging them at will
- 2021-09-05 00:49:47
- OfStack
In this paper, we share the specific code of Android to realize the floating drag effect of pictures for your reference. The specific contents are as follows
Implementation steps
1. Customize a floating tool class first
public class MoveImage extends ImageView {
/**
*
* Floating tool class
*
*/
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:
// Avoid slipping out to trigger click events
if ((int) (event.getRawX() - movex) != 0
|| (int) (event.getRawY() - movey) != 0) {
return true;
}
break;
default:
break;
}
return super.onTouchEvent(event);
}
}
2. Reference to xml layout
<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. Implementation of 3. activity
private MoveImage iv_phone_bar;// Sign-in picture
iv_phone_bar = (MoveImage) view.findViewById(R.id.iv_phone_bar);
iv_phone_bar.setOnClickListener(this);
// Sign in
case R.id.iv_phone_bar:
startActivity(new Intent(getActivity(), SignAcitvity.class));// Click to jump to the page
break;