2

我的應用的觸摸區域使用下列ViewPager來擴展ViewPager

Screenshot

ViewPager的具有相同的寬度顯示。

我添加利潤率的ViewPager在XML中,這樣我可以看到左(藍色)和右(灰色)頁面。 因此,一切正常,但我只能觸摸到綠色區域來移動頁面。

我想擴大觸摸區域到整個屏幕,以便我能夠隨時隨地觸及到移動ViewPager

我嘗試添加TouchDelegate

binding.pagerContainer.post { 
     val rect = Rect() 
     binding.touchArea.getHitRect(rect) 
     binding.pagerContainer.touchDelegate = TouchDelegate(rect, binding.viewPager) 
    } 

並且XML:

<FrameLayout 
     android:id="@+id/pager_container" 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:layout_centerVertical="true" 
     android:clipChildren="false"> 

     <android.support.v4.view.ViewPager 
      android:id="@+id/viewPager" 
      android:layout_width="match_parent" 
      android:layout_height="match_parent" 
      android:layout_gravity="center" 
      android:layout_marginBottom="150dp" 
      android:layout_marginLeft="70dp" 
      android:layout_marginRight="70dp" 
      android:layout_marginTop="150dp" 
      android:clipChildren="false"/> 

     <View 
      android:id="@+id/touchArea" 
      android:layout_width="match_parent" 
      android:layout_height="match_parent" 
      android:alpha="0"> 
     </View> 
    </FrameLayout> 

Rect具有正確的尺寸。 我發佈Runnable以確保視圖已佈置。 我閱讀了TouchDelegate的文檔。

我不知道爲什麼它不起作用。

回答

1

確定。我想我這次有。經過一些研究herehere,我想出了這個答案。我沒有試圖用TouchDelegate擴展ViewPager的區域,而是將觸摸事件從FrameLayout重新路由到ViewPager。 1,做你自己的FrameLayout

public class MyFrameLayout extends FrameLayout { 

    // make sure to include all the necessary constructors here 
    // with calls to super 

    // only need to override 1 method 
    @Override 
    public boolean onTouchEvent(MotionEvent event) { 
     ViewPager pager = null; 
     int count = getChildCount(); 
     for(int i=0; i<count; i++) { 
      if(getChildAt(i) instanceof ViewPager) { 
       pager = (ViewPager)getChildAt(i); 
       break; 
      } 
     } 
     if(pager != null) { 
      return pager.onTouchEvent(event); 
     } 
     return super.onTouchEvent(event); 
    } 
} 

如果您知道ViewPager總是會在FrameLayout裏同一個地方,在onTouchEvent()可以簡化爲

ViewPager pager = (ViewPager)getChildAt(0); 
    return pager.onTouchEvent(event); 

然後你使用自定義的FrameLayout中佈局文件

<your.package.name.MyFrameLayout 
    android:id="@+id/pager_container" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    etc. etc. 

我已經測試過它,這對我來說是這樣。希望對你有效。

+0

天才!愛你:) – Appyx

+0

它肯定有幫助,如果我讀完整個問題:) – Gary99

1

添加此行yourlayout.xml:

android:clickable="true" 
android:focusable="true" 
android:focusableInTouchMode="true" 

試試這個塊:

YOURActivityLayout.setOnTouchListener(new View.OnTouchListener() { 
     @Override 
     public boolean onTouch(View arg0, MotionEvent arg1) { 

      return true;//always return true 
     } 
    }); 

希望這將工作

+0

xml爲touchareaview? – Appyx

+0

驗證您的佈局@Appyx –

+0

我在我的FrameLayout中添加了您的xml。我將onTouchListener添加到了我的FrameLayout。不用找了。 – Appyx