Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fling smoothly AppBarLayout with NestedScrollView using AppBarLayout.Behavior

I have an AppBarLayout and NestedScrollView. I want the NestedScrollView whenever it scroll down, the AppBarLayout should also expand gracefully, without the NestedScrollView stop right before the AppBarLayout Expand; a second Flight/Scroll is required to get that done.

I check stackoverflow and found this solution pretty related, and could be used. But instead if NestedScrollView, it is RecyclerView. It is in https://stackoverflow.com/a/32454407/3286489

I basically take the code and changed it slightly, and used to check the velocity >8000 to consider also Fling the AppBarLayout as code below.

public final class FlingBehavior extends AppBarLayout.Behavior {
    private boolean isPositive;

    public FlingBehavior() {
    }

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

    @Override
    public boolean onNestedFling(CoordinatorLayout coordinatorLayout, AppBarLayout child, View target, float velocityX, float velocityY, boolean consumed) {
        if (velocityY > 0 && !isPositive || velocityY < 0 && isPositive) {
            velocityY = velocityY * -1;
        }

        if (target instanceof NestedScrollView && Math.abs(velocityY) > 8000) {
            consumed = false;
        }
        return super.onNestedFling(coordinatorLayout, child, target, velocityX, velocityY, consumed);
    }

    @Override
    public void onNestedPreScroll(CoordinatorLayout coordinatorLayout, AppBarLayout child, View target, int dx, int dy, int[] consumed) {
        super.onNestedPreScroll(coordinatorLayout, child, target, dx, dy, consumed);
        isPositive = dy > 0;
    }
}

This works, but not ideal. I'm only want to start (continue) the Fling on the AppBarLayout (i.e. return consumed = false), when the NestedScrollView has reach the top of it's scroll. How could I check that in onNestedFling?

Thanks.

like image 256
Elye Avatar asked Mar 17 '16 05:03

Elye


2 Answers

You Should Check for NestedScrollView And NestedScrollingChild

    if (target instanceof NestedScrollView && Math.abs(velocityY) > 8000) {
        consumed = false;
    }


    if (target instanceof NestedScrollingChild && Math.abs(velocityY) > 8000) {
        consumed = false;
    }
like image 72
Alaa Sbateen Avatar answered Oct 20 '22 19:10

Alaa Sbateen


The problem has been solved with the libraries in this repository.

(https://developer.android.com/topic/libraries/support-library/setup.html)

allprojects {
    repositories {
        jcenter()
        maven {
            url "https://maven.google.com"
        }
    }
}
like image 1
Eniz Bilgin Avatar answered Oct 20 '22 19:10

Eniz Bilgin