折叠伸缩工具栏 CollapsingToolbarLayout


PS:这是一个超级超级垃圾的控件,强烈建议放弃使用!

一个类似的效果的库,有800个星星: https://github.com/yanzhenjie/Sofia
Android沉浸式效果的实现,状态栏和导航栏均支持设置颜色、渐变色、图片、透明度、内容入侵和状态栏深色字体;兼容竖屏、横屏,当屏幕旋转时会自动适配。

简介

在AndroidStudio中新建一个Activity时选择ScrollingActivity 模板 ,它实现的就是简单的 折叠式 工具栏 效果 :Toolbar是透明的,有一个背景图片以及大标题,随着页面向上滑动,其标题逐渐缩放到Toolbar上,而背景图片则在滑动到一定程度后变成了Toolbar的颜色。 其实这种效果在GitHub上面已经有很多开源库实现了,但是Google在其推出的Design Library库中也给出了一个这种控件,让我们很方便地实现了这种效果。这个控件就是CollapsingToolbarLayout,它是一个增强型的FrameLayout。

常用xml属性介绍


一般属性

  • contentScrim:当Toolbar折叠到一定程度时的背景颜色
  • title:当titleEnable设置为true的时候(默认),显示的可缩放的标题
  • scrimAnimationDuration:控制Toolbar收缩时,颜色变化持续时间
  • app:collapsedTitleGravity="left"  Specifies how the title should be positioned when collapsed.  指定在折叠之后标题放置的位置 
  • app:collapsedTitleTextAppearance="@color/colorPrimary"  The text appearance of the CollapsingToolbarLayouts title when it is fully 'collapsed'。Must be a reference to another resource, in the form "@[+][package:]type:name" or to a theme attribute in the form "?[package:][type:]name". 在折叠的时候标题文字的外观。必须引用另一个资源 
  • app:contentScrim="#ff5252" The drawable to use as a scrim on top of the CollapsingToolbarLayouts content when it has been scrolled sufficiently off screen. 指定在折叠之后的背景色
  • app:expandedTitleGravity="left|bottom" Specifies how the title should be positioned when expanded. 在展开的时候 标题放置的位置
  • app:expandedTitleMargin="16dp" Specifies extra space on the start, top, end and bottom sides of the the expanded title text. 设置边界距离,还可以单独设置Bottom、Top、Left、Right等
  • app:expandedTitleTextAppearance 在展开的时候标题文字的外观
  • app:scrimAnimationDuration="200"  Specifies the duration used for scrim visibility animations. 控制Toolbar收缩时,颜色变化持续时间
  • app:scrimVisibleHeightTrigger="150dp"  Specifies the amount of visible height in pixels used to define when to trigger a scrim visibility change.当可视高度变为多少时(折叠或展开时)触发背景颜色改变
  • app:statusBarScrim="#123456" The drawable to use as a scrim for the status bar content when the CollapsingToolbarLayout has been scrolled sufficiently off screen. 在折叠的时候 状态栏 的背景颜色(一般不需要设置)
  • app:title="Title" The title to show when titleEnabled is set to true. 如果标题可用的话 显示的标题文字   
  • app:titleEnabled="true" Whether the CollapsingToolbarLayout should draw its own shrinking/growing title. 是否显示标题
  • app:toolbarId="@id/toolbar" The id of the primary Toolbar child that you wish to use for the purpose of collapsing.在折叠的时候 显示的toolbar的id

layout_scrollFlags属性

一般开发中,CollapsingToolbarLayout不会单独出现在布局文件中,而是作为另一个控件CoordinatorLayout的子元素出现,CoordinatorLayout这个控件很强大,能对其子元素实现多种不同的功能,一个常见的用法就是:给它的一个子元素A设置一个 layout_scrollFlags的属性,然后给另外一个子元素B设置一个 layout_behavior=”@string/appbar_scrolling_view_behavior”的属性,这个子元素B一般是一个可以滑动的控件,比如RecyclerView、NestedScrollView、FloatingActionButton(默认自带一个layout_behavior属性)等,那么当子元素B滑动的时候,子元素A就会根据其layout_scrollFlags的属性值而做出不同的改变,所以我们要为CollapsingToolbarLayout设置layout_scrollFlags属性。

