2015-12-15 43 views
5

我在我的應用程序中實現了Android導航抽屜。當用戶觸摸導航抽屜的外側時,我可以打開/關閉抽屜。當用戶觸摸/點擊導航抽屜的一側時,您能幫助我們檢測觸摸/點擊事件嗎?我需要在這種情況下執行一些功能。 請檢查附件截圖。 enter image description here 任何幫助將appriciated。如何檢測導航抽屜外的觸摸事件

回答

7

你必須處理在dispatchTouchEvent()方法的觸摸位置收盤後會調用。檢查更多關於觸摸層次結構here

@Override  
public boolean dispatchTouchEvent(MotionEvent event) { 
    if (event.getAction() == MotionEvent.ACTION_UP) { 
     if (mDrawerLayout.isDrawerOpen(mRightDrawerListView)) { 

      View content = findViewById(R.id.right_drawer); 
      int[] contentLocation = new int[2]; 
      content.getLocationOnScreen(contentLocation); 
      Rect rect = new Rect(contentLocation[0], 
       contentLocation[1], 
       contentLocation[0] + content.getWidth(), 
       contentLocation[1] + content.getHeight()); 

      View toolbarView = findViewById(R.id.toolbar); 
      int[] toolbarLocation = new int[2]; 
      toolbarView.getLocationOnScreen(toolbarLocation); 
      Rect toolbarViewRect = new Rect(toolbarLocation[0], 
       toolbarLocation[1], 
       toolbarLocation[0] + toolbarView.getWidth(), 
       toolbarLocation[1] + toolbarView.getHeight()); 


      if (!(rect.contains((int) event.getX(), (int) event.getY())) && !toolbarViewRect.contains((int) event.getX(), (int) event.getY())) { 
       isOutSideClicked = true; 
      } else { 
       isOutSideClicked = false; 
      } 

     } else { 
      return super.dispatchTouchEvent(event); 
     } 
    } else if (event.getAction() == MotionEvent.ACTION_DOWN && isOutSideClicked) { 
     isOutSideClicked = false; 
     return super.dispatchTouchEvent(event); 
    } else if (event.getAction() == MotionEvent.ACTION_MOVE && isOutSideClicked) { 
     return super.dispatchTouchEvent(event); 
    } 

    if (isOutSideClicked) { 
     //make http call/db request 
     Toast.makeText(this, "Hello..", Toast.LENGTH_SHORT).show(); 
    } 
    return super.dispatchTouchEvent(event); 
} 
+0

超酷的解決方案。保存我的時間! – Ganesh

0

您可以使用onDrawerClosed

,當你觸摸屏幕之外onDrawerClosed的導航 抽屜

public void onDrawerClosed(View view) { 
      super.onDrawerClosed(view); 
      //do here 
} 
+1

感謝您的回答。 onDrawerClosed(View view)將在很多場景中調用。這對我不起作用。 – Ganesh

+0

可能會幫助[this](http://stackoverflow.com/questions/22590247/android-navigation-drawer-doesnt-pass-ontouchevent-to-activity) –