SwipeRefreshLayout在ViewPager中干扰了ScrollView。

7
我有一个围绕着ViewPager的SwipeRefreshLayout。ViewPager加载的片段包含ScrollView。当我向下滚动时,它运作良好,但是当我向上滚动时,SwipeRefreshLayout会在ScrollView先滚动到顶部之前就激活。我该如何确保ScrollView具有优先级?
当SwipeRefreshLayout位于ScrollView外部的单独片段中时,它可以正常工作,但我需要它位于ViewPager周围的活动中。
以下是相关的布局:
活动:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:background="#EEEEEE"
    android:fitsSystemWindows="true">

    <include layout="@layout/toolbar" />

    <io.karim.MaterialTabs
        android:id="@+id/tabs"
        android:layout_width="match_parent"
        android:layout_height="48dp"
        android:background="@color/primary"
        app:mtIndicatorColor="@color/icons"
        app:mtIndicatorHeight="2dp"
        app:mtSameWeightTabs="true"
        app:mtPaddingMiddle="false"
        app:mtTextColorSelected="@color/icons"
        android:textColor="@color/icons"
        android:elevation="4dp"
        tools:ignore="UnusedAttribute" />

    <android.support.v4.widget.SwipeRefreshLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/swipeRefresh"
        android:layout_height="wrap_content"
        android:layout_width="match_parent">

        <android.support.v4.view.ViewPager
            android:id="@+id/pager"
            android:layout_width="match_parent"
            android:layout_height="0dp" />

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

</LinearLayout>

这是由ViewPager加载的碎片(共有5个选项卡,每个选项卡都有一个):

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="me.sargunvohra.android.purduediningcourts.presenter.MenuFragment">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            android:paddingLeft="@dimen/activity_horizontal_margin"
            android:paddingRight="@dimen/activity_horizontal_margin"
            android:paddingStart="@dimen/activity_horizontal_margin"
            android:paddingEnd="@dimen/activity_horizontal_margin"
            android:paddingTop="@dimen/activity_vertical_margin"
            android:paddingBottom="@dimen/activity_vertical_margin"
            >

            <!-- Content snipped for brevity -->

            <!-- blah blah... lots of content here -->

        </LinearLayout>

</ScrollView>

这里是在GitHub上的仓库HERE,如果您需要更多信息:

3个回答

9

谷歌在其发布于 GitHub 上的 google-sample 项目中,提供了一个示例来解决这个问题。

创建一个继承自原始 SwipeRefreshLayout 的视图:

/*
 * Copyright 2014 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.example.android.swiperefreshmultipleviews;

import android.content.Context;
import android.support.v4.view.ViewCompat;
import android.support.v4.widget.SwipeRefreshLayout;
import android.util.AttributeSet;
import android.view.View;
import android.widget.AbsListView;

/**
 * A descendant of {@link android.support.v4.widget.SwipeRefreshLayout} which supports multiple
 * child views triggering a refresh gesture. You set the views which can trigger the gesture via
 * {@link #setSwipeableChildren(int...)}, providing it the child ids.
 */
public class MultiSwipeRefreshLayout extends SwipeRefreshLayout {

    private View[] mSwipeableChildren;

    public MultiSwipeRefreshLayout(Context context) {
        super(context);
    }

    public MultiSwipeRefreshLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    /**
     * Set the children which can trigger a refresh by swiping down when they are visible. These
     * views need to be a descendant of this view.
     */
    public void setSwipeableChildren(final int... ids) {
        assert ids != null;

        // Iterate through the ids and find the Views
        mSwipeableChildren = new View[ids.length];
        for (int i = 0; i < ids.length; i++) {
            mSwipeableChildren[i] = findViewById(ids[i]);
        }
    }

    // BEGIN_INCLUDE(can_child_scroll_up)
    /**
     * This method controls when the swipe-to-refresh gesture is triggered. By returning false here
     * we are signifying that the view is in a state where a refresh gesture can start.
     *
     * <p>As {@link android.support.v4.widget.SwipeRefreshLayout} only supports one direct child by
     * default, we need to manually iterate through our swipeable children to see if any are in a
     * state to trigger the gesture. If so we return false to start the gesture.
     */
    @Override
    public boolean canChildScrollUp() {
        if (mSwipeableChildren != null && mSwipeableChildren.length > 0) {
            // Iterate through the scrollable children and check if any of them can not scroll up
            for (View view : mSwipeableChildren) {
                if (view != null && view.isShown() && !canViewScrollUp(view)) {
                    // If the view is shown, and can not scroll upwards, return false and start the
                    // gesture.
                    return false;
                }
            }
        }
        return true;
    }
    // END_INCLUDE(can_child_scroll_up)

    // BEGIN_INCLUDE(can_view_scroll_up)
    /**
     * Utility method to check whether a {@link View} can scroll up from it's current position.
     * Handles platform version differences, providing backwards compatible functionality where
     * needed.
     */
    private static boolean canViewScrollUp(View view) {
        if (android.os.Build.VERSION.SDK_INT >= 14) {
            // For ICS and above we can call canScrollVertically() to determine this
            return ViewCompat.canScrollVertically(view, -1);
        } else {
            if (view instanceof AbsListView) {
                // Pre-ICS we need to manually check the first visible item and the child view's top
                // value
                final AbsListView listView = (AbsListView) view;
                return listView.getChildCount() > 0 &&
                        (listView.getFirstVisiblePosition() > 0
                                || listView.getChildAt(0).getTop() < listView.getPaddingTop());
            } else {
                // For all other view types we just check the getScrollY() value
                return view.getScrollY() > 0;
            }
        }
    }
    // END_INCLUDE(can_view_scroll_up)
}

在您的xml布局中使用此视图:

<com.example.android.swiperefreshmultipleviews.MultiSwipeRefreshLayout
      xmlns:android="http://schemas.android.com/apk/res/android"
      android:id="@+id/swiperefresh"
      android:layout_width="match_parent"
      android:layout_height="match_parent">

    <!-- your code -->

</com.example.android.swiperefreshmultipleviews.MultiSwipeRefreshLayout>

在你的活动或片段中,你可以使用以下组件:

mSwipeRefreshLayout = (MultiSwipeRefreshLayout) view.findViewById(R.id.swiperefresh);
mSwipeRefreshLayout.setSwipeableChildren(android.R.id.list, android.R.id.empty);

android.R.id.list 和 android.R.id.empty 是你的列表或 Recycler 视图的 ID。这些视图与具有相同 ID 的两个列表完美地配合使用。

您可以在Google示例GitHub项目中查看真实示例。


9

NestedScrollView已经被弃用,请更新您的答案或将其删除。这个解决方案目前可行,但是谷歌有时会删除这个类。 - JonasPTFL
1
更正一下,之前链接的已经过时了,但它已经迁移到了AndroidX:NestedScrollView - jschlepp
1
正如@jschlepp所说,使用androidx.core.widget.NestedScrollView - SqAR.org

4
我解决了这个问题。我创建了如下的SwipeRefreshLayout:
public class MenuSwipeRefreshLayout: SwipeRefreshLayout {

    public var target: View? = null

    constructor(ctx: Context): super(ctx)
    constructor(ctx: Context, attr: AttributeSet): super(ctx, attr)

    override fun canChildScrollUp(): Boolean {
        return target?.canScrollVertically(-1) ?: super.canChildScrollUp()
    }
}

每次ViewPager切换视图,我都将目标设置为可见的ScrollView。

顺便说一句,这是Kotlin而不是Java。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接