[英]Events for Long click down and long click up in Android
我想要兩個單獨的事件長按單擊向下和長按。 我怎樣才能在Android中執行此操作?
我試過的內容如下
public class FfwRewButton extends ImageButton {
public interface ButtonListener {
void OnLongClickDown(View v);
void OnLongClickUp(View v);
}
private ButtonListener mListener;
private boolean mLongClicked = false;
public FfwRewButton(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
setFocusable(true);
setLongClickable(true);
}
public FfwRewButton(Context context) {
this(context, null);
}
public FfwRewButton(Context context, AttributeSet attrs) {
this(context, attrs, android.R.attr.imageButtonStyle);
}
@Override
public boolean onKeyLongPress(int keyCode, KeyEvent event) {
Log.d("my listener", "long press");
mLongClicked = true;
mListener.OnLongClickDown(this);
return super.onKeyLongPress(keyCode, event);
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
Log.d("my listener", "key down");
mLongClicked = false;
if (true) {
super.onKeyDown(keyCode, event);
return true;
}
return super.onKeyDown(keyCode, event);
}
@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
Log.d("my listener", "key up");
if (mLongClicked)
mListener.OnLongClickUp(this);
return super.onKeyUp(keyCode, event);
}
public void setFfwRewButtonListener(ButtonListener listener) {
mListener = listener;
}
}
在一項活動中,我這樣稱呼它
private FfwRewButton.ButtonListener mListener = new FfwRewButton.ButtonListener() {
@Override
public void OnLongClickUp(View v) {
Log.d(TAG, "longClickup");
}
@Override
public void OnLongClickDown(View v) {
Log.d(TAG, "longClickdown");
}
};
但仍然沒有得到logcat中的任何日志消息任何人都可以幫助我; 哪里錯了?
onKeyXXX()
方法用於鍵盤或硬鍵的鍵事件,如菜單鍵,搜索鍵等。
如果你想檢測觸摸事件,這就是所謂MotionEvent
在Android中,你必須覆蓋onTouchEvent(MotionEvent e)
方法,並使用GestureDetector
類識別長按。
private GestureDetector mGestureDetector;
public FfwRewButton(...) {
//....
mGestureDetector = new GestureDetector(context,
new GestureDetector.SimpleOnGestureListener() {
public boolean onDown(MotionEvent e) {
mLongClicked = false;
return true;
}
public void onLongPress(MotionEvent e) {
mLongClicked = true;
// long press down detected
}
});
}
public boolean onTouchEvent(MotionEvent e) {
mGestureDetector.onTouchEvent(e);
if (mLongClicked && e.getAction() == ACTION_UP) {
// long press up detected
}
}
}
這樣的事情會讓你走上正確的道路,
我沒有編譯,所以你可能需要糾正一些語法,但你的目標可以用這個概念來實現
OnTouchListener mTouchListener = new OnTouchListener(){
private totalTimeDown = -1;
private downTime = -1;
public boolean onTouch(View v, MotionEvent me){
if(me.getAction() == MotionEvent.ACTION_DOWN){
downTime = System.getCurrentTimeInMillis();
return true;
}
if(me.getAction() == MotionEvent.ACTION_UP){
totalTimeDown = System.getCurrentTimeInMillis() - downTime;
if(totalTimeDown > 500){
//Finger was down long enough for "longClick"
return true;
}
}
return false;
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.