猪头小队长 on March 9th, 2009

废话少说,要实现的效果就是在界面上拖动这一个按钮到处跑。
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 [...]

Continue reading about 实现拖动效果