Android编程实现图标拖动效果的方法
程序员文章站
2023-12-09 14:05:15
本文实例讲述了android编程实现图标拖动效果的方法。分享给大家供大家参考,具体如下:
最近优化图标拖动时的速率,稍微有一点点效果,直接把代码贴出来,有兴趣一起讨论的朋...
本文实例讲述了android编程实现图标拖动效果的方法。分享给大家供大家参考,具体如下:
最近优化图标拖动时的速率,稍微有一点点效果,直接把代码贴出来,有兴趣一起讨论的朋友可以给我留言。
代码如下:
dragview.java
package com.android.dragtest; import android.content.context; import android.util.attributeset; import android.util.log; import android.view.motionevent; import android.view.view; import android.widget.framelayout; public class dragview extends framelayout { private static final string tag = "dragview"; private float x; private float y; private view mdragview; public dragview(context context) { this(context, null); } public dragview(context context, attributeset attrs) { this(context, attrs, 0); } public dragview(context context, attributeset attrs, int defstyle) { super(context, attrs, defstyle); mdragview = new view(context); mdragview.setlayoutparams(new layoutparams(60, 60)); mdragview.setbackgrounddrawable(getresources().getdrawable(r.drawable.gamecenter)); mdragview.setvisibility(view.invisible); addview(mdragview); } public boolean onintercepttouchevent(motionevent ev) { final int action = ev.getaction(); switch (action) { case motionevent.action_down: log.d(tag, "===============>onintercepttouchevent action_down"); break; case motionevent.action_move: log.d(tag, "===============>onintercepttouchevent action_move"); break; case motionevent.action_up: log.d(tag, "===============>onintercepttouchevent action_up"); break; } return true; } public boolean ontouchevent(motionevent ev) { final int action = ev.getaction(); x = ev.getx(); y = ev.gety(); switch (action) { case motionevent.action_down: log.d(tag, "ontouchevent action_down"); mdragview.layout((int)x - 30, (int)y - 30, (int)x + 30, (int)y + 30); mdragview.setvisibility(view.visible); break; case motionevent.action_move: log.d(tag, "ontouchevent action_move x:" + x + " y:" + y); mdragview.layout((int)x - 30, (int)y - 30, (int)x + 30, (int)y + 30); break; case motionevent.action_up: log.d(tag, "ontouchevent action_up"); mdragview.setvisibility(view.invisible); break; } return true; } }
dragtestactivity.java
package com.android.dragtest; import android.app.activity; import android.os.bundle; public class dragtestactivity extends activity { /** called when the activity is first created. */ @override public void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.main); } }
main.xml
<?xml version="1.0" encoding="utf-8"?> <linearlayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <com.android.dragtest.dragview android:layout_width="match_parent" android:layout_height="match_parent"> </com.android.dragtest.dragview> </linearlayout>
希望本文所述对大家android程序设计有所帮助。