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

1. 布局文件

<?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. 代码


package com.roiding.sample;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.Button;

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();
break;

case MotionEvent.ACTION_UP:
break;
}

return false;
}

});

}
}

Tags: , , , ,

22 Responses to “实现拖动效果”

  1. 好,呀,这个网站是个人的吗,怎么不能评论呢,像是个做技术的人

  2. 小弟也新建了一个博客,希望大家以后多多交流!

  3. 很厉害。。。。分享了

  4. 第二个不是很懂唉。。

  5. thanks~~~很好用~

  6. so cool
    thx

    转摘ing…

  7. iXhCocQw [url=http://utkxmq.com/]HHCcgA[/url]

  8. sIhPHYt [url=http://ydxuxn.com/]BhPKEDa[/url]

  9. sfKpuV http://qolbne.com/

  10. PRDXasVj http://twoeen.com/

  11. 请问我想实现一个imageView移动 该怎么做呢

  12. iAtbhopQ http://samuelrutledge.com/xanax.html#6231 Xanax

  13. SJAtGzYr http://aidamexico.com/ambien.html#3596 Ambien

  14. bbaodbLc http://unioncountyvoice.com/#4585 Valium

  15. kdtGio http://taksimoldcity.com/xanax.html#1481 Cheap Xanax

  16. Hello! gddddcd interesting gddddcd site!

  17. Very nice site! cheap viagra

  18. Very nice site! [url=http://aieypxo.com/toxvss/2.html]cheap cialis[/url]

  19. Very nice site! cheap cialis http://aieypxo.com/toxvss/4.html

  20. Very nice site!

  21. phHFKm http://ranario.com/xanax.html#5460 Xanax

  22. gXChuDX http://rok-kosmac.com/valium.html#9999 Valium

Leave a Reply

You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>