【4858.com】安卓和iOS完毕上海好笑剧团停靠顶端悬浮框,CoordinatorLayout中各样控件完结德姆o

By admin in 4858.com on 2019年9月17日

一言不合就上海体育地方

一、简述CoordinatorLayout

原理请看这里 Android
design包中CoordinatorLayout的宏图原理
再看看facebook的效果

1018039-920fa0d9d86fa68b.gif

上边直接贴网络有的经文德姆o

此文的代码在Android Design Support
Library(一)用TabLayout达成类似搜狐选项卡动态滑动作效果果代码的根基上开展改变,如若您从未看过本种类的首先篇小说最佳先看一看。
CoordinatorLayout是Android Design Support
Library中相比较难的控件,望文生义,它是用来组织它的子views之间合营的一个父view。CoordinatorLayout私下认可意况下可领略是贰个FrameLayout,它的布局情势暗许是一层一层叠上去,在此地作者会介绍一下它最常用的两种状态。

那二日品种中须求贯彻多少个页面,大概的布局是顶上部分一块区域是一局地内容,然后下边是二个title条,那个title条下边是一个列表,因为列表的多少或然有众多,所以那几个页面是索要总体举行滑动的,因为只让下边的listview滚动的话,那么上面的显得区域就太小了,因为大家的listview的Item内容也比非常多,但是说只假诺scrollview嵌套listview,那么那一个title条也会被滚动出荧屏,然而我们的要命title条里面还会有触发上面listview删除、修改的意义,所以不能够滚动出显示屏,必要有三个吸顶的法力。
  思量过用stickylistheaderslistview,不过未免太麻烦了,所以我们大势所趋的选料了Material
Design中很有滚动作效果应的CoordinatorLayout了,它也很专长做那类滚动至显示器上方然后截止滚动的业务。接下来就跟原先似得从头写代码了,xml布局如下:

4858.com 1Android_view.gif4858.com 2iOS_view.gif

事例一:尾巴部分菜单抽屉效果

1. CoordinatorLayout达成Toolbar掩盖效果
先来探视效果

<android.support.design.widget.CoordinatorLayout  
    android:overScrollMode="never"  
    android:layout_alignParentTop="true"  
    android:layout_width="match_parent"  
    android:layout_height="match_parent">  

    <android.support.design.widget.AppBarLayout  
        android:overScrollMode="never"  
        app:elevation = "0dp"  
        android:layout_width="match_parent"  
        android:layout_height="wrap_content">  

        <android.support.design.widget.CollapsingToolbarLayout  
            android:id="@+id/collapsingToolbarLayout"  
            android:layout_width="match_parent"  
            android:layout_height="wrap_content"  
            android:overScrollMode="never"  
            app:layout_scrollFlags="scroll|exitUntilCollapsed">  

         <LinearLayout  
            android:id="@+id/firstLl"  
            android:orientation="vertical"  
            android:layout_width="match_parent"  
            android:layout_height="wrap_content">  

            <TextView  
                android:layout_width="match_parent"  
                android:layout_height="49dip"  
                android:background="@color/color_ffffff"  
                android:drawableLeft="@drawable/user_details_icon_basic"  
                android:drawablePadding="5dip"  
                android:gravity="center_vertical"  
                android:paddingLeft="16dip"  
                android:text="a信息"  
                android:textColor="@color/color_3399ff"  
                android:textSize="15sp"/>  

            <View style="@style/view_line"/>  

            <RelativeLayout  
                android:layout_width="match_parent"  
                android:layout_height="wrap_content"  
                android:background="@color/color_ffffff">  

                <TextView  
                    style="@style/style_basicinfo"  
                    android:layout_alignParentLeft="true"  
                    android:text="1字段"/>  

                <TextView  
                    style="@style/style_basicinfo"  
                    android:layout_alignParentRight="true"/>  

            </RelativeLayout>  

            <RelativeLayout  
                android:layout_width="match_parent"  
                android:layout_height="wrap_content"  
                android:background="@color/color_ffffff">  

                <TextView  
                    style="@style/style_basicinfo"  
                    android:layout_alignParentLeft="true"  
                    android:text="2字段"/>  

                <TextView  
                    style="@style/style_basicinfo"  
                    android:textColor="@color/color_3399ff"  
                    android:layout_alignParentRight="true"/>  

            </RelativeLayout>  

            <RelativeLayout  
                android:layout_width="match_parent"  
                android:layout_height="wrap_content"  
                android:background="@color/color_ffffff">  

                <TextView  
                    style="@style/style_basicinfo"  
                    android:layout_alignParentLeft="true"  
                    android:text="3字段"/>  

                <TextView  
                    style="@style/style_basicinfo"  
                    android:layout_alignParentRight="true"/>  

            </RelativeLayout>  

            <LinearLayout  
                android:paddingTop="15dip"  
                android:background="@color/color_ffffff"  
                android:layout_width="match_parent"  
                android:layout_height="wrap_content">  
                <View  
                    style="@style/view_line"/>  
            </LinearLayout>  

            <View  
                android:background="@color/color_e5e5e5"  
                android:layout_width="match_parent"  
                android:layout_height="16dip"/>  
        </LinearLayout>  
    </android.support.design.widget.CollapsingToolbarLayout>  

</android.support.design.widget.AppBarLayout>  

<LinearLayout  
    app:layout_behavior="@string/appbar_scrolling_view_behavior"  
    android:layout_width="match_parent"  
    android:layout_height="match_parent"  
    android:orientation="vertical">  

    <RelativeLayout  
            android:id="@+id/secondRl"  
            android:background="@color/color_ffffff"  
            android:paddingRight="16dip"  
            android:layout_width="match_parent"  
            android:layout_height="49dip">  

            <TextView  
                android:layout_width="wrap_content"  
                android:layout_height="wrap_content"  
                android:layout_alignParentLeft="true"  
                android:drawableLeft="@drawable/user_details_icon_car"  
                android:drawablePadding="5dip"  
                android:gravity="center_vertical"  
                android:layout_centerVertical="true"  
                android:paddingLeft="16dip"  
                android:text="b信息"  
                android:textColor="@color/color_3399ff"  
                android:textSize="15sp"/>  

            <ImageView  
                android:layout_alignParentRight="true"  
                android:layout_centerVertical="true"  
                android:src="@drawable/received_details_btn_add"  
                android:layout_width="wrap_content"  
                android:layout_height="wrap_content"/>  

            <ImageView  
                android:layout_centerVertical="true"  
                android:layout_toLeftOf="@+id/addCarIv"  
                android:layout_marginRight="15dip"  
                android:src="@drawable/received_details_btn_edit"  
                android:layout_width="wrap_content"  
                android:layout_height="wrap_content"/>  

            <ImageView  
                android:visibility="gone"  
                android:layout_alignParentRight="true"  
                android:layout_centerVertical="true"  
                android:src="@drawable/received_details_btn_cancel"  
                android:layout_width="wrap_content"  
                android:layout_height="wrap_content"/>  

        </RelativeLayout>  

        <View  
            style="@style/view_line"/>  

        <LinearLayout  
            android:id="@+id/addLl"  
            android:gravity="center"  
            android:orientation="vertical"  
            android:background="@color/color_ffffff"  
            android:layout_width="match_parent"  
            android:layout_height="match_parent">  

            <ImageView  
                android:src="@drawable/received_icon_details_empty"  
                android:layout_width="wrap_content"  
                android:layout_height="wrap_content"/>  

            <TextView  
                android:textSize="15sp"  
                android:text="此处有点空"  
                android:layout_marginTop="15dip"  
                android:textColor="@color/color_333333"  
                android:layout_width="wrap_content"  
                android:layout_height="wrap_content"/>  

            <TextView  
                android:textSize="18sp"  
                android:text="快来添加吧"  
                android:layout_marginTop="10dip"  
                android:textColor="@color/color_3399ff"  
                android:layout_width="wrap_content"  
                android:layout_height="wrap_content"/>  

        </LinearLayout>  

        <android.support.v7.widget.RecyclerView  
            android:id="@+id/carlistview"  
            android:overScrollMode="never"  
            android:background="@color/color_ffffff"  
            android:divider="@drawable/developcar_shape_divider"  
            android:layout_width="match_parent"  
            android:layout_height="wrap_content"/>  
    </LinearLayout>  
