折疊伸縮工具欄 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