gpt4 book ai didi

android - 扩展 View 并使用 onLongclick

转载 作者:行者123 更新时间:2023-11-29 22:12:46 29 4
gpt4 key购买 nike

我已经扩展了 android View 类,现在我想在 View 中定义一个方法,该方法在单击 longClick 时启动。

我已经使用 public boolean onTouchEvent(MotionEvent event) 对 Action 事件进行了操作。此方法不允许长时间点击以采取行动。

我想在扩展的 View 类中完成它。我知道我可以将 OnLongClickListener 添加到 Activity 中的 View ,但我想知道是否有办法在 View 本身中实现它。

public class ArchitectureView extends GraphView implements OnLongClickListener {

public ArchitectureView(Context context) {
super(context);
this.setOnLongClickListener(this);
}

@Override
public boolean onTouchEvent(MotionEvent event) {
super.onTouchEvent(event);

switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
break;

case MotionEvent.ACTION_UP:
break;

case MotionEvent.ACTION_CANCEL:
break;

}

return true;
}

@Override
public boolean onLongClick(View v) {
Log.e("I've been", "longclicked");
return false;
}

}

GraphView是View的扩展,也覆盖了onTouchEvent并调用了super

最佳答案

在您看来,您可以使用GestureDetectorOnGestureListener 来实现这一点。正式地,您应该为您的 View 类实现 OnGestureListener 并在您的类中定义 GestureDetector

public class YourView extends View implements OnGestureListener {
private GestureDetector detector;

public YourView(Context context) {
super(context);
detector = new GestureDetector(context, this); // "this" refers to the OnGestureListener
}
// Override onTouchEvent to get the Touch event for the gesture detector.
@Override
public boolean onTouchEvent(MotionEvent e) {
boolean handled = detector.onTouchEvent(e);
if (handled) {
return true;
}
return super.onTouchEvent(e);
}
// Some override methods from the OnGestureListener interface
@Override
public void onLongPress(MotionEvent e) {
// Your implementation here
}
// Other override methods, for example, onScroll() etc.
}

关于android - 扩展 View 并使用 onLongclick,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9240679/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com