android 实现拖动图片的功能

6,505 views

因为想写一个Mapview 拖拽图片并标记经纬度的功能,所以以下的代码可能有参考作用,所以记录下来。

思路:ImageView 实现OnTouchListener事件响应,向下点击时( MotionEvent.ACTION_DOWN)记录屏幕的坐标,当移动时(MotionEvent.ACTION_MOVE)移动到该点的坐标位置。

1.DragImageActivity.java

package com.drag.main;

import android.app.Activity;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.ImageView;

public class DragImageActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ImageView img = (ImageView) findViewById(R.id.img_view);
img.setOnTouchListener(dragTouch);
}
//拖动图标的时间响应
OnTouchListener dragTouch=new OnTouchListener() {
private float x, y;
private int mx, my;
@Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
//记录按下时的位置
x = event.getX();
y = event.getY();
case MotionEvent.ACTION_MOVE:
//拖动时
mx = (int) (event.getRawX() - x);
my = (int) (event.getRawY() - 50 - y);
v.layout(mx, my, mx + v.getWidth(), my + v.getHeight());
break;
}
return true;
}
};
}

2.main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<ImageView android:id="@+id/img_view"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:src="@drawable/ic_launcher"
android:contentDescription="@string/hello"/>
</LinearLayout>

Leave a Reply

Your email address will not be published. Required fields are marked *

*

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