Pages

Monday, September 26, 2016

Android: Blocking swipe-to-refresh on minimized AppBar

If you are designing an User-Interface that is using a CollapsingToolbarLayout and SwipeReshLayout, you may notice discomfort when flipping down the content, seen in CollapsingToolbarLayout that immediately trigger swipe-to-refresh.

Here I'm sharing a code below.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
/**
 * Block SwipeRefreshLayout in collapsed and idle state.
 */
public class AppBarRefreshAdjustListener implements AppBarLayout.OnOffsetChangedListener {

    private static final long BLOCK_DELAY = 1000L;

    private final SwipeRefreshLayout mSwipeRefreshLayout;
    private int mVerticalOffset;
    private Handler mHandler = new Handler();

    public AppBarRefreshAdjustListener(SwipeRefreshLayout refreshLayout) {
        mSwipeRefreshLayout = refreshLayout;
        handleOffsetChanged(mVerticalOffset);
    }

    @Override
    public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
        handleOffsetChanged(verticalOffset);
    }

    private void handleOffsetChanged(int verticalOffset) {
        if (verticalOffset == 0) {
            mHandler.removeCallbacksAndMessages(null);
            mHandler.postDelayed(() -> {
                mSwipeRefreshLayout.setEnabled(mVerticalOffset == 0);
            }, BLOCK_DELAY);
        } else {
            mSwipeRefreshLayout.setEnabled(false);
        }
        mVerticalOffset = verticalOffset;
    }
}

This class solves the problem - blocking SwipeRefreshLayout on clotting time / AppBar deployment:

1
appBarLayout addOnOffsetChangedListener (new AppBarRefreshAdjustListener (swipeRefreshLayout) );

2 comments: