Continuous “Action_DOWN” in Android

前端 未结 2 1263
死守一世寂寞
死守一世寂寞 2021-01-15 13:23
@Override
public boolean onTouchEvent(MotionEvent event) {

if(event.getAction()==MotionEvent.ACTION_DOWN){
Log.d(VIEW_LOG_TAG, \"Touching Down\");
}
    if(event.ge         


        
2条回答
  •  执念已碎
    2021-01-15 13:52

    You cannot do that in the UI-Thread. Code running in UI-Thread must be short to keep UI responsive.

    So you need to create a thread.

    • start the thread when ACTION_DOWN
    • In the thread : write a loop with your log (use a flag to stop the loop)
    • when ACTION_UP : change the flag (this will cause the end of the loop in your thread.

    Sample code :

    AtomicBoolean actionDownFlag = new AtomicBoolean(true);
    
    Thread loggingThread = new Thread(new Runnable(){
         public void run(){
             while(actionDownFlag.get()){
                 Log.d(VIEW_LOG_TAG, "Touching Down");
                 //maybe sleep some times to not polute your logcat
             }
             Log.d(VIEW_LOG_TAG, "Not Touching");
         }
    });
    
    @Override
    public boolean onTouchEvent(MotionEvent event) {
    
        if(event.getAction()==MotionEvent.ACTION_DOWN){
            loggingThread.start();
        }
        if(event.getAction()==MotionEvent.ACTION_UP){
            actionDownFlag.set(false);
        }
    }
    

提交回复
热议问题