【问题标题】:How to detect that View is NOT touched/clicked?如何检测未触摸/单击视图?
【发布时间】:2014-01-15 09:51:05
【问题描述】:

我想检查该视图(无论是哪个,在我的情况下为 ImageView)是否没有被用户触摸/点击,并且我想经常这样做。我认为我应该使用某种线程,但我不知道如何开始。我想做的操作是隐藏ActionBar,当没有动作时我想隐藏它。
触摸视图时,我使用以下代码:

   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);

但是当屏幕不被触摸时我必须做什么? :-)

【问题讨论】:

  • ImageView 一定时间没有被触摸后,要隐藏ActionBar吗?
  • 为什么不在应用启动时隐藏它,然后当用户触摸屏幕打开它,一段时间(可能是 500 毫秒)后再次隐藏它。我认为你应该找到一种触摸方式。

标签: java android multithreading event-handling android-actionbar


【解决方案1】:

创建一个额外的布尔值(例如:notTouched)为 true,然后在 onTouch 覆盖中将其设置为 false,然后您可以随时检查布尔值是 true 还是 false。

编辑: 如果你想让它在一段时间没有被触摸后隐藏它(如你所说) 你可以在一个单独的线程上的循环中实现一个额外的计数器整数,如下所示:

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
     }
}

【讨论】:

    【解决方案2】:

    为您的活动添加标志:

    boolean wasTouched = true;
    

    添加一个计时器来检查视图是否被触摸:

    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);
    

    在您的 onTouchListener 中,将 wasTouched 设置为 true:

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

    这至少应该让你知道如何去做。

    【讨论】:

    • 最后,我使用了你的解决方案
    猜你喜欢
    • 2016-09-13
    • 1970-01-01
    • 2014-04-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多