今天整理我之前写的代码,发现之前监听CollapsingToolbarLayout的状态的时候是通过监听包裹CollapsingToolbarLayout着的AppBarLayout的OnOffsetChangedListener的方法来实现的。当时也是借鉴其他程序员的方法实现的,现在也不知道是哪个网址,没办法贴出来。下面是我实现的方法:
public abstract class AppBarLayoutStateChangeListener implements AppBarLayout.OnOffsetChangedListener{ enum State{ EXPANDED,//展开 COLLAPSED,//折叠 INTERMEDIATE//中间状态 } private State mCurrentState = State.INTERMEDIATE; @Override public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) { if (verticalOffset == 0) { if (mCurrentState != State.EXPANDED) { onStateChanged(appBarLayout, State.EXPANDED); } mCurrentState = State.EXPANDED; } else if (Math.abs(verticalOffset) >= appBarLayout.getTotalScrollRange()) { if (mCurrentState != State.COLLAPSED) { onStateChanged(appBarLayout, State.COLLAPSED); } mCurrentState = State.COLLAPSED; } else { if (mCurrentState != State.INTERMEDIATE) { onStateChanged(appBarLayout, State.INTERMEDIATE); } mCurrentState = State.INTERMEDIATE; } } public abstract void onStateChanged(AppBarLayout appBarLayout, State state); }
然后只要在代码中监听即可
abl.addOnOffsetChangedListener(new AppBarLayoutStateChangeListener() { @Override public void onStateChanged(AppBarLayout appBarLayout, State state) { switch (state){ case EXPANDED: Log.v("CoordinatorLayout","EXPANDED"); break; case COLLAPSED: Log.v("CoordinatorLayout","COLLAPSED"); toolbar.setVisibility(View.VISIBLE); break; case INTERMEDIATE: Log.v("CoordinatorLayout","INTERMEDIATE"); toolbar.setVisibility(View.INVISIBLE); break; } } });
我的使用场景是做图片折叠然后状态栏的隐藏,背景展开状态栏显示,并且不在图片中显示title,我们在使用CollapsingToolbarLayout的使用的时候有一个属性app:titleEnabled="false"设置为false的时候就不会在图片上显示title,然后我通过上面监听的方法AppBarLayout来控制toolbar的隐藏显示,以下是我的部分布局代码
<android.support.design.widget.AppBarLayout android:id="@+id/abl" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical"> <android.support.design.widget.CollapsingToolbarLayout android:id="@+id/ctl" android:layout_width="match_parent" android:layout_height="wrap_content" app:layout_scrollFlags="scroll|exitUntilCollapsed" app:expandedTitleMarginStart="48dp" app:expandedTitleMarginEnd="64dp" app:titleEnabled="false" app:statusBarScrim="@color/colorPrimaryDark" app:contentScrim="@color/colorPrimaryDark"> <ImageView android:layout_width="match_parent" android:layout_height="180dp" android:src="@drawable/pic_1" android:scaleType="centerCrop" app:layout_collapseMode="parallax"/> <android.support.v7.widget.Toolbar android:id="@+id/toolbar_four" android:visibility="invisible" android:layout_width="match_parent" android:layout_height="?attr/actionBarSize" app:layout_scrollFlags="scroll|enterAlways" app:layout_collapseMode="pin"> </android.support.v7.widget.Toolbar> </android.support.design.widget.CollapsingToolbarLayout> </android.support.design.widget.AppBarLayout>