简体   繁体   中英

How to detect that View is NOT touched/clicked?

I want to check that view (no matter which, in my case ImageView) is not touched/clicked by user, and I want to do it constantly. I think that i should use some kind of thread but I have no idea how to start. The operation which I want to do is hiding the ActionBar, when there is no action I want to hide it.
When view is touched I use this code:

   Handler handler = new Handler();
    handler.postDelayed(new Runnable() {
        public void run() {

            //if (registerImageViewCallback(slidesPagerAdapter);
            gestureImageView = slidesPagerAdapter.getGestureImageView();
            gestureImageView.setOnTouchListener(new View.OnTouchListener() {
                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    getSupportActionBar().show();
                    return false;
                }
            });
        }
    }, 10);

But what I have to do when screen is not touched? :-)

Create an additional boolean (ex: notTouched) to true, then set it to false inside your onTouch override, then at any point you can just check if the boolean is true or false.

EDIT : If you want it to hide it after it has not been touched for a while (as you said) you could implement an additional counter integer in a loop on a separate thread like this:

while(true) {
     if (notTouched) {
         counter++
         if(counter == 20) {  // Assuming 20 seconds have passed of not touching
             hideMethodHere(); // Execute hiding
         }
         Thread.sleep(1000); // Sleep for a second (so we dont have to count in miliseconds)
     } else {
     counter = 0; // If it was touched, reset the counter
     notTouched == true; // Reset the touch flag as well because otherwise it will be visible forever if you touch it
     }
}

Add a flag to your Activity:

boolean wasTouched = true;

Add a timer that checks if the view was touched:

Timer t = new Timer();
t.scheduleAtFixedRate(new TimerTask() {
   @Override
   public void run() {
      if ( wasTouched == false ) {
         runOnUiThread(new Runnable() {
             public void run(){
               hideYourActionBar();
             }      
          });
      } else {
        wasTouched = false;
      }
   }    
 }, 0, YourDelayInMsHere);

In your onTouchListener, set wasTouched to true:

public boolean onTouch(View v, MotionEvent event) {
   wasTouched = true;
}

This should at least give you an idea of how to do it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM