要实现的效果就是在界面上拖动这一个按钮到处跑步骤如下:

PS: getX()方法 是返回当前View的相对x点坐标而 getRawX()方法是返回从屏幕原点计算的x点坐标。

main.xml
<?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>

Touch.java
public class Touch extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

final Button btn = (Button) findViewById(R.id.btn_hello);

btn.setOnTouchListener(new OnTouchListener() {
int[] temp = new int[] { 0, 0 };

public boolean onTouch(View v, MotionEvent event) {

int eventaction = event.getAction();
Log.i("&&&", "onTouchEvent:" + eventaction);

int x = (int) event.getRawX() ;
int y = (int) event.getRawY();


switch (eventaction) {
case MotionEvent.ACTION_DOWN: // touch down so check if the
temp[0] = (int) event.getX() ;
temp[1] = y - v.getTop();
break;

case MotionEvent.ACTION_MOVE: // touch drag with the ball
v.layout(x - temp[0], y - temp[1], x + v.getWidth() - temp[0], y - temp[1] + v.getHeight());
v.postInvalidate(); //redraw
break;
case MotionEvent.ACTION_UP:
break;
}

return false;
}
});
}
}

更多相关文章

  1. android 解析JSON
  2. Picasso源码分析
  3. [置顶] android中屏幕触摸事件
  4. Android(安卓)Sensor框架简述(三)
  5. 反射类查看类下面的所有方法及变量
  6. Android Studio 快捷键
  7. 【Android】【Fragment】Fragment生命周期
  8. android wifi之WifiMonitor
  9. Android执行定时循环任务

随机推荐

  1. Android中padding与layout_margin的区别
  2. 一定是我打开的姿势不对——Android下使
  3. Android短信拦截机制适配的坑(下)--4.4以
  4. 布局
  5. Android学习-SharedPreferences接口的学
  6. Android导入项目时出现红色感叹号
  7. android sdk API level对应关系及下载地
  8. Android(安卓)图像存储在SD卡ContentReso
  9. 关于android的各种disk images
  10. Android中的全局变量