实现拖动效果

http://www.roiding.com/index.php/archives/211

废话少说,要实现的效果就是在界面上拖动这一个按钮到处跑。

1. 布局文件

  1. <? xml   version = "1.0"   encoding = "utf-8" ?>  
  2. < LinearLayout   xmlns:android = "http://schemas.android.com/apk/res/android"  
  3. android:orientation = "vertical"   android:layout_width = "fill_parent"  
  4. android:layout_height = "fill_parent" >  
  5. < Button   android:id = "@+id/btn_hello"   android:layout_width = "fill_parent"  
  6. android:layout_height = "wrap_content"   android:text = "@string/hello"   />  
  7. </ LinearLayout >  
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent">
<Button android:id="@+id/btn_hello" android:layout_width="fill_parent"
android:layout_height="wrap_content" android:text="@string/hello" />
</LinearLayout>

2. 代码

  1. package  com.roiding.sample; 
  2.  
  3. import  android.app.Activity; 
  4. import  android.os.Bundle; 
  5. import  android.util.Log; 
  6. import  android.view.MotionEvent; 
  7. import  android.view.View; 
  8. import  android.view.View.OnTouchListener; 
  9. import  android.widget.Button; 
  10.  
  11. public   class  Touch  extends  Activity { 
  12. /** Called when the activity is first created. */  
  13. @Override  
  14. public   void  onCreate(Bundle savedInstanceState) { 
  15. super .onCreate(savedInstanceState); 
  16. setContentView(R.layout.main); 
  17.  
  18. final  Button btn = (Button) findViewById(R.id.btn_hello); 
  19.  
  20. btn.setOnTouchListener( new  OnTouchListener() { 
  21. int [] temp =  new   int [] {  00  }; 
  22.  
  23. public   boolean  onTouch(View v, MotionEvent event) { 
  24.  
  25. int  eventaction = event.getAction(); 
  26. Log.i( "&&&""onTouchEvent:"  + eventaction); 
  27.  
  28. int  x = ( int ) event.getRawX(); 
  29. int  y = ( int ) event.getRawY(); 
  30.  
  31. switch  (eventaction) { 
  32.  
  33. case  MotionEvent.ACTION_DOWN:  // touch down so check if the  
  34. temp[ 0 ] = ( int ) event.getX(); 
  35. temp[ 1 ] = y - v.getTop(); 
  36. break
  37.  
  38. case  MotionEvent.ACTION_MOVE:  // touch drag with the ball  
  39. v.layout(x - temp[ 0 ], y - temp[ 1 ], x + v.getWidth() 
  40. - temp[ 0 ], y - temp[ 1 ] + v.getHeight()); 
  41.  
  42. v.postInvalidate(); 
  43. break
  44.  
  45. case  MotionEvent.ACTION_UP: 
  46. break
  47.  
  48. return   false
  49.  
  50. }); 
  51.  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值