Android编程实现图标拖动效果的方法
本文实例讲述了Android编程实现图标拖动效果的方法。分享给大家供大家参考,具体如下:
最近优化图标拖动时的速率,稍微有一点点效果,直接把代码贴出来,有兴趣一起讨论的朋友可以给我留言。
代码如下:
DragView.java
packagecom.android.dragtest; importandroid.content.Context; importandroid.util.AttributeSet; importandroid.util.Log; importandroid.view.MotionEvent; importandroid.view.View; importandroid.widget.FrameLayout; publicclassDragViewextendsFrameLayout{ privatestaticfinalStringTAG="DragView"; privatefloatX; privatefloatY; privateViewmDragView; publicDragView(Contextcontext){ this(context,null); } publicDragView(Contextcontext,AttributeSetattrs){ this(context,attrs,0); } publicDragView(Contextcontext,AttributeSetattrs,intdefStyle){ super(context,attrs,defStyle); mDragView=newView(context); mDragView.setLayoutParams(newLayoutParams(60,60)); mDragView.setBackgroundDrawable(getResources().getDrawable(R.drawable.gamecenter)); mDragView.setVisibility(View.INVISIBLE); addView(mDragView); } publicbooleanonInterceptTouchEvent(MotionEventev){ finalintaction=ev.getAction(); switch(action){ caseMotionEvent.ACTION_DOWN: Log.d(TAG,"===============>onInterceptTouchEventACTION_DOWN"); break; caseMotionEvent.ACTION_MOVE: Log.d(TAG,"===============>onInterceptTouchEventACTION_MOVE"); break; caseMotionEvent.ACTION_UP: Log.d(TAG,"===============>onInterceptTouchEventACTION_UP"); break; } returntrue; } publicbooleanonTouchEvent(MotionEventev){ finalintaction=ev.getAction(); X=ev.getX(); Y=ev.getY(); switch(action){ caseMotionEvent.ACTION_DOWN: Log.d(TAG,"onTouchEventACTION_DOWN"); mDragView.layout((int)X-30,(int)Y-30,(int)X+30,(int)Y+30); mDragView.setVisibility(View.VISIBLE); break; caseMotionEvent.ACTION_MOVE: Log.d(TAG,"onTouchEventACTION_MOVEx:"+X+"Y:"+Y); mDragView.layout((int)X-30,(int)Y-30,(int)X+30,(int)Y+30); break; caseMotionEvent.ACTION_UP: Log.d(TAG,"onTouchEventACTION_UP"); mDragView.setVisibility(View.INVISIBLE); break; } returntrue; } }
DragTestActivity.java
packagecom.android.dragtest; importandroid.app.Activity; importandroid.os.Bundle; publicclassDragTestActivityextendsActivity{ /**Calledwhentheactivityisfirstcreated.*/ @Override publicvoidonCreate(BundlesavedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.main); } }
main.xml
<?xmlversion="1.0"encoding="utf-8"?> <LinearLayoutxmlns: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程序设计有所帮助。