2016-11-13 31 views
0

我有一個NestedScrollView之上的RelativeLayout。我想阻止任何對RelativeLayout的點擊傳播,但允許所有的滾動事件。 應適用於RelativeLayout的與「controllers_container」 ID如何防止點擊事件和繞過視圖上的滾動事件?

<android.support.design.widget.CoordinatorLayout 
    xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:app="http://schemas.android.com/apk/res-auto" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent"> 

    <android.support.v4.widget.NestedScrollView 
     android:id="@+id/scrollView" 
     android:layout_width="match_parent" 
     android:layout_height="match_parent"> 

     ... content ... 

    </android.support.v4.widget.NestedScrollView> 

    <RelativeLayout 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     app:layout_anchor="@id/scrollView" 
     app:layout_anchorGravity="bottom|left|end"> 

     <RelativeLayout 
      android:id="@+id/controllers_container" 
      android:layout_width="match_parent" 
      android:layout_height="wrap_content" 
      android:padding="@dimen/activity_vertical_margin" 
      android:layout_alignParentLeft="true" 
      android:layout_alignParentStart="true" 
      android:layout_above="@+id/bottom_bar"> 

      ... content ... 

     </RelativeLayout> 

     ... content ... 

    </RelativeLayout> 
</android.support.design.widget.CoordinatorLayout> 

添加android:clickable="true"防止任何觸摸事件,包括滾動。我試圖設置一個觸摸偵聽器的scrollView,但不能按需要管理它。有任何想法嗎?

+0

嘗試將觸摸事件切換到父級佈局,並使用onTouchIntercept進行處理 – Vicky

回答

0

我想出了一個辦法。 基本上,我在NestedScrollView中處理觸摸事件(稱爲targetView)。我創建處理該觸摸事件時,一個這樣的公共方法:

public boolean handleTouch(View v, MotionEvent event) { 
     if (event.getAction() == MotionEvent.ACTION_UP) { 

      ... Handle the action up event ... 

     } 
     return true; 
    } 

然後,我設置在父該視圖的觸摸監聽器(在這種情況下,包含所有這些元素的片段)。如果行動發生在控制器容器之外,我打電話給handleTouch方法。

targetView.setOnTouchListener(new View.OnTouchListener() { 
      @Override 
      public boolean onTouch(View v, MotionEvent event) { 
       if (event.getAction() == MotionEvent.ACTION_UP) { 
        int scrollY = nestedScrollView.getScrollY(); 
        int top = controllersContainer.getTop(); 
        float y = event.getY() + targetView.getTop(); 
        if (y - scrollY > top) { 
         return false; 
        } 
       } 
       return targetView.handleTouch(v, event); 
      } 
     });