app:layout_scrollFlags="scroll|exitUntilCollapsed"  
  • scroll - 是否可以滚动。所有想要滑动的控件都要设置这个标志位,如果不设置这个标志位,那么View会固定不动
  • enterAlways - 实现quick return效果,设置了该标志位后,若View已经滑出屏幕,此时手指向下滑,View会立刻出现(比如Toolbar)
  • exitUntilCollapsed - 向上滚动时收缩View,但view可以被固定在顶部(比如Toolbar)
  • enterAlwaysCollapsed - 设置了minHeight时又设置了该标志位的话,你的View只能以最小高度进入,只有当滚动视图到达顶部时才扩大到完整高度。

layout_collapseMode属性

上面提到CollapsingToolbarLayout是一个FrameLayout,它内部能有多个子元素,而子元素也会有不同的表现。比如说,toolbar在缩放后是固定在顶部的,而imageview则是随着布局的滚动而滚动,也即存在一个相对滚动的过程。所以这些子元素可以添加layout_collapseMode标志位进而产生不同的行为。

layout_collapseMode只有两种标志位,分别是: 
  • pin:有该标志位的View在页面滚动的过程中会一直停留在顶部(只有layout_scrollFlags添加exitUntilCollapsed才有效)
  • parallax:有该标志位的View表示能和页面同时滚动。
    与该标志位相关联的一个属性是:
    视差因子layout_collapseParallaxMultiplier,表示该View与页面的滚动速度存在的差值,造成一种相对滚动的效果。

注意事项

  • 1、Android Design Support Library的使用需要配合特定的主题,一般用AppCompat下的主题即可,也可以自定义主题,继承自AppCompat的主题,否则会报错。另外如果使用Android Studio的话,主题的相关代码需要在styles.xml(v21)文件内做出相应的修改,否则使用Android 5.0以上的机子做测试的话也会报错。 
  • 2、由于使用了AppCompat的主题,那么我们的Activity应该继承自AppCompatActivity。 
  • 3、笔者之前使用design support library的版本号是23.1.0,在此版本上,CollapsingToolbarLayout没有设置collapsedTitleTextAppearance属性,标题可以正常显示,然而到了24.1.0版本,如果没有设置collapsedTitleTextAppearance属性,则当toolbar收缩后,其标题文字变得非常小。所以我们要设置collapsedTitleTextAppearance=”@style/TextAppearance.AppCompat.Title”这个属性,才能变得正常。 
  • 4、如果没有为CollapsingToolbarLayout设置一个title,那么会使用ActionBar自带的标题来显示应用的名称,这是因为调用了setSupportActionBar(toolbar)函数。

样板代码一

添加依赖
compile 'com.android.support:design:25.3.1'
清单文件中设置
<activity
    android:name=".ScrollingActivity"
    android:theme="@style/AppTheme.NoActionBar" />
values中新增的主题
<resources>
    <style name="AppTheme.NoActionBar">
        <item name="windowActionBar">false</item>
        <item name="windowNoTitle">true</item>
    </style>
    <style name="AppTheme.AppBarOverlay" parent="ThemeOverlay.AppCompat.Dark.ActionBar"/>
    <style name="AppTheme.PopupOverlay" parent="ThemeOverlay.AppCompat.Light"/>
</resources>
values-v21 中新增的 主题
<resources>
    <style name="AppTheme.NoActionBar">
        <item name="windowActionBar">false</item>
        <item name="windowNoTitle">true</item>
        <item name="android:windowDrawsSystemBarBackgrounds">true</item>
        <item name="android:statusBarColor">@android:color/transparent</item>
    </style>
</resources>
折叠式工具栏布局
<?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:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true">

    <!--AppBarLayout继承自LinearLayout,其作用就是把其所有子元素当做一个AppBar来使用-->
    <android.support.design.widget.AppBarLayout
        android:id="@+id/app_bar"
        android:layout_width="match_parent"
        android:layout_height="220dp"
        android:fitsSystemWindows="true"
        android:theme="@style/AppTheme.AppBarOverlay">
        <!--contentScrim:当Toolbar折叠后的背景颜色,展开时的背景仍旧使用background属性 -->
        <!--title:当titleEnable设置为true的时候(默认)显示的可以缩放的标题,不要在Toolbar中设置标题-->
        <!--layout_scrollFlags属性,scroll:是否可以滑动(必须设置),exitUntilCollapsed:向上滚动时固定Toolbar-->
        <!--collapsed/expanded_TitleTextAppearance:折叠/展开之后标题的样式,必须引用另一个资源-->
        <!--collapsed/expanded_TitleGravity:折叠/展开之后标题放置的位置,折叠时这里有严重的bug-->
        <!--scrimAnimationDuration:控制Toolbar收缩时,颜色变化持续时间-->
        <android.support.design.widget.CollapsingToolbarLayout
            android:id="@+id/toolbar_layout"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="@drawable/bg"
            android:fitsSystemWindows="true"
            app:collapsedTitleGravity="center"
            app:collapsedTitleTextAppearance="@style/CollapsedTextStyle"
            app:contentScrim="@android:color/holo_orange_dark"
            app:expandedTitleGravity="center|bottom"
            app:expandedTitleMargin="10dp"
            app:expandedTitleTextAppearance="@style/ExpandedTextStyle"
            app:layout_scrollFlags="scroll|exitUntilCollapsed"
            app:scrimAnimationDuration="1500"
            app:title="可缩放的标题">
            <!--pin:有该标志位的View在页面滚动的过程中会一直停留在顶部,只有layout_scrollFlags添加exitUntilCollapsed才有效 -->
            <android.support.v7.widget.Toolbar
                android:id="@+id/toolbar"
                android:layout_width="match_parent"
                android:layout_height="40dp"
                app:layout_collapseMode="pin"
                app:popupTheme="@style/AppTheme.PopupOverlay"/>

            <ImageView
                android:layout_width="40dp"
                android:layout_height="40dp"
                android:layout_gravity="center"
                android:src="@drawable/icon"
                app:layout_collapseMode="pin"/>

            <!--parallax:有该标志位的View表示能和页面同时滚动(默认值),layout_collapseParallaxMultiplier为视差因子 -->
            <TextView
                android:layout_width="match_parent"
                android:layout_height="20dp"
                android:background="@android:color/holo_purple"
                android:gravity="center"
                android:text="和页面同时滚动"
                app:layout_collapseMode="parallax"
                app:layout_collapseParallaxMultiplier="0.6"/>
        </android.support.design.widget.CollapsingToolbarLayout>
    </android.support.design.widget.AppBarLayout>

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

</android.support.design.widget.CoordinatorLayout>
内容布局
<?xml version="1.0" encoding="utf-8"?>
<!--内容区域,NestedScrollView和scrollview基本一样,但是它支持嵌套滚动-->
<android.support.v4.widget.NestedScrollView
    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"
    app:layout_behavior="@string/appbar_scrolling_view_behavior">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="16dp"
        android:text="具有丰富项目经验,良好的编程习惯以及较强的学习、适应能力。"/>

</android.support.v4.widget.NestedScrollView>
文字样式
<style name="CollapsedTextStyle">
	<item name="android:textSize">20sp</item>
	<item name="android:textColor">#00f</item>
</style>

<style name="ExpandedTextStyle">
	<item name="android:textSize">35sp</item>
	<item name="android:textColor">#ff0</item>
</style>

改造

Activity布局
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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:background="@null"
                android:fitsSystemWindows="true">

    <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:background="@null">
        <!--设置高度-->
        <android.support.design.widget.AppBarLayout
            android:id="@+id/app_bar"
            android:layout_width="match_parent"
            android:layout_height="300dp"
            app:elevation="0dp">

            <!--contentScrim:当Toolbar折叠后的背景颜色,展开时的背景使用background属性 -->
            <!--layout_scrollFlags属性,scroll:是否可以滑动(必须设置),exitUntilCollapsed:向上滚动时固定Toolbar-->
            <!--scrimAnimationDuration:控制Toolbar收缩时,颜色变化持续时间-->
            <android.support.design.widget.CollapsingToolbarLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:background="@null"
                app:contentScrim="#f0f"
                app:layout_scrollFlags="scroll|exitUntilCollapsed"
                app:scrimAnimationDuration="500">

                <!--  ==============滑动后折叠的部分,parallax==============  -->
                <include layout="@layout/content_before"/>

                <!--pin:有该标志位的View在页面滚动的过程中会一直停留在当前位置,
                直到接近CollapsingToolbarLayout的边界时才和其一起滚动。这里是将Toolbar钉在了顶部。
                只有CollapsingToolbarLayout的layout_scrollFlags属性添加exitUntilCollapsed时才有效 -->
                <!--设置 android:layout_marginLeft="-17dp"可解决不左对齐的bug-->
                <!--标题栏-->
                <android.support.v7.widget.Toolbar
                    android:id="@+id/top_toolbar"
                    android:layout_width="match_parent"
                    android:layout_height="56dp"
                    android:layout_marginLeft="-16dp"
                    android:background="@null"
                    app:layout_collapseMode="pin">

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

                        <TextView
                            android:id="@+id/toolbar_tv_title"
                            android:layout_width="match_parent"
                            android:layout_height="40dp"
                            android:gravity="center_vertical"
                            android:text="标题"/>
                    </RelativeLayout>

                </android.support.v7.widget.Toolbar>
            </android.support.design.widget.CollapsingToolbarLayout>
        </android.support.design.widget.AppBarLayout>

        <!--  ==============滑动后展开的部分==============  -->
        <include layout="@layout/content_aftet"/>

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

    <!--加载中-->
    <RelativeLayout
        android:id="@+id/rl_load_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="#fff"
        android:visibility="gone">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:gravity="center"
            android:text="加载中…"/>

    </RelativeLayout>
</RelativeLayout>
滑动后折叠的部分,content_before
<?xml version="1.0" encoding="utf-8"?>
<!--parallax:有该标志位的View表示能和页面同时滚动(默认值)-->
<!-- 视差因子layout_collapseParallaxMultiplier设为0具有同步滚动效果 -->
<!-- 视差因子layout_collapseParallaxMultiplier设为1具有覆盖效果 -->
<RelativeLayout
    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:background="@null"
    app:layout_collapseMode="parallax"
    app:layout_collapseParallaxMultiplier="1">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="500dp"
        android:background="@android:color/holo_green_light"
        android:gravity="center"
        android:text="滑动后折叠的部分"/>

</RelativeLayout>
滑动后展开的部分,content_aftet
<?xml version="1.0" encoding="utf-8"?>
<!--系统提供两种layout_behavior,appbar_scrolling_view_behavior和bottom_sheet_behavior-->
<RelativeLayout
    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"
    app:layout_behavior="@string/appbar_scrolling_view_behavior">
    <!--最底部的浮窗-->
    <TextView
        android:id="@+id/tv_bottom"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:layout_alignParentBottom="true"
        android:background="@color/colorPrimary"
        android:gravity="center"
        android:text="滑动后展开的部分2"/>

    <!--用一个ScrollView包住需要滚动的区域,NestedScrollView和支持嵌套滚动-->
    <android.support.v4.widget.NestedScrollView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_above="@+id/tv_bottom">

        <!--ScrollView只能有一个子View-->
        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">
            <!--内容区域-->
            <TextView
                android:layout_width="match_parent"
                android:layout_height="800dp"
                android:background="@android:color/holo_blue_bright"
                android:gravity="center"
                android:text="滑动后展开的部分1"/>

        </RelativeLayout>

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

</RelativeLayout>
代码
public class MainActivity extends AppCompatActivity implements ViewTreeObserver.OnGlobalLayoutListener, AppBarLayout.OnOffsetChangedListener {
	private TextView title;
	private AppBarLayout appBar;
	private Toolbar toolBar;//android.support.v7.widget.Toolbar
	
	private int pxWhenExpanded;
	private int maxVerticalOffset;
	
	private boolean isAutoScrolling = false;//是否正在自动滚动
	private int scrollTo = SCROLL_TO_BOTTOM;//滚动方向
	private static final int SCROLL_TO_BOTTOM = 1;//滑动到底部,最初的动作
	private static final int SCROLL_TO_TOP = 2;//滑动到顶部,回看的动作
	
	InputManager im;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_cl);
		
		initview();
		initData();
	}
	
	public void initview() {
		title = findViewById(R.id.tv_title);
		appBar = findViewById(R.id.app_bar);
		toolBar = findViewById(R.id.toolbar);
		appBar.getViewTreeObserver().addOnGlobalLayoutListener(this);
		appBar.addOnOffsetChangedListener(this);
		title.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				appBar.setExpanded(new Random().nextBoolean(), true);
			}
		});
	}
	
	private void initData() {
		setSupportActionBar(toolBar);
		title.setText("标题是会变的");
		pxWhenExpanded = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 100, getResources().getDisplayMetrics());
	}
	
	@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
	@Override
	public void onGlobalLayout() {
		appBar.getViewTreeObserver().removeOnGlobalLayoutListener(this);
		maxVerticalOffset = appBar.getHeight() - toolBar.getHeight() - getStatusBarHeight();
		Log.i("bqt", "appBar=" + appBar.getHeight() + ", toolBar=" + toolBar.getHeight() + ", 状态栏=" + getStatusBarHeight());
		Log.i("bqt", "maxVerticalOffset=" + maxVerticalOffset);
	}
	
	@Override
	public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
		//verticalOffset是appBar【当前】高度与【最初】高度的差。最初值是0,向上滑到顶的话值是【-maxVerticalOffset】
		Log.i("bqt", "verticalOffset=" + verticalOffset + ", scrollTo=" + scrollTo + ", isAutoScrolling=" + isAutoScrolling);
		if (isAutoScrolling) {
			if (verticalOffset == 0) {
				Log.i("bqt", "【展开了】");
				title.setText("展开了");
				isAutoScrolling = false;
				scrollTo = SCROLL_TO_BOTTOM;
			} else if (Math.abs(verticalOffset) == maxVerticalOffset) {
				Log.i("bqt", "【折叠了】");
				title.setText("折叠了");
				isAutoScrolling = false;
				scrollTo = SCROLL_TO_TOP;
			}
		} else {//这一块有bug,不知为什么会往返跳动
			if (scrollTo == SCROLL_TO_BOTTOM && Math.abs(verticalOffset) >= pxWhenExpanded) {
				Log.i("bqt", "【开始自动折叠】");
				appBar.setExpanded(false, true);
				isAutoScrolling = true;
			} else if (scrollTo == SCROLL_TO_TOP && Math.abs(verticalOffset) <= maxVerticalOffset - pxWhenExpanded) {
				Log.i("bqt", "【开始自动展开】");
				appBar.setExpanded(true, true);
				isAutoScrolling = true;
			}
		}
	}
	
	/**
	 * 状态栏高度,单位px,一般为25dp
	 */
	private int getStatusBarHeight() {
		int height = 0;
		int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
		if (resourceId > 0) {
			height = getResources().getDimensionPixelSize(resourceId);
		}
		return height;
	}
	
}
2018-1-9





免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM