Android

关注公众号 jb51net

关闭
首页 > 软件编程 > Android > Android实现界面随意拖拽

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

作者:烟味少男

这篇文章主要介绍了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;

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对脚本之家的支持。

您可能感兴趣的文章:
阅读全文