Niko
Niko

Reputation: 8153

Parallax scrolling header in RecyclerView with multiple view types

The title pretty much explains my need. I have RecyclerView and adapter with N amount of view types. I have tried 3 different third party libraries (e.g. https://github.com/kanytu/android-parallax-recyclerview) which should support parallax header view. None of them seem to work or need custom adapter which doesn't apply to my use case. Maybe they are internally playing with view types.

Is there some library which would support multiple view types in adapter and parallax scrolling header?

Thanks.

Upvotes: 4

Views: 1215

Answers (1)

David Medenjak
David Medenjak

Reputation: 34552

You can use an ItemDecoration to add a parallax background to specific items. This is just some simple code and can be improved in lots of ways.

public class ParallaxHeaderDecoration extends RecyclerView.ItemDecoration {

    private Bitmap mImage;

    public ParallaxHeaderDecoration(final Context context, @DrawableRes int resId) {
        mImage = BitmapFactory.decodeResource(context.getResources(), resId);
    }

    @Override
    public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) {
        super.onDraw(c, parent, state);
        for (int i = 0; i < parent.getChildCount(); i++) {
            View view = parent.getChildAt(i);
            if (parent.getChildAdapterPosition(view) == 20) {
                int offset = view.getTop() / 3;
                c.drawBitmap(mImage, new Rect(0, offset, mImage.getWidth(), view.getHeight() + offset),
                        new Rect(view.getLeft(), view.getTop(), view.getRight(), view.getBottom()), null);
            }
        }

    }
}

With the item decoration characteristics you can just paint bg to specific views or positions.

RecyclerView with parallax background

And you can see a more complex sample at https://github.com/bleeding182/recyclerviewItemDecorations

Upvotes: 2

Related Questions