Search code examples
androidandroid-coordinatorlayout

Set Top Padding affects Bottom Margin of a View


This is bottom margin:

@Override
protected void directionDownScrolling(View recyclerView) {
    MarginLayoutParams params = (MarginLayoutParams) recyclerView.getLayoutParams();
    params.setMargins(0, 0, 0,
            (int) recyclerView.getContext().getResources().getDimension(R.dimen.dimen_recycler_view_spacing));
    mHandler.postDelayed(() -> recyclerView.setLayoutParams(params), 250);
}

And Top Padding :

@Override
protected void directionDownScrolling(View recyclerView) {
    // Calculate ActionBar height
    TypedValue tv = new TypedValue();
    int actionBarHeight = recyclerView.getContext().getTheme().resolveAttribute(android.R.attr.actionBarSize, tv, true) ?
            TypedValue.complexToDimensionPixelSize(tv.data, recyclerView.getContext().getResources().getDisplayMetrics()) :
            (int) recyclerView.getContext().getResources().getDimension(R.dimen.dimen_recycler_view_spacing);
    recyclerView.setPadding(0, actionBarHeight, 0, 0);
}

As you see top padding applies without no delay, but I expect bottom margin appears after 250ms,

but as soon as top padding applies, bottom margin appears as well. Why and how to fix it?


Solution

  • You're getting the layout parameters from recyclerView:

    MarginLayoutParams params = (MarginLayoutParams) recyclerView.getLayoutParams();
    

    Then you setup the margins directly on it:

    params.setMargins(0, 0, 0,
            (int) recyclerView.getContext().getResources().getDimension(R.dimen.dimen_recycler_view_spacing));
    

    So the delayed message doesn't do anything:

    mHandler.postDelayed(() -> recyclerView.setLayoutParams(params), 250);
    

    This would make a difference if you'd set the layout params to some other instance. Instead call setMargins delayed:

    @Override
    protected void directionDownScrolling(View recyclerView) {
        MarginLayoutParams params = (MarginLayoutParams) recyclerView.getLayoutParams();
        int marginBottom = (int) recyclerView.getContext().getResources().getDimension(R.dimen.dimen_recycler_view_spacing));
        mHandler.postDelayed(() -> {
                params.setMargins(0, 0, 0, marginBottom);
                recyclerView.requestLayout();
        }, 250);
    }