我有一个图像,可以移动并使用捏合手势缩放..所有这些都在onTouch()
内完成。我想限制这个并且只有在用户对图像进行了长按之后才使其可移动(并且可伸缩)。我该怎么做?
答案 0 :(得分:9)
注册LongCLickListener。如果识别出长按,则将标志设置为true。
在OnTouch方法中,仅当标志设置为true时才允许缩放和移动。移动和缩放后,再次将标志设置为false。
这是一些伪代码:
public class MyActivity extends Activity {
private boolean longClick = false;
public boolean onTouch(View v, MotionEvent event) {
if (longClick) {
// do scaling and moving ...
longClick = false;
}
return false;
}
public boolean onLongClick(View v) {
longClick = true;
return false;
}
}
答案 1 :(得分:2)
Roflcoptr的主要思想是正确的,但即使你没有长按也移动你的指针,也会调用onLongClick。为避免这种情况,您可以使用以下代码:
final int NONE=0;
final int DRAG=1;
final int LONG_PRESS=2;
int mode=NONE;
PointF start=new PointF();
public boolean onLongClick(View v) {
if(mode==NONE) mode=LONG_PRESS; //it helps to avoid unwanted onLongClick
return false;
}
public boolean onTouch(View v, MotionEvent event){
switch(event.getAction() & MotionEvent.ACTION_MASK){
case MotionEvent.ACTION_DOWN:
start.set(event.getX(),event.getY()); //point where we started from
break;
case MotionEvent.ACTION_UP:
mode=NONE;
break;
case MotionEvent.ACTION_MOVE:
if(mode==NONE && getDistance(event.getX(),event.getY(),start.x,start.y)>30d) mode=DRAG; //if we really move our pointer, then start the drag mode.
//it helps to avoid unwanted moving
if(mode==DRAG){
//do your stuff
}
if(mode==LONG_PRESS){
//do your stuff
}
break;
}
}
//returns distance between 2 points
private double getDistance(float x1,float y1,float x2,float y2){
float dx=Math.abs(x1-x2);
float dy=Math.abs(y1-y2);
return Math.sqrt(dx*dx+dy*dy);
}
希望它会帮助某人)
答案 2 :(得分:2)
您可以创建两个View.ontouchlistener for one和一个空,并将侦听器设置为仅在onlongpress上查看
LinearLayout.LayoutParams longpressLP = new LinearLayout.LayoutParams(100,100);
LinearLayout longpress = new LinearLayout(this);
longpress.setBackgroundColor(Color.GREEN);
mainlayout.addView(longpress,longpressLP);
final View.OnTouchListener buttontouch=new View.OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
if(event.getAction()==MotionEvent.ACTION_DOWN)
v.setOnTouchListener(buttontouchnone);
else
Toast.makeText(getApplicationContext(), "Touched", Toast.LENGTH_SHORT).show();
return false;
}
};
final View.OnTouchListener buttontouchnone=new View.OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "None Touch", Toast.LENGTH_SHORT).show();
return false;
}
};
longpress.setOnTouchListener(buttontouch);
longpress.setOnLongClickListener(new View.OnLongClickListener() {
public boolean onLongClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "LongClick", Toast.LENGTH_SHORT).show();
v.setOnTouchListener(buttontouch);
return true;
}
});