from: http://my.oschina.net/castusz/blog/66338
下面是activity的代码:
- public class DraftTest extends Activity {
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_draft_test);
- DisplayMetrics dm = getResources().getDisplayMetrics();
- final int screenWidth = dm.widthPixels;
- final int screenHeight = dm.heightPixels - 50;
- // 拖动的按钮
- final Button b = (Button) findViewById(R.id.startBtn);
- // 添加触摸事件
- b.setOnTouchListener(new OnTouchListener() {
- int lastX, lastY; // 记录移动的最后的位置
- public boolean onTouch(View v, MotionEvent event) {
- // 获取Action
- int ea = event.getAction();
- Log.i("TAG", "Touch:" + ea);
- switch (ea) {
- case MotionEvent.ACTION_DOWN: // 按下
- lastX = (int) event.getRawX();
- lastY = (int) event.getRawY();
- break;
- /**
- * layout(l,t,r,b) l Left position, relative to parent t Top
- * position, relative to parent r Right position, relative to
- * parent b Bottom position, relative to parent
- * */
- case MotionEvent.ACTION_MOVE: // 移动
- // 移动中动态设置位置
- int dx = (int) event.getRawX() - lastX;
- int dy = (int) event.getRawY() - lastY;
- int left = v.getLeft() + dx;
- int top = v.getTop() + dy;
- int right = v.getRight() + dx;
- int bottom = v.getBottom() + dy;
- if (left < 0) {
- left = 0;
- right = left + v.getWidth();
- }
- if (right > screenWidth) {
- right = screenWidth;
- left = right - v.getWidth();
- }
- if (top < 0) {
- top = 0;
- bottom = top + v.getHeight();
- }
- if (bottom > screenHeight) {
- bottom = screenHeight;
- top = bottom - v.getHeight();
- }
- v.layout(left, top, right, bottom);
- Log.i("aaa", "position:" + left + ", " + top + ", " + right
- + ", " + bottom);
- // 将当前的位置再次设置
- lastX = (int) event.getRawX();
- lastY = (int) event.getRawY();
- break;
- case MotionEvent.ACTION_UP: // 脱离
- break;
- }
- return false;
- }
- });
- }
- @Override
- public boolean onCreateOptionsMenu(Menu menu) {
- // Inflate the menu; this adds items to the action bar if it is present.
- getMenuInflater().inflate(R.menu.activity_draft_test, menu);
- return true;
- }
- }
配置文件activity_draft_test.xml的内容:
- <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:tools="http://schemas.android.com/tools"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:padding="0px"
- tools:context=".DraftTest" >
- <Button
- android:id="@+id/startBtn"
- android:text="tuodongdeanniu"
- android:layout_centerInParent="true"
- android:layout_width="wrap_content" android:layout_height="wrap_content"/>
- </RelativeLayout>