1. 程式人生 > >WebView自適應並巢狀在ScrollView 解決左右滑動衝突

WebView自適應並巢狀在ScrollView 解決左右滑動衝突

ANDROID中SCROLLVIEW巢狀WEBVIEW

Android中WebView用來載入html頁面,自帶滑動效果。ScrollView同樣也是自帶滑動效果,在專案中如果需要WebView和一些其他view比如TextView一起滑動的話就必須外面巢狀一層ScrollView,這時問題就來了,巢狀之後ScrollView的滑動和WebView的滑動就會有衝突,WebView的滑動不流暢。下面就是解決方案:

自定義一個ScrollView

public class MyScrollView extends ScrollView {
    private GestureDetector
mGestureDetector; View.OnTouchListener mGestureListener; public MyScrollView(Context context, AttributeSet attrs) { super(context, attrs); mGestureDetector = new GestureDetector(context, new YScrollDetector()); setFadingEdgeLength(0); } @Override public boolean
onInterceptTouchEvent(MotionEvent ev) { return super.onInterceptTouchEvent(ev) && mGestureDetector.onTouchEvent(ev); } // Return false if we're scrolling in the x direction class YScrollDetector extends SimpleOnGestureListener { @Override public boolean onScroll
(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) { if (Math.abs(distanceY) > Math.abs(distanceX)) { return true; } return false; } } }

上面程式碼中onInterceptTouchEvent方法是關鍵,重寫這個方法使如果ScrollView有touch事件時不被攔截,這樣只要ScrollView有touch事件優先處理,這樣就保證了滑動的流暢。

之後就在自己的xml佈局檔案裡用MyScrollView代替ScrollView來佈局就ok了。如

<com.boohee.widgets.MyScrollView
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="@drawable/main_bg"
    android:layout_marginTop="@dimen/default_shadow_margin" >

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical" >

        <RelativeLayout
            android:layout_width="fill_parent"
            android:layout_height="180dp" >

            <android.support.v4.view.ViewPager
                android:id="@+id/vp_top_show"
                android:layout_width="fill_parent"
                android:layout_height="fill_parent" />

            <LinearLayout
                android:id="@+id/dot_layout"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_alignParentBottom="true"
                android:gravity="center_horizontal"
                android:orientation="horizontal"
                android:padding="10dp" >
            </LinearLayout>
        </RelativeLayout>

        <WebView
            android:id="@+id/wv_show"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:layerType="software"
            android:scrollbars="none" />
    </LinearLayout>
</com.boohee.widgets.MyScrollView>
轉自http://stormzhang.com/android/2013/07/27/android-scrollview-nested-webview/