CoordinatorLayout implementiert sekundäre Aufhängungen und mehrere Aufhängungen

Wirkung erzielen

 

Laden Sie den Code direkt hoch

public class CSFragment4 extends BaseMVPFragment<CSPresenter> implements CSContract.View {



    @BindView(R.id.appbar)
    AppBarLayout appBarLayout;
    @BindView(R.id.top_sticky_lin)
    LinearLayout top_sticky_lin;
    @BindView(R.id.real_top_sticky_lin)
    LinearLayout real_top_sticky_lin;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;

    @BindView(R.id.mainTitle)
    View mainTitle;
    @BindView(R.id.city_tv)
    TextView city_tv;
    @BindView(R.id.map_iv)
    TextView map_iv;
    @BindView(R.id.title_bar)
    LinearLayout title_bar;
    @BindView(R.id.search_lin)
    LinearLayout search_lin;
    @BindView(R.id.tab_layout)
    TabLayout tab_layout;

    int top_sticky_totlal=0;

    public static CSFragment4 getInstance() {
        CSFragment4 fragment = new CSFragment4();
        Bundle bundle = new Bundle();
        fragment.setArguments(bundle);
        return fragment;
    }



    @Override
    protected void initInject() {
        getFragmentComponent().inject(this);
    }

    @Override
    protected int getLayout() {
        return R.layout.scxm_fragment_cs4;
    }

    public LinearLayoutManager linear;
    public int posint;
    @Override
    protected void initEventAndData() {
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        recyclerView.setAdapter(new RcvAdapter2());

        real_top_sticky_lin.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                top_sticky_totlal=real_top_sticky_lin.getTop();
            }
        });
        appBarLayout.post(new Runnable() {
            @Override
            public void run() {
                appBarLayout.addOnOffsetChangedListener(translateSearch());
            }
        });
        city_tv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                CoordinatorLayout.Behavior behavior =
                        ((CoordinatorLayout.LayoutParams) appBarLayout
                                .getLayoutParams())
                                .getBehavior();
                if (behavior instanceof AppBarLayout.Behavior) {
                    AppBarLayout.Behavior appBarLayoutBehavior = (AppBarLayout.Behavior) behavior;
                    //快熟滑动到顶部
                    appBarLayoutBehavior.setTopAndBottomOffset(0);
                }
            }
        });


    }
    AppBarLayout.OnOffsetChangedListener appBarLayou;
    private AppBarLayout.OnOffsetChangedListener translateSearch() {
        return (appBarLayou!=null)?appBarLayou:new AppBarLayout.OnOffsetChangedListener(){
            @Override
            public void onOffsetChanged(AppBarLayout appBarLayout, int i) {
                ViewGroup.MarginLayoutParams searchLayoutParams = (ViewGroup.MarginLayoutParams) search_lin.getLayoutParams();
                float searchLayoutNewTopMargin = 0;
                float searchLayoutNewLeftMargin = 0f;
                float searchLayoutNewWidth = 0f;
                float alpha = 0f;
                float MIN_TOP_MARGIN = Float.valueOf(mainTitle.getTop());
                float MAX_TOP_MARGIN = Float.valueOf(title_bar.getBottom());
                float MAX_WIDTH = Float.valueOf(search_lin.getWidth());
                float MIN_WIDTH = Float.valueOf((getScreenWidth() - city_tv.getRight() - city_tv.getWidth() - UnitsUtils.dp2px(getActivity(), 16f) * 2));
                float MIN_LEFT_MARGIN = Float.valueOf(search_lin.getLeft());
                float MAX_LEFT_MARGIN = Float.valueOf(city_tv.getRight() + UnitsUtils.dp2px(getActivity(), 16f));
                float mDy = -i;

                if (mDy < top_sticky_totlal) {
                    top_sticky_lin.setVisibility(View.GONE);
                }else if (mDy==0){

                }else{
                    top_sticky_lin.setVisibility(View.VISIBLE);
                }
                searchLayoutNewTopMargin = MAX_TOP_MARGIN - mDy * 0.5f;
                if (searchLayoutNewTopMargin < MIN_TOP_MARGIN) {
                    searchLayoutNewTopMargin = MIN_TOP_MARGIN;
                }
                if (searchLayoutNewTopMargin > MAX_TOP_MARGIN) {
                    searchLayoutNewTopMargin = MAX_TOP_MARGIN;
                }
                searchLayoutNewLeftMargin = MIN_LEFT_MARGIN + mDy * 0.5f;
                if (searchLayoutNewLeftMargin > MAX_LEFT_MARGIN) {
                    searchLayoutNewLeftMargin = MAX_LEFT_MARGIN;
                }
                if (searchLayoutNewLeftMargin < MIN_LEFT_MARGIN) {
                    searchLayoutNewLeftMargin = MIN_LEFT_MARGIN;
                }

                searchLayoutNewWidth = MAX_WIDTH - mDy * 1.0f;
                if (searchLayoutNewWidth < MIN_WIDTH) {
                    searchLayoutNewWidth = MIN_WIDTH;
                }
                if (searchLayoutNewWidth > MAX_WIDTH) {
                    searchLayoutNewWidth = MAX_WIDTH;
                }
                searchLayoutParams.topMargin = (int) searchLayoutNewTopMargin;
                searchLayoutParams.leftMargin = (int) searchLayoutNewLeftMargin;
                searchLayoutParams.width = (int) searchLayoutNewWidth;
                search_lin.setLayoutParams(searchLayoutParams);
            }
        };
    }


    public int getScreenWidth() {
        WindowManager wm = (WindowManager) getActivity().getSystemService(Context.WINDOW_SERVICE);
        Point point = new Point();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            wm.getDefaultDisplay().getRealSize(point);
        } else {
            wm.getDefaultDisplay().getSize(point);
        }
        return point.x;
    }



}

 2.xml-Datei

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
    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">
    <androidx.coordinatorlayout.widget.CoordinatorLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@color/white">

        <com.google.android.material.appbar.AppBarLayout
            app:layout_behavior="com.sc.scxm.cs.AppBarLayoutBehavior"
            android:id="@+id/appbar"
            app:elevation="0dp"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <com.google.android.material.appbar.CollapsingToolbarLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:fitsSystemWindows="true"
                app:layout_scrollFlags="scroll|exitUntilCollapsed">

                <RelativeLayout
                    android:layout_width="match_parent"
                    android:layout_height="300dp"
                    android:layout_marginTop="48dp"
                    app:layout_collapseMode="none">

                    <ImageView
                        android:id="@+id/iv_bg"
                        android:layout_width="match_parent"
                        android:layout_height="match_parent"
                        android:background="@mipmap/ic_entrust_bg"
                        android:scaleType="centerCrop" />
                    <TextView
                        android:id="@+id/text1_tv"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:text="专业委托"
                        android:textColor="@color/white"
                        android:layout_marginLeft="16dp"
                        android:layout_marginBottom="20dp"
                        android:textSize="20sp"
                        android:textStyle="bold"
                        android:layout_marginTop="100dp"
                        />
                    <LinearLayout
                        android:id="@+id/real_top_sticky_lin"
                        android:layout_width="match_parent"
                        android:layout_height="70dp"
                        android:layout_below="@id/text1_tv"
                        android:background="#ff6600">

                        <TextView
                            android:layout_width="0dp"
                            android:layout_height="match_parent"
                            android:layout_weight="1"
                            android:text="金额18"
                            android:gravity="center"
                            android:textSize="16sp"
                            android:textColor="@color/black"/>

                        <TextView
                            android:layout_width="0dp"
                            android:layout_height="match_parent"
                            android:layout_weight="1"
                            android:text="流量5g"
                            android:gravity="center"
                            android:textSize="16sp"
                            android:textColor="@color/black"/>
                    </LinearLayout>
                </RelativeLayout>
                <androidx.appcompat.widget.Toolbar
                    android:id="@+id/toolbar"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:background="#00000000"
                    app:layout_collapseMode="pin"
                    android:minHeight="@dimen/dp_48"
                    android:padding="0dp"
                    app:titleMargin="0dp"
                    app:contentInsetStart="0dp"
                    app:contentInsetStartWithNavigation="0dp">

                    <RelativeLayout
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content">

                        <LinearLayout
                            android:id="@+id/title_bar"
                            android:layout_width="match_parent"
                            android:layout_height="50dp"
                            android:background="@color/white"
                            android:gravity="center_vertical"
                            android:orientation="vertical">

                        </LinearLayout>

                        <LinearLayout
                            android:layout_width="match_parent"
                            android:layout_height="70dp"
                            android:layout_below="@id/title_bar"
                            android:background="#00000000"
                            android:orientation="vertical"
                            android:visibility="visible">

                            <LinearLayout
                                android:id="@+id/top_sticky_lin"
                                android:layout_width="match_parent"
                                android:layout_height="match_parent"
                                android:background="#ff6600"
                                android:visibility="gone">

                                <TextView
                                    android:layout_width="0dp"
                                    android:layout_height="match_parent"
                                    android:layout_weight="1"
                                    android:gravity="center"
                                    android:text="金额18"
                                    android:textColor="@color/black"
                                    android:textSize="16sp" />

                                <TextView
                                    android:layout_width="0dp"
                                    android:layout_height="match_parent"
                                    android:layout_weight="1"
                                    android:gravity="center"
                                    android:text="流量5g"
                                    android:textColor="@color/black"
                                    android:textSize="16sp" />
                            </LinearLayout>
                        </LinearLayout>
                    </RelativeLayout>
                </androidx.appcompat.widget.Toolbar>
            </com.google.android.material.appbar.CollapsingToolbarLayout>
            <com.google.android.material.tabs.TabLayout
                android:id="@+id/tab_layout"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                app:tabIndicatorHeight="0dp"
                app:tabIndicatorColor="@color/white"
                app:tabBackground="@android:color/transparent"
                app:tabRippleColor="@android:color/transparent"
                android:background="#fff">

                <com.google.android.material.tabs.TabItem
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:text="tab1"/>

                <com.google.android.material.tabs.TabItem
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:text="tab2"/>

            </com.google.android.material.tabs.TabLayout>
        </com.google.android.material.appbar.AppBarLayout>
        <androidx.recyclerview.widget.RecyclerView
            android:id="@+id/recyclerView"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:layout_behavior="@string/appbar_scrolling_view_behavior"
            app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"/>
    </androidx.coordinatorlayout.widget.CoordinatorLayout>
    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/white"
        android:orientation="vertical">

        <LinearLayout
            android:id="@+id/title_lin"
            android:layout_width="match_parent"
            android:layout_height="50dp"
            android:gravity="center_vertical"
            android:background="@color/white">
            <TextView
                android:id="@+id/city_tv"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginStart="16dp"
                android:layout_marginLeft="16dp"
                android:layout_marginEnd="16dp"
                android:drawablePadding="16dp"
                android:text="重庆"
                android:textStyle="bold" />

            <View
                android:id="@+id/mainTitle"
                android:layout_width="0dp"
                android:layout_height="35dp"
                android:layout_weight="1"/>

            <TextView
                android:id="@+id/map_iv"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginStart="16dp"
                android:layout_marginLeft="16dp"
                android:paddingRight="16dp"
                android:text="展开"
                android:textStyle="bold" />
        </LinearLayout>
        <LinearLayout
            android:id="@+id/search_lin"
            android:layout_width="match_parent"
            android:layout_height="40dp"
            android:layout_marginLeft="16dp"
            android:layout_marginRight="16dp"
            android:layout_marginBottom="2dp"
            android:layout_marginTop="50dp"
            android:layout_alignParentLeft="true">
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="18dp"
                android:paddingTop="8dp"
                android:paddingBottom="8dp"
                android:text="找好铺"
                android:textColor="#AFB4B9"
                android:singleLine="true"
                android:ellipsize="end" />
        </LinearLayout>
    </RelativeLayout>

</FrameLayout>

3.AppBarLayoutBehavior

public class AppBarLayoutBehavior extends AppBarLayout.Behavior {

    private static final String TAG = "AppbarLayoutBehavior";
    private static final int TYPE_FLING = 1;
    private boolean isFlinging;
    private boolean shouldBlockNestedScroll;

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

    @Override
    public boolean onInterceptTouchEvent(CoordinatorLayout parent, AppBarLayout child, MotionEvent ev) {
        LogUtil.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
     * @throws NoSuchFieldException
     */
    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
     * @throws NoSuchFieldException
     */
    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();
            Field scrollerField = getScrollerField();
            if (flingRunnableField != null) {
                flingRunnableField.setAccessible(true);
            }
            if (scrollerField != null) {
                scrollerField.setAccessible(true);
            }
            Runnable flingRunnable = null;
            if (flingRunnableField != null) {
                flingRunnable = (Runnable) flingRunnableField.get(this);
            }
            OverScroller overScroller = (OverScroller) scrollerField.get(this);
            if (flingRunnable != null) {
                LogUtil.d(TAG, "存在flingRunnable");
                appBarLayout.removeCallbacks(flingRunnable);
                flingRunnableField.set(this, null);
            }
            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) {
        LogUtil.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) {
        LogUtil.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) {
        LogUtil.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) {
        LogUtil.d(TAG, "onStopNestedScroll");
        super.onStopNestedScroll(coordinatorLayout, abl, target, type);
        isFlinging = false;
        shouldBlockNestedScroll = false;
    }

    private static class LogUtil{
        static void d(String tag, String string){
            Log.d(tag,string);
        }
    }

}

Acho que você gosta

Origin blog.csdn.net/qq_15059163/article/details/128280521
Recomendado
Clasificación