簡體   English   中英

沒有顯示MotionEvent.ACTION_UP或MotionEvent.ACTION_CANCEL

[英]not showing MotionEvent.ACTION_UP or MotionEvent.ACTION_CANCEL

我正在編寫一個需要響應觸摸事件的Android應用。 我希望我的應用程序將列表項的顏色更改為自定義顏色。 我編寫了以下代碼,但只有MotionEvent.ACTION_DOWN部分正在運行。 LogCat顯示ACTION_UP沒有調用ACTION_CANCELACTION_UP 能幫我理解為什么我的代碼不能正常工作嗎?

這是我的代碼......

view.setOnTouchListener(new OnTouchListener() {

    public boolean onTouch(View v, MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_UP) {
            view.setBackgroundColor(Color.rgb(1, 1, 1));
            Log.d("onTouch", "MotionEvent.ACTION_UP" );
        }
        if (event.getAction() == MotionEvent.ACTION_DOWN) {
            view.setBackgroundColor(Color.rgb(23, 128, 0));
            Log.d("onTouch", "MotionEvent.ACTION_DOWN" );
        }
        if (event.getAction() == MotionEvent.ACTION_CANCEL) {
            view.setBackgroundColor(Color.rgb(1, 1, 1));
            Log.d("onTouch", "MotionEvent.ACTION_CANCEL" );
        }
        return false;
    }
});

如果從onTouch方法返回falseonTouch其他事件傳遞給偵聽器。 至少在event.getAction() == MotionEvent.ACTION_DOWN情況下,你應該返回true

重構您的代碼,如下所示:

view.setOnTouchListener(new OnTouchListener() {

@Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_UP) {
    view.setBackgroundColor(Color.rgb(1, 1, 1));
    Log.d("onTouch", "MotionEvent.ACTION_UP" );
}
if (event.getAction() == MotionEvent.ACTION_DOWN) {
    view.setBackgroundColor(Color.rgb(23, 128, 0));
    Log.d("onTouch", "MotionEvent.ACTION_DOWN" );
    return true;
}

if (event.getAction() == MotionEvent.ACTION_CANCEL) {
    view.setBackgroundColor(Color.rgb(1, 1, 1));
    Log.d("onTouch", "MotionEvent.ACTION_CANCEL" );
}
return false;
}
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM