美文网首页协同布局
Android中RefreshLayout + Coordina

Android中RefreshLayout + Coordina

作者: 馒头炖土豆 | 来源:发表于2023-02-06 14:28 被阅读0次
RefreshLayout + CoordinatorLayout + AppBarLayout + MagicIndicator + ViewPager + Fragment

这是一个老生常谈的问题,网上也有很多优秀的方案,我也是经过自己的搜索、对比,最终选择出现在使用的这套
这个问题的主要点有三个
1:AppBarLayout 必须要设置layout_behavior
2:折叠部分必须要设置layout_scrollFlags
3:位于悬浮部分下面的viewpager必须设置layout_behavior

xml的布局文件:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    android:id="@+id/main_content"
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:background="@color/white"
    android:focusable="true"
    android:focusableInTouchMode="true"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <!--页面顶部部分,比如返回按钮、标题等-->
    <RelativeLayout
        android:layout_marginTop="@dimen/dp_25"
        android:id="@+id/rl_top_nav"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        android:layout_width="match_parent"
        android:layout_height="@dimen/dp_44">
    </RelativeLayout>
    <com.scwang.smartrefresh.layout.SmartRefreshLayout
        android:layout_marginTop="@dimen/dp_70"
        android:id="@+id/refresh_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:srlEnableLoadMore="false"
        app:srlHeaderTriggerRate="0.8"
        app:srlEnableRefresh="true">

        <com.kongfz.app.core.ui.widget.loading.RefreshHeaderView2
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />

        <com.kongfz.app.core.kfz2.widgets.MyCoordinatorLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent">
            <com.google.android.material.appbar.AppBarLayout
                android:id="@+id/appbarlayout"
                app:elevation="0dp"
                app:layout_behavior="com.kongfz.app.core.kfz2.widgets.appbar.FixAppBarLayoutBehavior"
                android:orientation="vertical"
                android:layout_width="match_parent"
                android:layout_height="wrap_content">
                <!--折叠部分-->
                <androidx.recyclerview.widget.RecyclerView
                    app:layout_scrollFlags="scroll|enterAlwaysCollapsed"
                    android:id="@+id/rv_top"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content" />
                <!--悬浮部分-->
                <RelativeLayout
                    android:id="@+id/rl_tab"
                    android:paddingHorizontal="@dimen/dp_30"
                    android:background="@drawable/home_total_list_bg"
                    android:layout_width="match_parent"
                    android:layout_height="@dimen/dp_50">
                    <RelativeLayout
                        android:layout_centerInParent="true"
                        android:layout_width="wrap_content"
                        android:layout_height="@dimen/dp_50">
                        <com.kongfz.app.core.common.widgets.tab.MagicIndicator
                            android:layout_marginTop="@dimen/dp_1"
                            android:id="@+id/magicIndicator_recommend"
                            android:layout_width="@dimen/dp_300"
                            android:layout_height="@dimen/dp_49" />
                    </RelativeLayout>
                </RelativeLayout>

            </com.google.android.material.appbar.AppBarLayout>

            <androidx.viewpager.widget.ViewPager
                android:background="@color/gray4"
                android:id="@+id/vp_recommend"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                app:layout_behavior="@string/appbar_scrolling_view_behavior" />
        </com.kongfz.app.core.kfz2.widgets.MyCoordinatorLayout>
    </com.scwang.smartrefresh.layout.SmartRefreshLayout>
 <!--暂无数据的空页面-->
    <RelativeLayout
        android:layout_below="@id/rl_top_nav"
        android:visibility="gone"
        android:id="@+id/rl_empty"
        android:background="@color/white"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
    </RelativeLayout>
    <!--用来展示骨架屏-->
    <RelativeLayout
        android:id="@+id/rl_ske"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@id/rl_top_nav" />
</RelativeLayout>

AppBarLayout的Behavior:

import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.OverScroller;
import androidx.coordinatorlayout.widget.CoordinatorLayout;
import com.google.android.material.appbar.AppBarLayout;
import java.lang.reflect.Field;

//用于解决CoordinatorLayout+AppBarLayout+RecyclerView导致的滑动冲突抖动
public class FixAppBarLayoutBehavior extends AppBarLayout.Behavior{
    private static final String TAG = "FixBehavior";
    private static final int TYPE_FLING = 1;
    private boolean isFlinging;
    private boolean shouldBlockNestedScroll;

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

    @Override
    public boolean onInterceptTouchEvent(CoordinatorLayout parent, AppBarLayout child, MotionEvent ev) {
        Log.d(TAG, "onInterceptTouchEvent:" + child.getTotalScrollRange());
        shouldBlockNestedScroll = isFlinging;
        switch (ev.getActionMasked()) {
            case MotionEvent.ACTION_DOWN:
                //手指触摸屏幕的时候停止fling事件
                stopAppbarLayoutFling(child);
                break;
            default:
                break;
        }
        return super.onInterceptTouchEvent(parent, child, ev);
    }

    /**
     * 反射获取私有的flingRunnable 属性,考虑support 28以后变量名修改的问题
     *
     * @return Field
     */
    private Field getFlingRunnableField() throws NoSuchFieldException {
        Class<?> superclass = this.getClass().getSuperclass();
        try {
            // support design 27及一下版本
            Class<?> headerBehaviorType = null;
            if (superclass != null) {
                headerBehaviorType = superclass.getSuperclass();
            }
            if (headerBehaviorType != null) {
                return headerBehaviorType.getDeclaredField("mFlingRunnable");
            } else {
                return null;
            }
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
            // 可能是28及以上版本
            Class<?> headerBehaviorType = superclass.getSuperclass().getSuperclass();
            if (headerBehaviorType != null) {
                return headerBehaviorType.getDeclaredField("flingRunnable");
            } else {
                return null;
            }
        }
    }

    /**
     * 反射获取私有的scroller 属性,考虑support 28以后变量名修改的问题
     *
     * @return Field
     */
    private Field getScrollerField() throws NoSuchFieldException {
        Class<?> superclass = this.getClass().getSuperclass();
        try {
            // support design 27及一下版本
            Class<?> headerBehaviorType = null;
            if (superclass != null) {
                headerBehaviorType = superclass.getSuperclass();
            }
            if (headerBehaviorType != null) {
                return headerBehaviorType.getDeclaredField("mScroller");
            } else {
                return null;
            }
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
            // 可能是28及以上版本
            Class<?> headerBehaviorType = superclass.getSuperclass().getSuperclass();
            if (headerBehaviorType != null) {
                return headerBehaviorType.getDeclaredField("scroller");
            } else {
                return null;
            }
        }
    }

    /**
     * 停止appbarLayout的fling事件
     *
     * @param appBarLayout
     */
    private void stopAppbarLayoutFling(AppBarLayout appBarLayout) {
        //通过反射拿到HeaderBehavior中的flingRunnable变量
        try {
            Field flingRunnableField = getFlingRunnableField();
            Runnable flingRunnable;
            if (flingRunnableField != null) {
                flingRunnableField.setAccessible(true);
                flingRunnable = (Runnable) flingRunnableField.get(this);
                if (flingRunnable != null) {
                    Log.d(TAG, "存在flingRunnable");
                    appBarLayout.removeCallbacks(flingRunnable);
                    flingRunnableField.set(this, null);
                }
            }

            Field scrollerField = getScrollerField();
            if (scrollerField != null) {
                scrollerField.setAccessible(true);
                OverScroller overScroller = (OverScroller) scrollerField.get(this);
                if (overScroller != null && !overScroller.isFinished()) {
                    overScroller.abortAnimation();
                }
            }
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }

    @Override
    public boolean onStartNestedScroll(CoordinatorLayout parent, AppBarLayout child, View directTargetChild, View target, int nestedScrollAxes, int type) {
        Log.d(TAG, "onStartNestedScroll");
        stopAppbarLayoutFling(child);
        return super.onStartNestedScroll(parent, child, directTargetChild, target,
                nestedScrollAxes, type);
    }

    @Override
    public void onNestedPreScroll(CoordinatorLayout coordinatorLayout, AppBarLayout child, View target, int dx, int dy, int[] consumed, int type) {
        Log.d(TAG, "onNestedPreScroll:" + child.getTotalScrollRange() + " ,dx:" + dx + " ,dy:" + dy + " ,type:" + type);
        //type返回1时,表示当前target处于非touch的滑动,
        //该bug的引起是因为appbar在滑动时,CoordinatorLayout内的实现NestedScrollingChild2接口的滑动
        //子类还未结束其自身的fling
        //所以这里监听子类的非touch时的滑动,然后block掉滑动事件传递给AppBarLayout
        if (type == TYPE_FLING) {
            isFlinging = true;
        }
        if (!shouldBlockNestedScroll) {
            super.onNestedPreScroll(coordinatorLayout, child, target, dx, dy, consumed, type);
        }
    }

    @Override
    public void onNestedScroll(CoordinatorLayout coordinatorLayout, AppBarLayout child, View target, int dxConsumed, int dyConsumed, int dxUnconsumed, int dyUnconsumed, int type) {
        Log.d(TAG, "onNestedScroll: target:" + target.getClass() + " ," + child.getTotalScrollRange() + " ,dxConsumed:" + dxConsumed + " ,dyConsumed:" + dyConsumed + " " + ",type:" + type);
        if (!shouldBlockNestedScroll) {
            super.onNestedScroll(coordinatorLayout, child, target, dxConsumed, dyConsumed, dxUnconsumed, dyUnconsumed, type);
        }
    }

    @Override
    public void onStopNestedScroll(CoordinatorLayout coordinatorLayout, AppBarLayout abl, View target, int type) {
        Log.d(TAG, "onStopNestedScroll");
        super.onStopNestedScroll(coordinatorLayout, abl, target, type);
        isFlinging = false;
        shouldBlockNestedScroll = false;
    }
}

兼容横向滑动的MyCoordinatorLayout:

import android.content.Context;
import android.util.AttributeSet;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.coordinatorlayout.widget.CoordinatorLayout;
import androidx.core.view.ViewCompat;

public class MyCoordinatorLayout extends CoordinatorLayout {
    public MyCoordinatorLayout(@NonNull Context context) {
        super(context);
    }

    public MyCoordinatorLayout(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    public MyCoordinatorLayout(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    public boolean onStartNestedScroll(View child, View target, int axes, int type) {
        if ((axes & ViewCompat.SCROLL_AXIS_HORIZONTAL) != 0) {
            //不处理横向嵌套滑动事件
            return false;
        }
        return super.onStartNestedScroll(child, target, axes, type);
    }
}
Fragment中的xml,注意这里最外层的layout_behavio设置,这里可以看到空页面时我使用了NestedScrollView,并且设置了app:layout_behavior,主要是我们需要空页面的时候也能跟随顶部折叠部分收起而滑动;这里的骨架屏也是同理
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <com.scwang.smartrefresh.layout.SmartRefreshLayout
        android:id="@+id/refresh_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:srlEnableLoadMore="true"
        app:srlEnableRefresh="false">

        <androidx.recyclerview.widget.RecyclerView
            android:id="@+id/rv_recommend"
            android:layout_marginHorizontal="@dimen/dp_5"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />
        <com.kongfz.app.core.ui.widget.loading.RefreshFooterView2
            android:background="@color/gray_4"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />
    </com.scwang.smartrefresh.layout.SmartRefreshLayout>
    <!--分类列表接口错误的时候显示的骨架屏-->
    <androidx.core.widget.NestedScrollView
        android:id="@+id/sv_ste"
        android:visibility="gone"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <LinearLayout
            android:background="@color/gold_dark"
            android:orientation="vertical"
            android:id="@+id/ll_ste"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"/>
    </androidx.core.widget.NestedScrollView>
    <!--分类列表接口返回data为[]时显示的空页面-->
    <androidx.core.widget.NestedScrollView
        android:visibility="gone"
        android:background="@color/white"
        android:id="@+id/sv_empty_list"
        app:layout_behavior="@string/appbar_scrolling_view_behavior"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <RelativeLayout
            android:id="@+id/rl_empty_list"
            android:layout_width="match_parent"
            android:layout_height="match_parent">
        
        </RelativeLayout>
    </androidx.core.widget.NestedScrollView>
</RelativeLayout>

相关文章

网友评论

    本文标题:Android中RefreshLayout + Coordina

    本文链接:https://www.haomeiwen.com/subject/uijtkdtx.html