最近研究了下图片的拖拽缩放,这里需要自定义touch时间这样在实现这些功能的同时,往往系统自带的onLongClickListener事件冲突。
1 |
下面就在ontouch中对ImageView自定义长按事件进行了重新仅供大家参考 布局xml文件就一个imageview这里我就不贴了:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 |
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.ImageView;
import android.widget.Toast;
public class MainActivity extends Activity {
private ImageView imageview;
private String tag ="MainActivity";
private int mLastMotionX, mLastMotionY;
private int mCounter;
//长按的runnable
private Runnable mLongPressRunnable;
//移动的阈值
private static final int TOUCH_SLOP = 20;
MyHandler myHandler;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageview = (ImageView) findViewById(R.id.imageView1);
myHandler = new MyHandler();
mLongPressRunnable = new Runnable() {
@Override
public void run() {
Log.i(tag, "run-ok--");
Message msg = new Message();
msg.what =2000;
myHandler.sendMessage(msg);
}
};
imageview.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View arg0, MotionEvent event) {
int x = (int) event.getX();
int y = (int) event.getY();
switch(event.getAction()) {
case MotionEvent.ACTION_DOWN:
mCounter=2;
Log.i(tag, "ACTION_DOWN---"+mCounter);
mLastMotionX = x;
mLastMotionY = y;
myHandler.postDelayed(mLongPressRunnable,2000);
break;
case MotionEvent.ACTION_MOVE:
Log.i(tag, "ACTION_MOVE---"+mCounter);
if(Math.abs(mLastMotionX-x) > TOUCH_SLOP
|| Math.abs(mLastMotionY-y) > TOUCH_SLOP) {
//移动超过阈值,则表示移动了
myHandler.removeCallbacks(mLongPressRunnable);
}
break;
case MotionEvent.ACTION_UP:
Log.i(tag, "ACTION_UP---"+mCounter);
myHandler.removeCallbacks(mLongPressRunnable);
break;
}
return true;
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
/**
* 接受消息,处理消息 ,此Handler会与当前主线程一块运行
* */
class MyHandler extends Handler {
public MyHandler() {
}
public MyHandler(Looper L) {
super(L);
}
// 子类必须重写此方法,接受数据
@Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
Log.d("MyHandler", "handleMessage......");
super.handleMessage(msg);
// 此处可以更新UI
if(msg.what ==2000)
{
Toast.makeText(MainActivity.this, "Hello World!", Toast.LENGTH_SHORT).show();
}
}
}
}
|
声明:eoe文章著作权属于作者,受法律保护,转载时请务必以超链接形式附带如下信息
原文作者: sai26746647