我有一个从View派生的自定义视图.我希望在单击视图时收到通知,以及点击发生位置的x,y位置.长按也是如此.
看起来这样做,我需要覆盖onTouchEvent().但是,没有办法从OnClickListener相反的方式获取事件的x,y位置吗?
如果不是,有什么好的方法来判断一个动作事件是"真正的"点击还是长按等?将onTouchEvent产生快速连续等许多事件
小智 86
谢谢.这正是我想要的.我现在的代码是:
imageView.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN){
textView.setText("Touch coordinates : " +
String.valueOf(event.getX()) + "x" + String.valueOf(event.getY()));
}
return true;
}
});
Run Code Online (Sandbox Code Playgroud)
这正是马克要求的......
Sur*_*gch 21
其他答案缺少一些细节.这是一个完整的例子.
public class MainActivity extends AppCompatActivity {
// class member variable to save the X,Y coordinates
private float[] lastTouchDownXY = new float[2];
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// add both a touch listener and a click listener
View myView = findViewById(R.id.my_view);
myView.setOnTouchListener(touchListener);
myView.setOnClickListener(clickListener);
}
// the purpose of the touch listener is just to store the touch X,Y coordinates
View.OnTouchListener touchListener = new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
// save the X,Y coordinates
if (event.getActionMasked() == MotionEvent.ACTION_DOWN) {
lastTouchDownXY[0] = event.getX();
lastTouchDownXY[1] = event.getY();
}
// let the touch event pass on to whoever needs it
return false;
}
};
View.OnClickListener clickListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
// retrieve the stored coordinates
float x = lastTouchDownXY[0];
float y = lastTouchDownXY[1];
// use the coordinates for whatever
Log.i("TAG", "onLongClick: x = " + x + ", y = " + y);
}
};
}
Run Code Online (Sandbox Code Playgroud)
OnTouchListenerOnClickListener覆盖 onTouchEvent(MotionEvent ev)
然后你可以这样做:
ev.getXLocation()
Run Code Online (Sandbox Code Playgroud)
或类似的东西。有一个布奇。
| 归档时间: |
|
| 查看次数: |
58577 次 |
| 最近记录: |