Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
An extension of Android AppBarLayout, that allows to programatically change the CollapsibleToolbarLayout state and receive state changes (collapsed, expanded and idle)
package com.eatfirst.android.ui.custom;
/**
* Copyright 2015 Bartosz Lipinski
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import android.content.Context;
import android.graphics.Canvas;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.CoordinatorLayout;
import android.util.AttributeSet;
import java.lang.ref.WeakReference;
public class ControllableAppBarLayout extends AppBarLayout
implements AppBarLayout.OnOffsetChangedListener {
private AppBarLayout.Behavior mBehavior;
private WeakReference<CoordinatorLayout> mParent;
private ToolbarChange mQueuedChange = ToolbarChange.NONE;
private boolean mAfterFirstDraw = false;
private State state;
private OnStateChangeListener onStateChangeListener;
public ControllableAppBarLayout(Context context) {
super(context);
}
public ControllableAppBarLayout(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
if (!(getLayoutParams() instanceof CoordinatorLayout.LayoutParams)
|| !(getParent() instanceof CoordinatorLayout)) {
throw new IllegalStateException(
"ControllableAppBarLayout must be a direct child of CoordinatorLayout.");
}
mParent = new WeakReference<CoordinatorLayout>((CoordinatorLayout) getParent());
addOnOffsetChangedListener(this);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
if (mBehavior == null) {
mBehavior = (Behavior) ((CoordinatorLayout.LayoutParams) getLayoutParams()).getBehavior();
}
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
super.onLayout(changed, l, t, r, b);
if (r - l > 0 && b - t > 0 && mAfterFirstDraw && mQueuedChange != ToolbarChange.NONE) {
analyzeQueuedChange();
}
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if (!mAfterFirstDraw) {
mAfterFirstDraw = true;
if (mQueuedChange != ToolbarChange.NONE) {
analyzeQueuedChange();
}
}
}
private synchronized void analyzeQueuedChange() {
switch (mQueuedChange) {
case COLLAPSE:
performCollapsingWithoutAnimation();
break;
case COLLAPSE_WITH_ANIMATION:
performCollapsingWithAnimation();
break;
case EXPAND:
performExpandingWithoutAnimation();
break;
case EXPAND_WITH_ANIMATION:
performExpandingWithAnimation();
break;
}
mQueuedChange = ToolbarChange.NONE;
}
public void collapseToolbar() {
collapseToolbar(false);
}
public void collapseToolbar(boolean withAnimation) {
mQueuedChange = withAnimation ? ToolbarChange.COLLAPSE_WITH_ANIMATION : ToolbarChange.COLLAPSE;
requestLayout();
}
public void expandToolbar() {
expandToolbar(false);
}
public void expandToolbar(boolean withAnimation) {
mQueuedChange = withAnimation ? ToolbarChange.EXPAND_WITH_ANIMATION : ToolbarChange.EXPAND;
requestLayout();
}
private void performCollapsingWithoutAnimation() {
if (mParent.get() != null) {
mBehavior.onNestedPreScroll(mParent.get(), this, null, 0, getHeight(), new int[] { 0, 0 });
}
}
private void performCollapsingWithAnimation() {
if (mParent.get() != null) {
mBehavior.onNestedFling(mParent.get(), this, null, 0, getHeight(), true);
}
}
private void performExpandingWithoutAnimation() {
if (mParent.get() != null) {
mBehavior.setTopAndBottomOffset(0);
}
}
private void performExpandingWithAnimation() {
if (mParent.get() != null) {
mBehavior.onNestedFling(mParent.get(), this, null, 0, -getHeight() * 5, false);
}
}
@Override
public void onOffsetChanged(AppBarLayout appBarLayout, int i) {
if (i == 0) {
if (onStateChangeListener != null && state != State.EXPANDED) {
onStateChangeListener.onStateChange(State.EXPANDED);
}
state = State.EXPANDED;
} else if (Math.abs(i) >= appBarLayout.getTotalScrollRange()) {
if (onStateChangeListener != null && state != State.COLLAPSED) {
onStateChangeListener.onStateChange(State.COLLAPSED);
}
state = State.COLLAPSED;
} else {
if (onStateChangeListener != null && state != State.IDLE) {
onStateChangeListener.onStateChange(State.IDLE);
}
state = State.IDLE;
}
}
public void setOnStateChangeListener(OnStateChangeListener listener) {
this.onStateChangeListener = listener;
}
public State getState() {
return state;
}
public interface OnStateChangeListener {
void onStateChange(State toolbarChange);
}
public enum State {
COLLAPSED,
EXPANDED,
IDLE
}
private enum ToolbarChange {
COLLAPSE,
COLLAPSE_WITH_ANIMATION,
EXPAND,
EXPAND_WITH_ANIMATION,
NONE
}
}
@skimarxall

This comment has been minimized.

Copy link
Owner Author

commented Jul 17, 2015

Forked from https://gist.github.com/blipinsk/3f8fb37209de6d3eea99

How to use:

ControllableAppBarLayout appBarLayout = // get the instance from your view
appBarLayout.setOnStateChangeListener(new ControllableAppBarLayout.OnStateChangeListener() {

      @Override
      public void onStateChange(ControllableAppBarLayout.State toolbarChange) {
        switch (toolbarChange) {

          case COLLAPSED:
            break;
          case EXPANDED:
            break;
          case IDLE: // Just fired once between switching states
            break;
        }
      }
    });
@ntanduc2288

This comment has been minimized.

Copy link

commented Jul 28, 2015

Very easy to use. Good job :)

@maheshwarLigade

This comment has been minimized.

Copy link

commented Sep 2, 2015

I implemented it i just want the on collapse set background image as home logo & hide when expand can you help

@MrWuZhenQuan

This comment has been minimized.

Copy link

commented Sep 24, 2015

How do I do to change the appbar status.

@skimarxall

This comment has been minimized.

Copy link
Owner Author

commented Oct 17, 2015

@MrWuZhenQuan sorry for the late reply I did not see the comment. What do you mean for status? Did you mean state? If so you can use the expand or the collapse method in order to change the state

@skimarxall

This comment has been minimized.

Copy link
Owner Author

commented Oct 17, 2015

@jjimenez0611

This comment has been minimized.

Copy link

commented May 10, 2016

Hi I really

Don't understand how to use this class, I receive an parse error, I don't know what I have to write in this line

ControllableAppBarLayout appBarLayout = // get the instance from your view

Maybe if you can do a little example with a simple Log.d using this class, I really appreciate

@sanathe06

This comment has been minimized.

Copy link

commented Aug 14, 2016

thank you very much.

@pfcvik

This comment has been minimized.

Copy link

commented Sep 7, 2016

How to know when it begins to expand?

@asbadve

This comment has been minimized.

Copy link

commented Feb 5, 2017

Please use intDef instead of enums.
here is updated post

@Axrorxoja

This comment has been minimized.

Copy link

commented May 23, 2017

how to collapse to position,who can help

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.