</android.support.design.widget.CoordinatorLayout>

很早在此之前写过八个近似的功效,可是当下的做法是:

  • 在FrameLayout中布局listview和您想要在滑行时显得在最上部的布局并将品质设置为invisible。
  • 在代码中动态拉长想要悬停的布局为listview头布局(也正是悬停部分写五次)。
  • 【4858.com】安卓和iOS完毕上海好笑剧团停靠顶端悬浮框,CoordinatorLayout中各样控件完结德姆o。监听listview的滚动(滚动时呈现在布局中暗藏的局地达到悬停效果)

 @Override public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { if (firstVisibleItem >= 1) { //悬浮布局显示 invis.setVisibility(View.VISIBLE); } else { invis.setVisibility(View.GONE); } }
1 增加依赖
compile 'com.android.support:appcompat-v7:25.1.1'

4858.com 3

地方能够见到id为firstLl的LinearLayout就是大家开始时代说的非常最上部布局,而id为second昂Coral的RelativeLayout则是大家说的相当需求吸顶的title条了,用过CoordinatorLayout的同校都知情,假如哪一部分须求滑动出显示器,那么那部分就需求写在CollapsingToolbarLayout布局中,而CollapsingToolbarLayout要求写在AppBarLayout中,同期为了能够使那有的内容能够滑动也许找到其在CoordinatorLayout中的地点,供给给这一部分搭架子设置layout_scrollFlags属性,一般都设置值为scroll|exitUntilCollapsed因为大家也不供给新鲜的渐变之类的效应,只要能滑出显示屏就好了,然后呢,需求滑动到最上端接下来吸顶的布局我们须求安装layout_behavior属性,它报告了CoordinatorLayout本人在滑行时候实施怎么样表现,为了创设吸顶供给设置其值为@string/appbar_scrolling_view_behavior就好了,然后运维一看貌似一切都很美丽好。
  其实自个儿下边包车型大巴布局还会有三个id为addLl的LinearLayout,它是干嘛的吗?大家都驾驭列表非常的少的时候,总要给客商一些提示吧,它便是极其提示,其实当中正是部分文字以及图片了,可是是居中显得的,可是发掘二个难点,正是当列表为空那个布局展示的时候,里面包车型大巴内容并不曾完全居中,只是程度方向上居中了,垂直方向上是在荧屏底边的,那是为啥呢?其实就是三个简练的布局,不过它是被放在CoordinatorLayout中的,后来透过反复调节和测量试验,开掘是layout_scrollFlags的scroll值捣的鬼,倘使不设置这一个scroll值,那么下边是能够从中的,但是顶上部分不可能滑动了,借使设置的话,顶上部分是能力所能达到滑动了,但是上面不能够居中了。所以最终的化解格局是动态设置这几个layout_scrollFlags属性了,实例代码如下:

缺点:

  • 布局非常不足灵活
  • 不可能处监护人件(假诺想要作为四个fragment的滑行提示器不可能完结)。

安卓5.0后达成如此的布局就很简短了还要仍可以够管理各个风云

2 xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/coordinator"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true">


    <android.support.v4.widget.NestedScrollView
        android:id="@+id/nestedScrollView"
        android:layout_width="match_parent"
        android:layout_height="350dp"
        android:background="@mipmap/ic_launcher"
        app:layout_behavior="@string/bottom_sheet_behavior"
        app:behavior_peekHeight="0dp"
        app:behavior_hideable="true">
        <!--中间可以随意写自己的布局-->

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

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/fabs"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|end"
        android:layout_margin="@dimen/fab_margin"
        app:srcCompat="@android:drawable/ic_dialog_email" />


</android.support.design.widget.CoordinatorLayout>

接下去代码完结,首先仍然是安插build.gradle:

//因为在CoordinatorLayout中如果给CollapsingToolbarLayout设置的ScrollFlags有scroll,那么下面设置layout_behavior的布局就无法垂直居中  
//但是不设置scroll属性,那么上面的有无法滑动然后吸顶。所以只能够动态设置了  
private void setCollapsingToolbarLayoutFlag(@AppBarLayout.LayoutParams.ScrollFlags int flags){  
    AppBarLayout.LayoutParams layoutParams = (AppBarLayout.LayoutParams) binding.collapsingToolbarLayout.getLayoutParams();  
    layoutParams.setScrollFlags(flags);  
    binding.collapsingToolbarLayout.setLayoutParams(layoutParams);  

做法:

  • layout代码

 <?xml version="1.0" encoding="utf-8"?> <android.support.design.widget.CoordinatorLayout xmlns:andro xmlns:app="http://schemas.android.com/apk/res-auto" android:orientation="vertical" android:background="@color/white" android:layout_width="match_parent" android:layout_height="match_parent"> <android.support.design.widget.AppBarLayout android: android:layout_width="match_parent" android:layout_height="wrap_content" android:background="@color/white" app:elevation="0dp"> <!-- app:layout_scrollFlags="scroll" 加此属性可滚动 不加就固定在顶部--> <LinearLayout android:layout_width="match_parent" android:layout_height="48dp" android:gravity="center" app:layout_scrollFlags="scroll" android:background="@color/main_Green"> <TextView android: style="@style/ShowTv1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="在线测评" android:textColor="@color/white" /> </LinearLayout> <com.bigkoo.convenientbanner.ConvenientBanner android: android:layout_width="match_parent" android:layout_height="170dp" android:background="@mipmap/banner_loading" app:canLoop="true" app:layout_scrollFlags="scroll" /> <ImageView android:layout_width="match_parent" android:layout_height="1px" android:background="@android:color/darker_gray" /> <LinearLayout android:layout_width="match_parent" android:layout_height="4dp" android:background="#f0f0f0"></LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="130dp" android:orientation="horizontal"> <LinearLayout android:layout_width="0dp" android:layout_height="130dp" android:layout_weight="1" android: android:gravity="center_horizontal" android:background="@drawable/btn_bg_main" android:orientation="vertical"> <ImageView android:layout_width="80dp" android:layout_height="80dp" android:src="@mipmap/consult_icon"/> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:layout_marginLeft="1dp" android:gravity="center_horizontal" android:orientation="vertical"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="心理咨询师考试" android:textColor="#3399cc" style="@style/ShowTv2"/> <TextView android:layout_marginTop="5dp" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="做自己的咨询师" android:textColor="@color/default_gray" style="@style/ShowTv4"/> </LinearLayout> </LinearLayout> <ImageView android:layout_width="1px" android:layout_height="match_parent" android:background="@android:color/darker_gray" /> <LinearLayout android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1" android:orientation="vertical"> <LinearLayout android: android:layout_width="match_parent" android:layout_height="match_parent" android:layout_weight="1" android:background="@drawable/btn_bg_main" android:gravity="center_vertical" android:orientation="horizontal" android:paddingLeft="3dp" android:paddingRight="3dp"> <ImageView android: android:layout_width="44dp" android:layout_height="44dp" android:src="@mipmap/hunyin_icon" /> <LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="5dp" android:orientation="vertical"> <TextView android: style="@style/ShowTv3" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textColor="#f11e8a" android:text="婚姻家庭咨询师" /> <TextView android: style="ShowTv5" android:layout_marginTop="5dp" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="为幸福服务" android:textColor="@color/default_gray" /> </LinearLayout> </LinearLayout> <ImageView android:layout_width="match_parent" android:layout_height="1px" android:background="@android:color/darker_gray" /> <LinearLayout android: android:layout_width="match_parent" android:layout_height="match_parent" android:layout_weight="1" android:background="@drawable/btn_bg_main" android:focusable="true" android:gravity="center_vertical" android:orientation="horizontal" android:paddingLeft="3dp" android:paddingRight="3dp"> <ImageView android: android:layout_width="44dp" android:layout_height="44dp" android:focusable="false" android:src="@mipmap/yingyang_icon1" /> <LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="5dp" android:focusable="false" android:orientation="vertical"> <TextView android: style="ShowTv3" android:layout_width="wrap_content" android:layout_height="wrap_content" android:focusable="false" android:textColor="#ff742f" android:text="营养师资格证" /> <TextView android: style="ShowTv5" android:layout_width="wrap_content" android:layout_height="wrap_content" android:focusable="false" android:text="与健康同行" android:layout_marginTop="5dp" android:textColor="@color/default_gray" /> </LinearLayout> </LinearLayout> </LinearLayout> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="4dp" android:background="#f0f0f0"></LinearLayout> <View android: android:layout_width="match_parent" android:layout_height="1px" android:background="@android:color/darker_gray" android:visibility="gone" /> </android.support.design.widget.AppBarLayout> <android.support.v7.widget.RecyclerView android: android:layout_width="match_parent" android:layout_height="match_parent" android:background="@color/white" app:layout_behavior="@string/appbar_scrolling_view_behavior" /></android.support.design.widget.CoordinatorLayout>

4858.com 4layout.png

注意点:

  • 1:新属性app:layout_scrollFlags的行使,对应的值为:scroll,enterAlways,enterAlwaysCollapsed,snap,exitUntilCollapsed;也能够在代码中通过setScrollFlags方法应用,app:layout_scrollFlags=”scroll”就能够随着一块滚动假使不安装则在滑行的时候会悬停在顶端。
  • 2: 下边必需使用RecyclerView。

页面代码

package com.ygxinjian.anhui.test_online.Fragment;import android.content.Context;import android.support.design.widget.AppBarLayout;import android.support.v7.widget.LinearLayoutManager;import android.support.v7.widget.RecyclerView;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.ImageView;import android.widget.LinearLayout;import android.widget.TextView;import android.widget.Toast;import com.bigkoo.convenientbanner.ConvenientBanner;import com.bigkoo.convenientbanner.adapter.CBPageAdapter;import com.bigkoo.convenientbanner.adapter.CBViewHolderCreator;import com.bigkoo.convenientbanner.listener.OnItemClickListener;import com.chad.library.adapter.base.BaseQuickAdapter;import com.chad.library.adapter.base.BaseViewHolder;import com.nostra13.universalimageloader.core.ImageLoader;import com.ygxinjian.anhui.test_online.Activity.Consult_Test_Activity;import com.ygxinjian.anhui.test_online.Activity.Consult_Test_intros_Activity;import com.ygxinjian.anhui.test_online.Controller.NetworkImageHolderView;import com.ygxinjian.anhui.test_online.Model.JsEntry;import com.ygxinjian.anhui.test_online.R;import com.ygxinjian.anhui.test_online.TestOnlineApplication;import com.ygxinjian.anhui.test_online.View.DividerItemDecoration;import com.ygxinjian.anhui.test_online.utils.DevUtil;import java.util.ArrayList;import java.util.Arrays;import java.util.List;/** * Created by handongqiang on 16/12/29. */public class Fragment_Home extends BaseFragment implements View.OnClickListener{ private static final String TAG = "Fragment_Home"; private ConvenientBanner mConvenientBanner; private RecyclerView mRecyclerView; private AppBarLayout mAppBarLayout; private View mLine; private NewsAdapter mAdapter; private LinearLayout ll_consult_click,ll_hunying_click,ll_yingyang_click; List<String> mData; private String[] images = {"http://img2.imgtn.bdimg.com/it/u=3093785514,1341050958&fm=21&gp=0.jpg", "http://img2.3lian.com/2014/f2/37/d/40.jpg", "http://img2.3lian.com/2014/f2/37/d/39.jpg", "http://f.hiphotos.baidu.com/image/h%3D200/sign=1478eb74d5a20cf45990f9df460b4b0c/d058ccbf6c81800a5422e5fdb43533fa838b4779.jpg", "http://f.hiphotos.baidu.com/image/pic/item/09fa513d269759ee50f1971ab6fb43166c22dfba.jpg" }; @Override public View initView() { View view = View.inflate(mActivity, R.layout.fragment_home, null); ll_consult_click = (LinearLayout) view.findViewById(R.id.ll_consult); ll_hunying_click = (LinearLayout) view.findViewById(R.id.ll_hunyin); ll_yingyang_click = (LinearLayout) view.findViewById(R.id.ll_yingyang); ll_consult_click.setOnClickListener; ll_hunying_click.setOnClickListener; ll_yingyang_click.setOnClickListener; mConvenientBanner = (ConvenientBanner) view.findViewById(R.id.banner); mAppBarLayout = (AppBarLayout) view.findViewById(R.id.appbar_layout); mLine = view.findViewById(R.id.line_divider); mRecyclerView = (RecyclerView) view.findViewById(R.id.vertical_recyclerView); mRecyclerView.addItemDecoration(new DividerItemDecoration(getActivity(), DividerItemDecoration.VERTICAL_LIST)); mAdapter = new NewsAdapter(getActivity; //添加头尾布局// mAdapter.addHeaderView); mConvenientBanner.setPages(new CBViewHolderCreator<NetworkImageHolderView>() { @Override public NetworkImageHolderView createHolder() { return new NetworkImageHolderView(); } }, Arrays.asList .setPageIndicator(new int[]{R.mipmap.ic_page_indicator, R.mipmap.ic_page_indicator_focused}) .setPageIndicatorAlign(ConvenientBanner.PageIndicatorAlign.CENTER_HORIZONTAL); initAdapter(); initBanner(); initLine(); return view; } private void initLine() { mAppBarLayout.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() { @Override public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) { if(Math.abs(verticalOffset) >= mAppBarLayout.getTotalScrollRange{ mLine.setVisibility(View.VISIBLE); }else{ mLine.setVisibility(View.GONE); } } }); } private void initBanner() { mConvenientBanner.startTurning; // 进入Banner mConvenientBanner.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(int position) { DevUtil.showShortInfo(mActivity,"心理咨询师考试"); } }); } @Override public void onClick { switch ){ case R.id.ll_consult: DevUtil.gotoActivity(mActivity, Consult_Test_Activity.class); break; case R.id.ll_hunyin: DevUtil.gotoActivity(mActivity, Consult_Test_intros_Activity.class); break; case R.id.ll_yingyang: DevUtil.showShortInfo(mActivity,"题库整理中"); break; } } /** * 模拟首页数据 * @return */ private List<JsEntry> mockData(){ List<JsEntry> data = new ArrayList<>(); JsEntry jsEntry = new JsEntry(); jsEntry.time = "15小时前"; jsEntry.title = "这些情商的技巧,你是不是都掌握了?"; jsEntry.authorName = "JayChou"; jsEntry.cover ="http://upload-images.jianshu.io/upload_images/2785318-5306a632b46a8c27.jpg?imageMogr2/auto-orient/strip|imageView2/2/w/1020/q/80"; JsEntry jsEntry2 = new JsEntry(); jsEntry2.time = "10小时前"; jsEntry2.title = "除了阴谋,《锦绣未央》里还有哪些温情?"; jsEntry2.authorName = "菇凉似梦"; jsEntry2.cover = "http://upload-images.jianshu.io/upload_images/2881988-b217e714eb05f88e.jpg?imageMogr2/auto-orient/strip|imageView2/2/w/1020/q/80"; for (int i=0;i<20;i++){ if(i % 2 == 0){ data.add; }else{ data.add; } } return data; } /** * 设置RecyclerView属性 */ private void initAdapter() { mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity; mAdapter.openLoadAnimation(); mRecyclerView.setAdapter;//设置adapter //设置item点击事件 mAdapter.setOnRecyclerViewItemClickListener(new BaseQuickAdapter.OnRecyclerViewItemClickListener() { @Override public void onItemClick(View view, int position) { Toast.makeText(mActivity, ""+position, Toast.LENGTH_SHORT).show; } /** * RecycleView的adapter */ class NewsAdapter extends BaseQuickAdapter<JsEntry> { public NewsAdapter(Context context) { super(context,R.layout.news_label_item,mockData; } @Override public void convert(BaseViewHolder helper, JsEntry mData) { helper.setText(R.id.item_content, mData.title) .setText(R.id.author_name, mData.authorName) .setText(R.id.publish_time, mData.time); ImageLoader.getInstance().displayImage(mData.cover, (ImageView) helper.getView(R.id.cover)); } }}

从那之后安卓端这几个大约的效果与利益就完结了

思路:

  • 最尾部为UIScrollView,布局上种种加多banner,悬停的UIView布局和Tableview.
  • 经过代码推断UIScrollView的滚动达成悬停

中央代码:

- scrollViewDidScroll:(UIScrollView *)scrollView{ //悬浮框 if (_bottomScrollView.contentOffset.y < self.banner.bounds.size.height) { _bottomScrollView.delegate = nil; CGPoint contentOffsetPoint = _bottomScrollView.contentOffset; _bottomScrollView.contentOffset = contentOffsetPoint; _bottomScrollView.delegate = self; m_tabel.scrollEnabled =NO; //设置tableview 不能滚动 }else if(_bottomScrollView.contentOffset.y > self.banner.bounds.size.height){ m_tabel.scrollEnabled =YES; _bottomScrollView.delegate = nil; _bottomScrollView.contentOffset = CGPointMake(0, self.banner.bounds.size.height); _bottomScrollView.delegate = self; }}

4858.com 5常规-喜欢就点个赞呗
T.T .gif

2 Activity
    @BindView(R.id.coordinator)
    CoordinatorLayout coordinator;

    @BindView(R.id.nestedScrollView)
    NestedScrollView scrollView;

    @BindView(R.id.fabs)
    FloatingActionButton fab;

    @Override
    protected int setLayoutResourceID() {
        return R.layout.activity_hellow;
    }

    @Override
    protected void setUpView() {
       fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //点击出现底部菜单
                BottomSheetBehavior bottomSheetBehavior = BottomSheetBehavior.from(scrollView);
                bottomSheetBehavior.setState(bottomSheetBehavior.getState() == BottomSheetBehavior.STATE_COLLAPSED?BottomSheetBehavior.STATE_EXPANDED:BottomSheetBehavior.STATE_COLLAPSED);
            }
        });
    }
dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:22.2.0'
    compile 'com.android.support:design:22.2.0'
    compile 'com.android.support:recyclerview-v7:22.2.0'
    compile 'com.android.support:cardview-v7:22.2.0'
}

上边的注释写的也很驾驭,分别在底下的recyclerview有无数据时候动态调用这一个setCollapsingToolbarLayoutFlag方法来动态设置了。那标准难题不怕消除了。不过怎么无法居中只怕没太搞通晓,有通晓的相恋的人还请多多指教。别的做的时候还开采三个难题,正是AppBarLayout会出现阴影,那一个是android5.0过后material
design自带的,但是在有个别手机上不狼狈,大家就想要去掉,是要设置elevation属性,然则没有什么可争辨的是app:elevation不然会劳而无功哦,因为对于AppBarLayout这一个好不轻便自定义属性。
   好的,以上便是本次的全体内容,有标题应接谈论指正。

金玉满堂的关键点:

1 根布局为 CoordinatorLayout;
2
为尾巴部分弹出框设置app:layout_behavior=”@string/bottom_sheet_behavior”;
3 在代码中拿走BottomSheetBehavior(底部菜单),并动态更换它的景况;
4至于FloatingActionButton跟随弹出框移动,关键点在于为FloatingActionButton设置
5app:layout_4858.com,behavior=”@string/bottom_sheet_behavior”appbar_scrolling_view_behavior并非八个字符串,而是叁个类,何况以此类大家得以自定义。

com.android.support:design:22.2.0正是我们须要引进的Android Design
Support
Library,其次咱们还引进了Recyclerview和Cardview,还不打听那四个控件的同室能够看看Android5.x
RecyclerView
应用深入分析和Android5.x
CardView
应用剖判这两篇小说。

例子二:AppBarLayout

起来上代码,先来拜见布局(activity_tab_layout.xml),最外层大家用CoordinatorLayout
来是做完全的布局,AppBarLayout将Toolbar和TabLayout整合成了二个完完全全:

1 xml
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <android.support.design.widget.AppBarLayout
        android:id="@+id/main_appbarlayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <android.support.v7.widget.Toolbar
            android:id="@+id/main_toolbar"
            app:title="@string/app_name"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"/>
    </android.support.design.widget.AppBarLayout>

    <android.support.v4.widget.NestedScrollView 
        app:layout_behavior="@string/appbar_scrolling_view_behavior"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
         <!--中间可以随意写自己的布局-->
    </android.support.v4.widget.NestedScrollView>

</android.support.design.widget.CoordinatorLayout>
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/main_content"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true">

    <android.support.design.widget.AppBarLayout
        android:id="@+id/appbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"                                         android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            app:layout_scrollFlags="scroll|enterAlways"
            app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />

        <android.support.design.widget.TabLayout
            android:id="@+id/tabs"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:tabIndicatorColor="#ADBE107E"
            app:tabMode="scrollable" />
    </android.support.design.widget.AppBarLayout>

    <android.support.v4.view.ViewPager
        android:id="@+id/viewpager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior" />

    <android.support.design.widget.FloatingActionButton
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:clickable="true"
        android:onClick="checkin"
        android:src="@drawable/ic_discuss"
        app:layout_anchor="@id/main_content"
        app:layout_anchorGravity="bottom|right|end" />
</android.support.design.widget.CoordinatorLayout>
质量介绍
layout_scrollFlags

AppBarLayout中的子控件通过layout_scrollFlags这几个性情或许setScrollFlags工夫表现出他们的滚动行为。它的值有:scroll、snap、enterAlways、enterAlwaysCollapsed、exitUntilCollapsed。

scrol:全体想滚动的view都亟需设置这几个flag,
未有设置这些flag的view将被固化在显示器最上端。那个我们早就见识过了
snap:这么些平素翻译成“折断”。就是说被”关怀”的View假诺展现了概略上,就全显示出来,不但是藏身。

app:layout_scrollFlags="scroll|snap"

app:layout_scrollFlags=”scroll|snap”

enterAlways:往上海滑稽剧团动的时候被”关注”的这么些View隐蔽,往下滑的时候显得

app:layout_scrollFlags="scroll|enterAlways"

app:layout_scrollFlags=”scroll|enterAlways”

enterAlwaysCollapsed:向上海好笑剧团动的时候被”关注”的这几个View遮盖,向下滑动时先表现二个非常小中度,等到滑动到NestedScrollView最顶上部分的时候再完全表现出来。在意那边一定要有一个微细高度,即minHeight属性,何况enterAlwaysCollapsed绝对要搭配enterAlways和scroll工夫不奇怪表现

<android.support.v7.widget.Toolbar 
    android:id="@+id/main_toolbar"
    app:title="@string/app_name"
    app:layout_scrollFlags="scroll|enterAlways|enterAlwaysCollapsed"
    android:layout_width="match_parent"
    android:layout_height="200dip"
    android:minHeight="?attr/actionBarSize"/>

app:layout_scrollFlags=”scroll|enterAlways|enterAlwaysCollapsed”

能遮盖的重大是
app:layout_scrollFlags=”scroll|enterAlways”这些性情,设置滚动事件,属性之中必需至少启用scroll这些flag,这样这些view才会滚动出荧屏,不然它将一贯稳固在最上端。

要是您的AppBarLayout中带有别的的View,那么带有layout_scrollFlags的价签的View请布局在前头。因为AppBarLayout实际上是二个LinearLayout。

这里咱们用到了三个新的控件FloatingActionButton,它也是Design Support
Library提供的,你能够把它当作ImageView。它有三个属性需求专一下:

例子三:折叠的Toolbar

CollapsingToolbarLayout提供了一个足以折叠的Toolbar,它一而再FrameLayout。给它设置layout_scrollFlags,它能够决定包蕴在其间的子控件(如:ImageView、Toolbar)。

  • app:layout_anchor=””表示相对于哪个布局。
  • app:layout_anchorGravity=””表示相对于布局的地方。
1 xml
<android.support.design.widget.CoordinatorLayout 
    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">

    <android.support.design.widget.AppBarLayout
        android:id="@+id/main_appbarlayout"
        android:layout_width="match_parent"
        android:layout_height="200dip">

        <android.support.design.widget.CollapsingToolbarLayout 
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:expandedTitleMarginStart="64dp"
            app:expandedTitleMarginEnd="64dp"
            app:contentScrim="?attr/colorPrimaryDark"
            app:layout_scrollFlags="scroll|exitUntilCollapsed">
            <ImageView
                android:src="@mipmap/bg"
                app:layout_collapseParallaxMultiplier="0.5"
                app:layout_collapseMode="parallax"
                android:scaleType="centerCrop"
                android:layout_width="match_parent"
                android:layout_height="match_parent" />
            <android.support.v7.widget.Toolbar
                app:title="@string/app_name"
                app:layout_collapseMode="pin"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"/>
          </android.support.design.widget.CollapsingToolbarLayout>

    </android.support.design.widget.AppBarLayout>

    <android.support.v4.widget.NestedScrollView 
        app:layout_behavior="@string/appbar_scrolling_view_behavior"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <!-- 自己布局 -->
    </android.support.v4.widget.NestedScrollView>

</android.support.design.widget.CoordinatorLayout>

1018039-e7f47d571d8b5bfb.gif

连带属性

java代码(CoordinatorLayoutActivity .java)

layout_collapseMode

有2种模式,
pin模式:即一定格局,在折叠的时候最终稳固在下面
parallax模式:即视差格局,在折叠的时候会有个视差折叠的功能

package com.example.liuwangshu.mooncoordinatorlayout;
import android.support.design.widget.Snackbar;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.View;
import java.util.ArrayList;
import java.util.List;

public class CoordinatorLayoutActivity extends AppCompatActivity {
    private ViewPager mViewPager;
    private TabLayout mTabLayout;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_tab_layout);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        final ActionBar ab = getSupportActionBar();
        ab.setDisplayHomeAsUpEnabled(true);
        mViewPager = (ViewPager) findViewById(R.id.viewpager);
        initViewPager();
    }

    private void initViewPager() {

        mTabLayout = (TabLayout) findViewById(R.id.tabs);
        List<String> titles = new ArrayList<>();
        titles.add("精选");
        titles.add("体育");
        titles.add("巴萨");
        titles.add("购物");
        titles.add("明星");
        titles.add("视频");
        titles.add("健康");
        titles.add("励志");
        titles.add("图文");
        titles.add("本地");
        titles.add("动漫");
        titles.add("搞笑");
        titles.add("精选");
        for (int i = 0; i < titles.size(); i++) {
            mTabLayout.addTab(mTabLayout.newTab().setText(titles.get(i)));
        }
        List<Fragment> fragments = new ArrayList<>();
        for (int i = 0; i < titles.size(); i++) {
            fragments.add(new ListFragment());
        }
        FragmentAdapter mFragmentAdapteradapter =
                new FragmentAdapter(getSupportFragmentManager(), fragments, titles);
        //给ViewPager设置适配器
        mViewPager.setAdapter(mFragmentAdapteradapter);
        //将TabLayout和ViewPager关联起来。
        mTabLayout.setupWithViewPager(mViewPager);
        //给TabLayout设置适配器
        mTabLayout.setTabsFromPagerAdapter(mFragmentAdapteradapter);

    }
    public void checkin(View view) {
        Snackbar.make(view, "点击成功", Snackbar.LENGTH_SHORT).show();
    }
}
layout_collapseParallaxMultiplier

CollapsingToolbarLayout滑动时,子视图的视觉差。那些值的范围为0.0-1.0里面。为0的时候,你能够感到到到视图完全随NestedScrollView滚动;为1的时候,仿佛又是完全不滚动

咱俩点击FloatingActionButton时会触发checkin方法,并用Snackbar来弹出多少个唤起。Snackbar也是Design
Support Library的新控件,可以用来代表Toast和有个别的Dialog。

contentScrim

那是ToolBar被折叠到最上端一直后的背景。

4858.com 6

expandedTitleMarginStart/expandedTitleMarginEnd

在ToolBar被折叠前文字部分的左右距离

任何的代码请参见源码或许Android Design Support
Library(一)用TabLayout完成类似天涯论坛选项卡动态滑动作效果果那篇小说的执教,这里就不赘述了。

setExpandedTitleColor/setCollapsedTitleTextColor

安装还没收缩时场所下字体颜色与缩短后Toolbar上字体的颜色

2. CoordinatorLayout+CollapsingToolbarLayout贯彻Toolbar折叠效果
仍旧先来拜候效果(软件bug转成gif动画后效果十分的小好):

setTitle

应用CollapsingToolbarLayout时必须把title设置到CollapsingToolbarLayout上,设置到Toolbar上不会来得

4858.com 7

事例四:同步移动

先看效果

2800913-45ea0c7812fa7a12.gif

要贯彻折叠功用咱们须求引进三个新的布局CollapsingToolbarLayout,它功用是提供了八个方可折叠的Toolbar,它三番八次至FrameLayout,给它设置layout_scrollFlags,它能够决定包含在CollapsingToolbarLayout中的控件比如mageView、Toolbar在响应layout_behavior事件时作出相应的scrollFlags滚动事件。

DodoMoveView
**
 * @创建 HaiJia
 * @时间 2017/3/10 11:21
 * @描述 可拖动的View
 */

public class DodoMoveView extends TextView{

    private int lastX;
    private int lastY;


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

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        int x = (int) event.getRawX();
        int y = (int) event.getRawY();

        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                break;

            case MotionEvent.ACTION_MOVE:
                CoordinatorLayout.MarginLayoutParams layoutParams = 
                (CoordinatorLayout.MarginLayoutParams) getLayoutParams();
                int left = layoutParams.leftMargin + x - lastX;
                int top = layoutParams.topMargin + y - lastY;

                layoutParams.leftMargin = left;
                layoutParams.topMargin = top;
                setLayoutParams(layoutParams);
                requestLayout();
                break;

            case MotionEvent.ACTION_UP:
                break;
        }
        lastX = x;
        lastY = y;
        //如果返回值是true,代表事件在当前的viewGroup中会被处理,
        //向下传递之路被截断(所有子控件将没有机会参与Touch事件),
        // 同时把事件传递给当前的控件的onTouchEvent()处理。
        return true;
    }
}

下一场简短修改Behavior

public class DodoBehavior0s extends CoordinatorLayout.Behavior<Button>{

    private Context mContext;

    private int width;
    private int height;

    public DodoBehavior0s(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.mContext = context;
        DisplayMetrics display = context.getResources().getDisplayMetrics();
        width = display.widthPixels;
        height = display.heightPixels;
    }

    @Override
    public boolean layoutDependsOn(CoordinatorLayout parent, Button child, View dependency) {
        //如果dependency是TempView的实例,说明它就是我们所需要的Dependency
        return dependency instanceof DodoMoveView;
    }

    //每次dependency位置发生变化,都会执行onDependentViewChanged方法
    @Override
    public boolean onDependentViewChanged(CoordinatorLayout parent, Button btn, View dependency) {

        //根据dependency的位置,设置Button的位置

        int top = dependency.getTop();
        int left = dependency.getLeft();

        int x = width - left - btn.getWidth();
        int y = height - top - btn.getHeight();

        setPosition(btn, x, y);
        return true;
    }

    private void setPosition(View v, int x, int y) {
        CoordinatorLayout.MarginLayoutParams layoutParams = (CoordinatorLayout.MarginLayoutParams) v.getLayoutParams();
        layoutParams.leftMargin = x;
        layoutParams.topMargin = y;
        layoutParams.width = y/2;
        v.setLayoutParams(layoutParams);
    }
}

成效如下

2800913-9d0211e3e8802f09.gif

布局文件(activity_detail.xml)用CollapsingToolbarLayout将ImageView和Toolbar包蕴起来作为三个可折叠的Toolbar,再用AppBarLayout包裹起来作为叁个Appbar的完全,当然,AppBarLayout近些日子必需是率先个嵌套在CoordinatorLayout里面包车型大巴子view。

三、别的各样成效德姆o
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/main_content"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true">

    <android.support.design.widget.AppBarLayout
        android:id="@+id/appbar"
        android:layout_width="match_parent"
        android:layout_height="200dp"
        android:fitsSystemWindows="true"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

        <android.support.design.widget.CollapsingToolbarLayout
            android:id="@+id/collapsing_toolbar"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:fitsSystemWindows="true"
            app:contentScrim="?attr/colorPrimary"
            app:expandedTitleMarginEnd="64dp"
            app:expandedTitleMarginStart="48dp"
            app:layout_scrollFlags="scroll|exitUntilCollapsed">

            <ImageView
                android:id="@+id/backdrop"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:fitsSystemWindows="true"
                android:scaleType="centerCrop"
                android:src="@drawable/mao"
                />

            <android.support.v7.widget.Toolbar
                android:id="@+id/toolbar"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                app:layout_collapseMode="pin"
                app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />

        </android.support.design.widget.CollapsingToolbarLayout>

    </android.support.design.widget.AppBarLayout>

        <android.support.v7.widget.RecyclerView
            android:id="@+id/recyclerView"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:scrollbars="none"
            app:layout_behavior="@string/appbar_scrolling_view_behavior"/>
</android.support.design.widget.CoordinatorLayout>
1、BackBehavior

十分的快回到效果的Behavior,依据AppBarLayout的滚动来调节自定义View的轮转

1018039-5d44d427cea2929e.gif

CollapsingToolbarLayout有多少个基本点质量须求验证下:

2、项目可用的德姆o

CoordinatorLayoutSample
CoordinatorBehaviorExample

2267876-d4f42ee04a3d2760.gif

屈居关键源码

  • app:contentScrim=””,用来设置CollapsingToolbarLayout裁减后最顶上部分的水彩
  • app:expandedTitleGravity=”left|bottom”,表示将此CollapsingToolbarLayout完全张开后,title所处的岗位,暗中同意是left+
    bottom
  • app:collapsedTitleGravity=”left”,表示当尾部的衬图ImageView消失后,此title将回归到Toolbar的岗位,私下认可是left。
  • app:layout_scrollFlags=””,那本天性大家地点讲过用来安装滚动事件,属性之中必需至少启用scroll那一个flag,那样这几个view才会滚动出显示屏,不然它将直接稳固在最上端。这里大家设置的是app:layout_scrollFlags=”scroll|exitUntilCollapsed”那样能促成折叠功用,借使想要掩饰效果大家得以设置app:layout_scrollFlags=”scroll|enterAlways”。
xml
<android.support.design.widget.CoordinatorLayout
    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"
   >

    <android.support.design.widget.AppBarLayout
        android:id="@+id/app_bar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

        <android.support.design.widget.CollapsingToolbarLayout
            android:id="@+id/collapsing_tool_bar"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:contentScrim="@color/colorPrimary"
            app:expandedTitleGravity="bottom|center_horizontal"
            app:layout_scrollFlags="scroll|exitUntilCollapsed|snap">

            <ImageView
                android:id="@+id/iv_head"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:scaleType="fitXY"
                android:src="@mipmap/dd"
                app:layout_collapseMode="parallax"
                app:layout_collapseParallaxMultiplier="0.6"/>

            <!-- 设置app:navigationIcon="@android:color/transparent"给头像预留位置 -->
            <android.support.v7.widget.Toolbar
                android:id="@+id/tool_bar"
                android:layout_width="match_parent"
                android:layout_height="50dp"
                app:layout_collapseMode="pin"
                app:navigationIcon="@android:color/transparent"
                app:theme="@style/ThemeOverlay.AppCompat.Dark"
                app:title="Tom Hardy"/>
        </android.support.design.widget.CollapsingToolbarLayout>
    </android.support.design.widget.AppBarLayout>

    <android.support.v4.widget.NestedScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior">

        <include layout="@layout/layout_content_tom"/>
    </android.support.v4.widget.NestedScrollView>

    <!-- layout_anchor属性5.0以上需要设置为CollapsingToolbarLayout,不然头像最后会被覆盖 -->
    <de.hdodenhof.circleimageview.CircleImageView
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:layout_margin="16dp"
        android:src="@mipmap/tom"
        app:border_color="@android:color/white"
        app:border_width="1dp"
        app:layout_anchor="@id/collapsing_tool_bar"
        app:layout_anchorGravity="bottom|right"
        app:layout_behavior="com.haijia.demo.behavior.AvatarBehavior"/>
</android.support.design.widget.CoordinatorLayout>

笔者们要求定义AppBarLayout与滚动视图之间的维系,Design Support
Library包蕴了二个卓殊的字符串能源@string/appbar_scrolling_view_behavior,它和AppBarLayout.ScrollingViewBehavior相相配,用来打招呼AppBarLayout哪一天发生了滚动事件,这些behavior须要安装在触及事件的view之上,所以大家应当在RecyclerView恐怕放肆帮忙嵌套滚动的view比方NestedScrollView上增加app:layout_behavior=”@string/appbar_scrolling_view_behavior这几个特性,当然AppBarLayout
中的子view供给设置app:layout_scrollFlags这么些性子,不然接收到RecyclerView滚动事件,AppBarLayout
也不会有啥样变动。

layout_content_tom.xml
<?xml version="1.0" encoding="utf-8"?>

<android.support.v7.widget.CardView
    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="wrap_content"
    android:layout_marginTop="5dp"
    app:cardCornerRadius="5dp"
    app:cardElevation="8dp"
    app:cardPreventCornerOverlap="false"
    app:cardUseCompatPadding="true">

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

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="10dp"
            android:layout_marginRight="10dp"
            android:layout_marginTop="10dp"
            android:orientation="horizontal">

            <TextView
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:text="Date of Birth"
                android:textAppearance="@style/TextAppearance.AppCompat.Body2"/>

            <TextView
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="3"
                android:text="15 September 1977, Hammersmith, London, England, UK"/>
        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="10dp"
            android:layout_marginRight="10dp"
            android:layout_marginTop="10dp"
            android:orientation="horizontal">

            <TextView
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:text="Birth Name"
                android:textAppearance="@style/TextAppearance.AppCompat.Body2"/>

            <TextView
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="3"
                android:text="Edward Thomas Hardy"/>
        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginBottom="10dp"
            android:layout_marginLeft="10dp"
            android:layout_marginRight="10dp"
            android:layout_marginTop="10dp"
            android:orientation="horizontal">

            <TextView
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:text="Height"
                android:textAppearance="@style/TextAppearance.AppCompat.Body2"/>

            <TextView
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="3"
                android:text="(1.75 m)"/>
        </LinearLayout>

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="10dp"
            android:text="黄海佳"/>
    </LinearLayout>
</android.support.v7.widget.CardView>

最终看看java代码(CollapsingToolbarActivity.java)

AvatarBehavior
public class AvatarBehavior extends CoordinatorLayout.Behavior<CircleImageView> {

    // 缩放动画变化的支点
    private static final float ANIM_CHANGE_POINT = 0.2f;

    private Context mContext;
    // 整个滚动的范围
    private int mTotalScrollRange;
    // AppBarLayout高度
    private int mAppBarHeight;
    // AppBarLayout宽度
    private int mAppBarWidth;
    // 控件原始大小
    private int mOriginalSize;
    // 控件最终大小
    private int mFinalSize;
    // 控件最终缩放的尺寸,设置坐标值需要算上该值
    private float mScaleSize;
    // 原始x坐标
    private float mOriginalX;
    // 最终x坐标
    private float mFinalX;
    // 起始y坐标
    private float mOriginalY;
    // 最终y坐标
    private float mFinalY;
    // ToolBar高度
    private int mToolBarHeight;
    // AppBar的起始Y坐标
    private float mAppBarStartY;
    // 滚动执行百分比[0~1]
    private float mPercent;
    // Y轴移动插值器
    private DecelerateInterpolator mMoveYInterpolator;
    // X轴移动插值器
    private AccelerateInterpolator mMoveXInterpolator;
    // 最终变换的视图,因为在5.0以上AppBarLayout在收缩到最终状态会覆盖变换后的视图,所以添加一个最终显示的图片
    private CircleImageView mFinalView;
    // 最终变换的视图离底部的大小
    private int mFinalViewMarginBottom;


    public AvatarBehavior(Context context, AttributeSet attrs) {
        super(context, attrs);
        mContext = context;
        mMoveYInterpolator = new DecelerateInterpolator();
        mMoveXInterpolator = new AccelerateInterpolator();
        if (attrs != null) {
            TypedArray a = mContext.obtainStyledAttributes(attrs, R.styleable.AvatarImageBehavior);
            mFinalSize = (int) a.getDimension(R.styleable.AvatarImageBehavior_finalSize, 0);
            mFinalX = a.getDimension(R.styleable.AvatarImageBehavior_finalX, 0);
            mToolBarHeight = (int) a.getDimension(R.styleable.AvatarImageBehavior_toolBarHeight, 0);
            a.recycle();
        }
    }

    @Override
    public boolean layoutDependsOn(CoordinatorLayout parent, CircleImageView child, View dependency) {
        return dependency instanceof AppBarLayout;
    }

    @Override
    public boolean onDependentViewChanged(CoordinatorLayout parent, CircleImageView child, View dependency) {

        if (dependency instanceof AppBarLayout) {
            _initVariables(child, dependency);

            mPercent = (mAppBarStartY - dependency.getY()) * 1.0f / mTotalScrollRange;

            float percentY = mMoveYInterpolator.getInterpolation(mPercent);
            AnimHelper.setViewY(child, mOriginalY, mFinalY - mScaleSize, percentY);

            if (mPercent > ANIM_CHANGE_POINT) {
                float scalePercent = (mPercent - ANIM_CHANGE_POINT) / (1 - ANIM_CHANGE_POINT);
                float percentX = mMoveXInterpolator.getInterpolation(scalePercent);
                AnimHelper.scaleView(child, mOriginalSize, mFinalSize, scalePercent);
                AnimHelper.setViewX(child, mOriginalX, mFinalX - mScaleSize, percentX);
            } else {
                AnimHelper.scaleView(child, mOriginalSize, mFinalSize, 0);
                AnimHelper.setViewX(child, mOriginalX, mFinalX - mScaleSize, 0);
            }
            if (mFinalView != null) {
                if (percentY == 1.0f) {
                    // 滚动到顶时才显示
                    mFinalView.setVisibility(View.VISIBLE);
                } else {
                    mFinalView.setVisibility(View.GONE);
                }
            }
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && dependency instanceof CollapsingToolbarLayout) {
            // 大于5.0才生成新的最终的头像,因为5.0以上AppBarLayout会覆盖变换后的头像
            if (mFinalView == null && mFinalSize != 0 && mFinalX != 0 && mFinalViewMarginBottom != 0) {
                mFinalView = new CircleImageView(mContext);
                mFinalView.setVisibility(View.GONE);
                // 添加为CollapsingToolbarLayout子视图
                ((CollapsingToolbarLayout) dependency).addView(mFinalView);
                FrameLayout.LayoutParams params = (FrameLayout.LayoutParams) mFinalView.getLayoutParams();
                // 设置大小
                params.width = mFinalSize;
                params.height = mFinalSize;
                // 设置位置,最后显示时相当于变换后的头像位置
                params.gravity = Gravity.BOTTOM;
                params.leftMargin = (int) mFinalX;
                params.bottomMargin = mFinalViewMarginBottom;
                mFinalView.setLayoutParams(params);
                mFinalView.setImageDrawable(child.getDrawable());
                mFinalView.setBorderColor(child.getBorderColor());
                int borderWidth = (int) ((mFinalSize * 1.0f / mOriginalSize) * child.getBorderWidth());
                mFinalView.setBorderWidth(borderWidth);
            }
        }

        return true;
    }

    /**
     * 初始化变量
     * @param child
     * @param dependency
     */
    private void _initVariables(CircleImageView child, View dependency) {
        if (mAppBarHeight == 0) {
            mAppBarHeight = dependency.getHeight();
            mAppBarStartY = dependency.getY();
        }
        if (mTotalScrollRange == 0) {
            mTotalScrollRange = ((AppBarLayout) dependency).getTotalScrollRange();
        }
        if (mOriginalSize == 0) {
            mOriginalSize = child.getWidth();
        }
        if (mFinalSize == 0) {
            mFinalSize = mContext.getResources().getDimensionPixelSize(R.dimen.avatar_final_size);
        }
        if (mAppBarWidth == 0) {
            mAppBarWidth = dependency.getWidth();
        }
        if (mOriginalX == 0) {
            mOriginalX = child.getX();
        }
        if (mFinalX == 0) {
            mFinalX = mContext.getResources().getDimensionPixelSize(R.dimen.avatar_final_x);
        }
        if (mOriginalY == 0) {
            mOriginalY = child.getY();
        }
        if (mFinalY == 0) {
            if (mToolBarHeight == 0) {
                mToolBarHeight = mContext.getResources().getDimensionPixelSize(R.dimen.toolbar_height);
            }
            mFinalY = (mToolBarHeight - mFinalSize) / 2 + mAppBarStartY;
        }
        if (mScaleSize == 0) {
            mScaleSize = (mOriginalSize - mFinalSize) * 1.0f / 2;
        }
        if (mFinalViewMarginBottom == 0) {
            mFinalViewMarginBottom = (mToolBarHeight - mFinalSize) / 2;
        }
    }
}
package com.example.liuwangshu.mooncoordinatorlayout;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.support.v7.widget.Toolbar;
public class CollapsingToolbarActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_detail);
        Toolbar toolbar = (Toolbar) this.findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        CollapsingToolbarLayout collapsingToolbar =
                (CollapsingToolbarLayout) findViewById(R.id.collapsing_toolbar);
        collapsingToolbar.setTitle("哆啦A梦");
        RecyclerView mRecyclerView= (RecyclerView) findViewById(R.id.recyclerView);
        mRecyclerView.setLayoutManager(new StaggeredGridLayoutManager(1, StaggeredGridLayoutManager.VERTICAL));
        mRecyclerView.setItemAnimator(new DefaultItemAnimator());
        mRecyclerView.setAdapter(new RecyclerViewAdapter(CollapsingToolbarActivity.this));
    }
}

github源码下载

发表评论

电子邮件地址不会被公开。 必填项已用*标注

网站地图xml地图
Copyright @ 2010-2019 美高梅手机版4858 版权所有