Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

IllegalStateException on adding parallax header #12

Open
manujosephv opened this issue Mar 6, 2015 · 20 comments
Open

IllegalStateException on adding parallax header #12

manujosephv opened this issue Mar 6, 2015 · 20 comments

Comments

@manujosephv
Copy link

Hi,

I was trying to implement parallax scrolling using this awesome library. But I ran into some problems. Am not sure I'm doing this right(first time android programmer). I'm getting this on adding parallaxheader.

java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() >on the child's parent first.

I'll just give you a brief idea of what I did. I have a chart which is the header.
So I extended your ParallaxRecyclerAdapter with a custom constructor, overrode some methods, and named it StatsAdapter

 public StatsAdapter(LineChartData mChartData, final List<StatsItem> mListData) {
        super(mListData);
      this.mListData = mListData;
        this.mChartData = mChartData;
        implementRecyclerAdapterMethods(this);
    }

And overrode setParallaxHeader like this

 public void setParallaxHeader(View header, RecyclerView view) {
        LineChartView chart = (LineChartView) header.findViewById(R.id.chart);
        chart.setLineChartData(mChartData);
        formatChart(chart);
        super.setParallaxHeader(header, view);
    }

And in the Fragment from which I'm loading the recyclerview, I did this

 mRecyclerView = (RecyclerView) rootView.findViewById(R.id.stats_recycler_view);
        mRecyclerView.setHasFixedSize(true);
        mLayoutManager = new LinearLayoutManager(getActivity());
        mRecyclerView.setLayoutManager(mLayoutManager);
        mStatsAdapter = new StatsAdapter(mChartData, mListData);
        mHeaderView = LayoutInflater.from(getActivity()).inflate(R.layout.fragment_chart_detail,mRecyclerView,false);
        mStatsAdapter.setParallaxHeader(mHeaderView, mRecyclerView);
        mRecyclerView.setAdapter(mStatsAdapter);

Any idea why I'm getting this error?

@kanytu
Copy link
Owner

kanytu commented Mar 6, 2015

A full stack trace would be better.

This error suggest me that the app is trying to add a view that already has a parent. Also I think implementRecyclerAdapterMethods(this); will not work. This will create an override for the actual methods of RecyclerView.Adapter and not the parallax adapter. I might be wrong but first change to a inner class implementation like implementRecyclerAdapterMethods(new ....) before continuation with more debugging.

@manujosephv
Copy link
Author

I tried replacing "this" with a inner class implementation, but am still getting the error.

Here is the complete stack trace

03-06 16:00:11.081  16363-16363/com.designs.zoomonkey.writetrack E/AndroidRuntimeFATAL EXCEPTION: main
    Process: com.designs.zoomonkey.writetrack, PID: 16363
    java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
            at android.view.ViewGroup.addViewInner(ViewGroup.java:3880)
            at android.view.ViewGroup.addView(ViewGroup.java:3733)
            at android.view.ViewGroup.addView(ViewGroup.java:3709)
            at com.designs.zoomonkey.writetrack.lib.parallaxrecyclerview.ParallaxRecyclerAdapter.setParallaxHeader(ParallaxRecyclerAdapter.java:99)
            at com.designs.zoomonkey.writetrack.adapters.StatsAdapter.setParallaxHeader(StatsAdapter.java:121)
            at com.designs.zoomonkey.writetrack.ui.fragments.StatsDetailFragment.setUpAdapter(StatsDetailFragment.java:194)
            at com.designs.zoomonkey.writetrack.ui.fragments.StatsDetailFragment.onLoadFinished(StatsDetailFragment.java:293)
            at com.designs.zoomonkey.writetrack.ui.fragments.StatsDetailFragment.onLoadFinished(StatsDetailFragment.java:43)
            at android.support.v4.app.LoaderManagerImpl$LoaderInfo.callOnLoadFinished(LoaderManager.java:427)
            at android.support.v4.app.LoaderManagerImpl$LoaderInfo.onLoadComplete(LoaderManager.java:395)
            at android.support.v4.content.Loader.deliverResult(Loader.java:104)
            at android.support.v4.content.CursorLoader.deliverResult(CursorLoader.java:73)
            at android.support.v4.content.CursorLoader.deliverResult(CursorLoader.java:35)
            at android.support.v4.content.AsyncTaskLoader.dispatchOnLoadComplete(AsyncTaskLoader.java:223)
            at android.support.v4.content.AsyncTaskLoader$LoadTask.onPostExecute(AsyncTaskLoader.java:61)
            at android.support.v4.content.ModernAsyncTask.finish(ModernAsyncTask.java:461)
            at android.support.v4.content.ModernAsyncTask.access$500(ModernAsyncTask.java:47)
            at android.support.v4.content.ModernAsyncTask$InternalHandler.handleMessage(ModernAsyncTask.java:474)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5221)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)

@kanytu
Copy link
Owner

kanytu commented Mar 6, 2015

Can you show me the XML for R.layout.fragment_chart_detail?

@manujosephv
Copy link
Author

I also tried passing null as the parent when inflating it, but still no use.
Here is my layout file.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/chart_fragment"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".ProjectDetailFragment"
    android:background="@color/primary">


    <lecho.lib.hellocharts.view.LineChartView
        android:id="@+id/chart"
        android:layout_width="match_parent"
        android:layout_height="@dimen/chart_height"

        android:paddingRight="@dimen/large_padding"
        android:paddingLeft="@dimen/large_padding"
        android:paddingBottom="@dimen/small_padding" />

    <RadioGroup
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_below="@+id/chart"
        android:id="@+id/chart_date_group"
        android:checkedButton="@+id/day_14"
        android:orientation="horizontal"
        android:layout_marginBottom="@dimen/small_margin">

        <RadioButton
            android:layout_width="@dimen/radio_button"
            android:layout_height="@dimen/radio_button"
            android:text="@string/day_7"
            android:id="@+id/day_7"
            android:gravity="center"
            style="@style/AppTheme.RadioButton" />

        <RadioButton
            android:layout_width="@dimen/radio_button"
            android:layout_height="@dimen/radio_button"
            android:text="@string/day_14"
            android:id="@+id/day_14"
            android:gravity="center"
            style="@style/AppTheme.RadioButton" />

        <RadioButton
            android:layout_width="@dimen/radio_button"
            android:layout_height="@dimen/radio_button"
            android:text="@string/month_1"
            android:id="@+id/month_1"
            android:gravity="center"
            style="@style/AppTheme.RadioButton" />

        <RadioButton
            android:layout_width="@dimen/radio_button"
            android:layout_height="@dimen/radio_button"
            android:text="@string/month_6"
            android:id="@+id/month_6"
            android:gravity="center"
            style="@style/AppTheme.RadioButton" />

        <RadioButton
            android:layout_width="@dimen/radio_button"
            android:layout_height="@dimen/radio_button"
            android:text="@string/all"
            android:id="@+id/all_time"
            android:gravity="center"
            style="@style/AppTheme.RadioButton" />
    </RadioGroup>
</RelativeLayout>

@kanytu
Copy link
Owner

kanytu commented Mar 6, 2015

Are you familiar with android debugging? If so add a breakpoint on ParallaxRecyclerAdapter.java:99. Once the debugger stops there check the content of header and search for it's parent:

image

@manujosephv
Copy link
Author

I checked and it's null.. It's null when it is inflated as well.

@kanytu
Copy link
Owner

kanytu commented Mar 6, 2015

Well it doesn't make any sense then :\ could you please comment:

    LineChartView chart = (LineChartView) header.findViewById(R.id.chart);
    chart.setLineChartData(mChartData);
    formatChart(chart);

And try again with just the super call?

@manujosephv
Copy link
Author

I figured it out... I was calling setParallaxHeader twice. Once in onCreate and another time when my loader is finished with the data load. I removed the first call and it started working.. haha..

I got a question. What should one do if he wants to change the header view once you set it once? Like this example: I setParallaxHeader once. And then I have to change the header to another on some user interaction. Obviously creating a new adapter and calling setParallaxHeader is not working. Any workaround?

@manujosephv
Copy link
Author

I am using Loaders to load data to the recycler view and because of that, when the underlying data changes, the loader is called again which calls the setParallaxHeader method. This is getting me same error...

If tried putting a check in the setParallaxHeader method like

if (hasHeader()){
            mHeader.removeAllViews();
        }

And even like this

 if (header.getParent() != null){
            CustomRelativeWrapper customRelativeWrapper = (CustomRelativeWrapper) header.getParent();
            customRelativeWrapper.removeAllViews();
        }

But neither of them gives me a consistent solution.

@kanytu
Copy link
Owner

kanytu commented Mar 8, 2015

Could you try this setParallaxHeader method?

public void setParallaxHeader(View header, final RecyclerView view) {
    mRecyclerView = view;
    if (mHeader != null) {
        RecyclerView.ViewHolder holder = view.findViewHolderForPosition(0);
        if (holder != null) {
            mHeader = new CustomRelativeWrapper(header.getContext(), mShouldClipView);
            mHeader.addView(header, new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
            ((CustomRelativeWrapper) holder.itemView).removeAllViews();
            ((CustomRelativeWrapper) holder.itemView).addView(mHeader, new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
            return;
        }
    } else {
        mHeader = new CustomRelativeWrapper(header.getContext(), mShouldClipView);
        mHeader.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
        mHeader.addView(header, new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
    }
    view.setOnScrollListener(new RecyclerView.OnScrollListener() {
        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            super.onScrolled(recyclerView, dx, dy);
            if (mHeader != null) {
                mTotalYScrolled += dy;
                translateHeader(mTotalYScrolled);
            }
        }
    });
}

@manujosephv
Copy link
Author

I tried and it's not working. It's not going into the if condition that you put in. i.e holder is null.

I think the problem is that mHeader is already a child of the previous CustomRelativeWrapper, but somehow the reference to that is lost. Cause when I debugged, I could see even when mHeader was null, the header we pass in has a parent.
I tried slightly tweaking the method you gave me..

 public void setParallaxHeader(View header, final RecyclerView view) {
        mRecyclerView = view;
        if (header.getParent()!=null) {
            RecyclerView.ViewHolder holder = view.findViewHolderForPosition(0);
            if (holder != null) {
                ((CustomRelativeWrapper) holder.itemView).removeAllViews();
                mHeader = new CustomRelativeWrapper(header.getContext(), mShouldClipView);
                mHeader.addView(header, new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
                ((CustomRelativeWrapper) holder.itemView).addView(mHeader, new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
                return;
            }
        } else {
            mHeader = new CustomRelativeWrapper(header.getContext(), mShouldClipView);
            mHeader.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
            mHeader.addView(header, new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
        }
        view.setOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                if (mHeader != null) {
                    mTotalYScrolled += dy;
                    translateHeader(mTotalYScrolled);
                }
            }
        });
    }

Here it is going into the loop, and it works the first time it gets called(but the UI becomes weird). From the next time I'm getting the error. So when I looked into it what I found out was:

  1. In the first run: CustomRelativeWrapper is added as the holder.itemview
  2. when we call the function again, we go into the if condition and then we remove the views from itemView(CustomRelativeWrapper) and then we add another CustomRelativeWrapper to the itemView(which is already a CustomRelativeWrapper)

If there was a way to add the header directly to the holder, then it might work. I'm not sure though. What do you think?

@kanytu
Copy link
Owner

kanytu commented Mar 9, 2015

This might work but only if the header is currently visible because if not the holder will return null. Could you try and see if it works. If so we can start working from here.

public void setParallaxHeader(View header, final RecyclerView view) {
    mRecyclerView = view;
    if (mHeader != null) {
        RecyclerView.ViewHolder holder = view.findViewHolderForPosition(0);
        if (holder != null) {
            ((CustomRelativeWrapper) holder.itemView).removeAllViews();
            ((CustomRelativeWrapper) holder.itemView).addView(header, new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
            mHeader = ((CustomRelativeWrapper) holder.itemView);
            //mHeader.addView(header, new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
            return;
        }
    } else {
        mHeader = new CustomRelativeWrapper(header.getContext(), mShouldClipView);
        mHeader.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
        mHeader.addView(header, new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
    }
    view.setOnScrollListener(new RecyclerView.OnScrollListener() {
        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            super.onScrolled(recyclerView, dx, dy);
            if (mHeader != null) {
                mTotalYScrolled += dy;
                translateHeader(mTotalYScrolled);
            }
        }
    });

}

@kanytu
Copy link
Owner

kanytu commented Mar 9, 2015

Tell me something. Is the new header you're trying to set the same size of the old one? Because if so I might have a working solution on my hands.

@manujosephv
Copy link
Author

Yeah, Its the same header, in fact, with some updated values.. If I can get a reference to the header, I should be able to update it.

@kanytu
Copy link
Owner

kanytu commented Mar 9, 2015

So if it's the same header a simple getHeader returning mHeader don't work?

Something like

public View getHeader(){
    return mHeader;
}

Then you can get your view by simple calling getChildAt(0);

@manujosephv
Copy link
Author

I just had this idea while driving back from work. getHeader might not work
as I'm creating a new adapter with new data. mHeader is usually null. But
I'll try holding on to the view I'm passing as header in the fragment and
update the header view. I'll let you know how this goes.

On Mon, Mar 9, 2015, 9:46 PM Pedro Oliveira [email protected]
wrote:

So if it's the same header a simple getHeader returning mHeader don't
work?

Something like

public View getHeader(){
return mHeader;
}

Then you can get your view by simple calling getChildAt(0);


Reply to this email directly or view it on GitHub
#12 (comment)
.

@kanytu
Copy link
Owner

kanytu commented Mar 9, 2015

If that doesn't work try this adapter:

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.os.Build;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.TranslateAnimation;
import android.widget.RelativeLayout;

import java.util.List;


/**
 * Created by poliveira on 03/11/2014.
 */
public class ParallaxRecyclerAdapter<T> extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
    private final float SCROLL_MULTIPLIER = 0.5f;

    public static class VIEW_TYPES {
        public static final int NORMAL = 1;
        public static final int HEADER = 2;
        public static final int FIRST_VIEW = 3;
    }

    public interface RecyclerAdapterMethods {
        void onBindViewHolder(RecyclerView.ViewHolder viewHolder, int i);

        RecyclerView.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i);

        int getItemCount();
    }


    public interface OnClickEvent {
        /**
         * Event triggered when you click on a item of the adapter
         *
         * @param v        view
         * @param position position on the array
         */
        void onClick(View v, int position);
    }

    public interface OnParallaxScroll {
        /**
         * Event triggered when the parallax is being scrolled.
         *
         * @param percentage
         * @param offset
         * @param parallax
         */
        void onParallaxScroll(float percentage, float offset, View parallax);
    }

    private List<T> mData;
    private CustomRelativeWrapper mHeader;
    private RecyclerAdapterMethods mRecyclerAdapterMethods;
    private OnClickEvent mOnClickEvent;
    private OnParallaxScroll mParallaxScroll;
    private RecyclerView mRecyclerView;
    private int mTotalYScrolled;
    private boolean mShouldClipView = true;

    /**
     * Translates the adapter in Y
     *
     * @param of offset in px
     */
    public void translateHeader(float of) {
        RecyclerView.ViewHolder holder = mRecyclerView.findViewHolderForPosition(0);
        if (holder == null) {
            holder = mRecyclerView.getRecycledViewPool().getRecycledView(VIEW_TYPES.HEADER);
        }
        if (holder == null)
            return;
        View header = holder.itemView;
        float ofCalculated = of * SCROLL_MULTIPLIER;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
            header.setTranslationY(ofCalculated);
        } else {
            TranslateAnimation anim = new TranslateAnimation(0, 0, ofCalculated, ofCalculated);
            anim.setFillAfter(true);
            anim.setDuration(0);
            header.startAnimation(anim);
        }
        ((CustomRelativeWrapper) header).setClipY(Math.round(ofCalculated));
        if (mParallaxScroll != null) {
            float left = Math.min(1, ((ofCalculated) / (header.getHeight() * SCROLL_MULTIPLIER)));
            mParallaxScroll.onParallaxScroll(left, of, header);
        }
    }

    /**
     * Set the view as header.
     *
     * @param header The inflated header
     * @param view   The RecyclerView to set scroll listeners
     */
    public void setParallaxHeader(View header, final RecyclerView view) {
        mRecyclerView = view;
        if (mHeader != null) {
            RecyclerView.ViewHolder holder = view.findViewHolderForPosition(0);
            if (holder == null) {
                holder = view.getRecycledViewPool().getRecycledView(VIEW_TYPES.HEADER);
            }
            if (holder == null) {
                mHeader = new CustomRelativeWrapper(header.getContext(), mShouldClipView);
                mHeader.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
                mHeader.addView(header, new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
                notifyDataSetChanged();
                return;
            }
            // mHeader = new CustomRelativeWrapper(header.getContext(), mShouldClipView);
            //mHeader.addView(header);
            ((CustomRelativeWrapper) holder.itemView).removeAllViews();
            ((CustomRelativeWrapper) holder.itemView).addView(header, new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));

            //mHeader.addView(header, new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
        } else {
            mHeader = new CustomRelativeWrapper(header.getContext(), mShouldClipView);
            mHeader.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
            mHeader.addView(header, new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
        }

        view.setOnScrollListener(new RecyclerView.OnScrollListener() {
                                     @Override
                                     public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                                         super.onScrolled(recyclerView, dx, dy);
                                         if (mHeader != null) {
                                             mTotalYScrolled += dy;
                                             translateHeader(mTotalYScrolled);
                                         }
                                     }
                                 }

        );
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder viewHolder, final int i) {
        if (mRecyclerAdapterMethods == null)
            throw new NullPointerException("You must call implementRecyclerAdapterMethods");
        if (i != 0 && mHeader != null) {
            mRecyclerAdapterMethods.onBindViewHolder(viewHolder, i - 1);
        } else if (i != 0)
            mRecyclerAdapterMethods.onBindViewHolder(viewHolder, i);
        if (mOnClickEvent != null)
            viewHolder.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mOnClickEvent.onClick(v, i - (mHeader == null ? 0 : 1));
                }
            });
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
        Log.v("TESTE", "requesting layout " + i);
        if (mRecyclerAdapterMethods == null)
            throw new NullPointerException("You must call implementRecyclerAdapterMethods");
        if (i == VIEW_TYPES.HEADER && mHeader != null) {
            Log.v("TESTE", "header");
            return new ViewHolder(mHeader);
        }
        if (i == VIEW_TYPES.FIRST_VIEW && mHeader != null && mRecyclerView != null) {
            RecyclerView.ViewHolder holder = mRecyclerView.findViewHolderForPosition(0);
            if (holder != null) {
                translateHeader(-holder.itemView.getTop());
                mTotalYScrolled = -holder.itemView.getTop();
            }
        }
        return mRecyclerAdapterMethods.onCreateViewHolder(viewGroup, i);
    }

    /**
     * @return true if there is a header on this adapter, false otherwise
     */

    public boolean hasHeader() {
        return mHeader != null;
    }

    public void setOnClickEvent(OnClickEvent onClickEvent) {
        mOnClickEvent = onClickEvent;
    }


    public boolean isShouldClipView() {
        return mShouldClipView;
    }

    /**
     * Defines if we will clip the layout or not. MUST BE CALLED BEFORE {@link #setParallaxHeader(android.view.View, android.support.v7.widget.RecyclerView)}
     *
     * @param shouldClickView
     */
    public void setShouldClipView(boolean shouldClickView) {
        mShouldClipView = shouldClickView;
    }

    public void setOnParallaxScroll(OnParallaxScroll parallaxScroll) {
        mParallaxScroll = parallaxScroll;
        mParallaxScroll.onParallaxScroll(0, 0, mHeader);
    }

    public ParallaxRecyclerAdapter(List<T> data) {
        mData = data;
    }

    public List<T> getData() {
        return mData;
    }

    public void setData(List<T> data) {
        mData = data;
        notifyDataSetChanged();
    }

    public void addItem(T item, int position) {
        mData.add(position, item);
        notifyItemInserted(position + (mHeader == null ? 0 : 1));
    }

    public void removeItem(T item) {
        int position = mData.indexOf(item);
        if (position < 0)
            return;
        mData.remove(item);
        notifyItemRemoved(position + (mHeader == null ? 0 : 1));
    }


    public int getItemCount() {
        if (mRecyclerAdapterMethods == null)
            throw new NullPointerException("You must call implementRecyclerAdapterMethods");
        return mRecyclerAdapterMethods.getItemCount() + (mHeader == null ? 0 : 1);
    }

    @Override
    public int getItemViewType(int position) {
        if (mRecyclerAdapterMethods == null)
            throw new NullPointerException("You must call implementRecyclerAdapterMethods");
        if (position == 1)
            return VIEW_TYPES.FIRST_VIEW;
        return position == 0 ? VIEW_TYPES.HEADER : VIEW_TYPES.NORMAL;
    }

    /**
     * You must call this method to set your normal adapter methods
     *
     * @param callbacks
     */
    public void implementRecyclerAdapterMethods(RecyclerAdapterMethods callbacks) {
        mRecyclerAdapterMethods = callbacks;
    }

    static class ViewHolder extends RecyclerView.ViewHolder {
        public ViewHolder(View itemView) {
            super(itemView);
        }
    }

    static class CustomRelativeWrapper extends RelativeLayout {

        private int mOffset;
        private boolean mShouldClip;

        public CustomRelativeWrapper(Context context, boolean shouldClick) {
            super(context);
            mShouldClip = shouldClick;
        }

        @Override
        protected void dispatchDraw(Canvas canvas) {
            if (mShouldClip) {
                canvas.clipRect(new Rect(getLeft(), getTop(), getRight(), getBottom() + mOffset));
            }
            super.dispatchDraw(canvas);
        }

        public void setClipY(int offset) {
            mOffset = offset;
            invalidate();
        }
    }
}

@manujosephv
Copy link
Author

I tried it with getheader, but not working. I tried the new Adapter, also not working(on first try). Will look into it further tomorrow.

I have modified your adapter to use Cursors. I did not touch any of your methods, but added some other. The full code is below. I am not sure if that is causing a problem

package com.designs.zoomonkey.writetrack.lib.parallaxrecyclerview;

import android.content.Context;
import android.database.ContentObserver;
import android.database.Cursor;
import android.database.DataSetObserver;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.os.Build;
import android.os.Handler;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.TranslateAnimation;
import android.widget.Filter;
import android.widget.FilterQueryProvider;
import android.widget.RelativeLayout;

/**
 * Created by manu.joseph on 07-03-2015.
 * Combined two great libraries for RecyclerViews
 */
public class ParallaxCursorRecyclerAdapter<VH
        extends android.support.v7.widget.RecyclerView.ViewHolder> extends RecyclerView.Adapter<RecyclerView.ViewHolder> implements CursorFilter.CursorFilterClient {
    private final float SCROLL_MULTIPLIER = 0.5f;

    public static class VIEW_TYPES {
        public static final int NORMAL = 1;
        public static final int HEADER = 2;
        public static final int FIRST_VIEW = 3;
    }


    public interface RecyclerAdapterMethods {
        void onBindViewHolder(RecyclerView.ViewHolder viewHolder, int position, Cursor cursor);

        RecyclerView.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int position);
    }


    public interface OnClickEvent {
        /**
         * Event triggered when you click on a item of the adapter
         *
         * @param v        view
         * @param position position on the array
         */
        void onClick(View v, int position);
    }

    public interface OnParallaxScroll {
        /**
         * Event triggered when the parallax is being scrolled.
         *
         * @param percentage
         * @param offset
         * @param parallax
         */
        void onParallaxScroll(float percentage, float offset, View parallax);
    }

    //    private List<T> mData;
    private CustomRelativeWrapper mHeader;
    private RecyclerAdapterMethods mRecyclerAdapterMethods;
    private OnClickEvent mOnClickEvent;
    private OnParallaxScroll mParallaxScroll;
    private RecyclerView mRecyclerView;
    private int mTotalYScrolled;
    private boolean mShouldClipView = true;
    /**
     * ****************************************************************************************************************************
     */
    private boolean mDataValid;
    private int mRowIDColumn;
    private Cursor mCursor;
    private ChangeObserver mChangeObserver;
    private DataSetObserver mDataSetObserver;
    private CursorFilter mCursorFilter;
    private FilterQueryProvider mFilterQueryProvider;


    void init(Cursor c) {
        boolean cursorPresent = c != null;
        mCursor = c;
        mDataValid = cursorPresent;
        mRowIDColumn = cursorPresent ? c.getColumnIndexOrThrow("_id") : -1;

        mChangeObserver = new ChangeObserver();
        mDataSetObserver = new MyDataSetObserver();

        if (cursorPresent) {
            if (mChangeObserver != null) c.registerContentObserver(mChangeObserver);
            if (mDataSetObserver != null) c.registerDataSetObserver(mDataSetObserver);
        }
    }

    public Cursor getCursor() {
        return mCursor;
    }

    /**
     * Change the underlying cursor to a new cursor. If there is an existing cursor it will be
     * closed.
     *
     * @param cursor The new cursor to be used
     */
    public void changeCursor(Cursor cursor) {
        Cursor old = swapCursor(cursor);
        if (old != null) {
            old.close();
        }
    }

    /**
     * Swap in a new Cursor, returning the old Cursor.  Unlike
     * {@link #changeCursor(Cursor)}, the returned old Cursor is <em>not</em>
     * closed.
     *
     * @param newCursor The new cursor to be used.
     * @return Returns the previously set Cursor, or null if there wasa not one.
     * If the given new Cursor is the same instance is the previously set
     * Cursor, null is also returned.
     */
    public Cursor swapCursor(Cursor newCursor) {
        if (newCursor == mCursor) {
            return null;
        }
        Cursor oldCursor = mCursor;
        if (oldCursor != null) {
            if (mChangeObserver != null) oldCursor.unregisterContentObserver(mChangeObserver);
            if (mDataSetObserver != null) oldCursor.unregisterDataSetObserver(mDataSetObserver);
        }
        mCursor = newCursor;
        if (newCursor != null) {
            if (mChangeObserver != null) newCursor.registerContentObserver(mChangeObserver);
            if (mDataSetObserver != null) newCursor.registerDataSetObserver(mDataSetObserver);
            mRowIDColumn = newCursor.getColumnIndexOrThrow("_id");
            mDataValid = true;
            // notify the observers about the new cursor
            notifyDataSetChanged();
        } else {
            mRowIDColumn = -1;
            mDataValid = false;
            // notify the observers about the lack of a data set
            // notifyDataSetInvalidated();
            notifyItemRangeRemoved(0, getItemCount());
        }
        return oldCursor;
    }

    /**
     * <p>Converts the cursor into a CharSequence. Subclasses should override this
     * method to convert their results. The default implementation returns an
     * empty String for null values or the default String representation of
     * the value.</p>
     *
     * @param cursor the cursor to convert to a CharSequence
     * @return a CharSequence representing the value
     */
    public CharSequence convertToString(Cursor cursor) {
        return cursor == null ? "" : cursor.toString();
    }

    /**
     * Runs a query with the specified constraint. This query is requested
     * by the filter attached to this adapter.
     * <p/>
     * The query is provided by a
     * {@link android.widget.FilterQueryProvider}.
     * If no provider is specified, the current cursor is not filtered and returned.
     * <p/>
     * After this method returns the resulting cursor is passed to {@link #changeCursor(Cursor)}
     * and the previous cursor is closed.
     * <p/>
     * This method is always executed on a background thread, not on the
     * application's main thread (or UI thread.)
     * <p/>
     * Contract: when constraint is null or empty, the original results,
     * prior to any filtering, must be returned.
     *
     * @param constraint the constraint with which the query must be filtered
     * @return a Cursor representing the results of the new query
     * @see #getFilter()
     * @see #getFilterQueryProvider()
     * @see #setFilterQueryProvider(android.widget.FilterQueryProvider)
     */
    public Cursor runQueryOnBackgroundThread(CharSequence constraint) {
        if (mFilterQueryProvider != null) {
            return mFilterQueryProvider.runQuery(constraint);
        }

        return mCursor;
    }

    public Filter getFilter() {
        if (mCursorFilter == null) {
            mCursorFilter = new CursorFilter(this);
        }
        return mCursorFilter;
    }

    /**
     * Returns the query filter provider used for filtering. When the
     * provider is null, no filtering occurs.
     *
     * @return the current filter query provider or null if it does not exist
     * @see #setFilterQueryProvider(android.widget.FilterQueryProvider)
     * @see #runQueryOnBackgroundThread(CharSequence)
     */
    public FilterQueryProvider getFilterQueryProvider() {
        return mFilterQueryProvider;
    }

    /**
     * Sets the query filter provider used to filter the current Cursor.
     * The provider's
     * {@link android.widget.FilterQueryProvider#runQuery(CharSequence)}
     * method is invoked when filtering is requested by a client of
     * this adapter.
     *
     * @param filterQueryProvider the filter query provider or null to remove it
     * @see #getFilterQueryProvider()
     * @see #runQueryOnBackgroundThread(CharSequence)
     */
    public void setFilterQueryProvider(FilterQueryProvider filterQueryProvider) {
        mFilterQueryProvider = filterQueryProvider;
    }

    /**
     * Called when the {@link android.database.ContentObserver} on the cursor receives a change notification.
     * Can be implemented by sub-class.
     *
     * @see android.database.ContentObserver#onChange(boolean)
     */
    protected void onContentChanged() {

    }

/********************************************************************************************************************************/
    /**
     * Translates the adapter in Y
     *
     * @param of offset in px
     */
    public void translateHeader(float of) {
        RecyclerView.ViewHolder holder = mRecyclerView.findViewHolderForPosition(0);
        if (holder == null) {
            holder = mRecyclerView.getRecycledViewPool().getRecycledView(VIEW_TYPES.HEADER);
        }
        if (holder == null)
            return;
        View header = holder.itemView;
        float ofCalculated = of * SCROLL_MULTIPLIER;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
            header.setTranslationY(ofCalculated);
        } else {
            TranslateAnimation anim = new TranslateAnimation(0, 0, ofCalculated, ofCalculated);
            anim.setFillAfter(true);
            anim.setDuration(0);
            header.startAnimation(anim);
        }
        ((CustomRelativeWrapper) header).setClipY(Math.round(ofCalculated));
        if (mParallaxScroll != null) {
            float left = Math.min(1, ((ofCalculated) / (header.getHeight() * SCROLL_MULTIPLIER)));
            mParallaxScroll.onParallaxScroll(left, of, header);
        }
    }

    /**
     * Set the view as header.
     *
     * @param header The inflated header
     * @param view   The RecyclerView to set scroll listeners
     */
    public void setParallaxHeader(View header, final RecyclerView view) {
        mRecyclerView = view;
        if (mHeader != null) {
            RecyclerView.ViewHolder holder = view.findViewHolderForPosition(0);
            if (holder == null) {
                holder = view.getRecycledViewPool().getRecycledView(VIEW_TYPES.HEADER);
            }
            if (holder == null) {
                mHeader = new CustomRelativeWrapper(header.getContext(), mShouldClipView);
                mHeader.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
                mHeader.addView(header, new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
                notifyDataSetChanged();
                return;
            }
            // mHeader = new CustomRelativeWrapper(header.getContext(), mShouldClipView);
            //mHeader.addView(header);
            ((CustomRelativeWrapper) holder.itemView).removeAllViews();
            ((CustomRelativeWrapper) holder.itemView).addView(header, new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));

            //mHeader.addView(header, new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
        } else {
            mHeader = new CustomRelativeWrapper(header.getContext(), mShouldClipView);
            mHeader.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
            mHeader.addView(header, new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
        }

        view.setOnScrollListener(new RecyclerView.OnScrollListener() {
                                     @Override
                                     public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                                         super.onScrolled(recyclerView, dx, dy);
                                         if (mHeader != null) {
                                             mTotalYScrolled += dy;
                                             translateHeader(mTotalYScrolled);
                                         }
                                     }
                                 }

        );
    }

    public void removeParallaxHeader() {
        mHeader.removeAllViews();
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder viewHolder, final int i) {
        if (!mDataValid) {
            throw new IllegalStateException("this should only be called when the cursor is valid");
        }

        if (i > 0 && !mCursor.moveToPosition(i - 1)) {
            throw new IllegalStateException("couldn't move cursor to position " + i);
        }
//        Log.d("BAWDA", "position: " + i + ": holder type: " + viewHolder.getItemViewType() + ": cursor current position: " + mCursor.getPosition());
        if (mRecyclerAdapterMethods == null)
            throw new NullPointerException("You must call implementRecyclerAdapterMethods");
        if (i != 0 && mHeader != null) {
            mRecyclerAdapterMethods.onBindViewHolder(viewHolder, i - 1, mCursor);
        } else if (i != 0)
            mRecyclerAdapterMethods.onBindViewHolder(viewHolder, i, mCursor);
        if (mOnClickEvent != null)
            viewHolder.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mOnClickEvent.onClick(v, i - (mHeader == null ? 0 : 1));
                }
            });
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
        Log.v("TESTE", "requesting layout " + i);
        if (mRecyclerAdapterMethods == null)
            throw new NullPointerException("You must call implementRecyclerAdapterMethods");
        if (i == VIEW_TYPES.HEADER && mHeader != null) {
            Log.v("TESTE", "header");
            return new ViewHolder(mHeader);
        }
        if (i == VIEW_TYPES.FIRST_VIEW && mHeader != null && mRecyclerView != null) {
            RecyclerView.ViewHolder holder = mRecyclerView.findViewHolderForPosition(0);
            if (holder != null) {
                translateHeader(-holder.itemView.getTop());
                mTotalYScrolled = -holder.itemView.getTop();
            }
        }
        return mRecyclerAdapterMethods.onCreateViewHolder(viewGroup, i);
    }

    /**
     * @return true if there is a header on this adapter, false otherwise
     */
    public boolean hasHeader() {
        return mHeader != null;
    }

    public void setOnClickEvent(OnClickEvent onClickEvent) {
        mOnClickEvent = onClickEvent;
    }


    public boolean isShouldClipView() {
        return mShouldClipView;
    }

    /**
     * Defines if we will clip the layout or not. MUST BE CALLED BEFORE {@link #setParallaxHeader(android.view.View, android.support.v7.widget.RecyclerView)}
     *
     * @param shouldClickView
     */
    public void setShouldClipView(boolean shouldClickView) {
        mShouldClipView = shouldClickView;
    }

    public void setOnParallaxScroll(OnParallaxScroll parallaxScroll) {
        mParallaxScroll = parallaxScroll;
        mParallaxScroll.onParallaxScroll(0, 0, mHeader);
    }

    public ParallaxCursorRecyclerAdapter(Cursor cursor) {
//        mData = data;
        init(cursor);
    }
/*    //Required Default Constructor
    public ParallaxRecyclerAdapter() {

    }*/

/*    public List<T> getData() {
        return mData;
    }

    public void setData(List<T> data) {
        mData = data;
        notifyDataSetChanged();
    }

    public void addItem(T item, int position) {
        mData.add(position, item);
        notifyItemInserted(position + (mHeader == null ? 0 : 1));
    }

    public void removeItem(T item) {
        int position = mData.indexOf(item);
        if (position < 0)
            return;
        mData.remove(item);
        notifyItemRemoved(position + (mHeader == null ? 0 : 1));
    }*/


    public int getItemCount() {
        if (mDataValid && mCursor != null) {
            return mCursor.getCount() + (mHeader == null ? 0 : 1);
        } else {
            return 0 + (mHeader == null ? 0 : 1);
        }
    }

    @Override
    public int getItemViewType(int position) {
        if (mRecyclerAdapterMethods == null)
            throw new NullPointerException("You must call implementRecyclerAdapterMethods");
        if (position == 1)
            return VIEW_TYPES.FIRST_VIEW;
        return position == 0 ? VIEW_TYPES.HEADER : VIEW_TYPES.NORMAL;
    }

    /**
     * @see android.widget.ListAdapter#getItemId(int)
     */
    @Override
    public long getItemId(int position) {
        if (mDataValid && mCursor != null) {
            if (mCursor.moveToPosition(position)) {
                return mCursor.getLong(mRowIDColumn);
            } else {
                return 0;
            }
        } else {
            return 0;
        }
    }

    /**
     * You must call this method to set your normal adapter methods
     *
     * @param callbacks
     */
    public void implementRecyclerAdapterMethods(RecyclerAdapterMethods callbacks) {
        mRecyclerAdapterMethods = callbacks;
    }

    static class ViewHolder extends RecyclerView.ViewHolder {
        public ViewHolder(View itemView) {
            super(itemView);
        }
    }

    static class CustomRelativeWrapper extends RelativeLayout {

        private int mOffset;
        private boolean mShouldClip;

        public CustomRelativeWrapper(Context context, boolean shouldClick) {
            super(context);
            mShouldClip = shouldClick;
        }

        @Override
        protected void dispatchDraw(Canvas canvas) {
            if (mShouldClip) {
                canvas.clipRect(new Rect(getLeft(), getTop(), getRight(), getBottom() + mOffset));
            }
            super.dispatchDraw(canvas);
        }

        public void setClipY(int offset) {
            mOffset = offset;
            invalidate();
        }
    }

    /**
     * ****************************************************************************************************************************
     */

    private class ChangeObserver extends ContentObserver {
        public ChangeObserver() {
            super(new Handler());
        }

        @Override
        public boolean deliverSelfNotifications() {
            return true;
        }

        @Override
        public void onChange(boolean selfChange) {
            onContentChanged();
        }
    }

    private class MyDataSetObserver extends DataSetObserver {
        @Override
        public void onChanged() {
            mDataValid = true;
            notifyDataSetChanged();
        }

        @Override
        public void onInvalidated() {
            mDataValid = false;
            // notifyDataSetInvalidated();
            notifyItemRangeRemoved(0, getItemCount());
        }
    }


}

class CursorFilter extends Filter {

    CursorFilterClient mClient;

    interface CursorFilterClient {
        CharSequence convertToString(Cursor cursor);

        Cursor runQueryOnBackgroundThread(CharSequence constraint);

        Cursor getCursor();

        void changeCursor(Cursor cursor);
    }

    CursorFilter(CursorFilterClient client) {
        mClient = client;
    }

    @Override
    public CharSequence convertResultToString(Object resultValue) {
        return mClient.convertToString((Cursor) resultValue);
    }

    @Override
    protected FilterResults performFiltering(CharSequence constraint) {
        Cursor cursor = mClient.runQueryOnBackgroundThread(constraint);

        FilterResults results = new FilterResults();
        if (cursor != null) {
            results.count = cursor.getCount();
            results.values = cursor;
        } else {
            results.count = 0;
            results.values = null;
        }
        return results;
    }

    @Override
    protected void publishResults(CharSequence constraint, FilterResults results) {
        Cursor oldCursor = mClient.getCursor();

        if (results.values != null && results.values != oldCursor) {
            mClient.changeCursor((Cursor) results.values);
        }
    }
}

@manujosephv
Copy link
Author

Hey, great news.. I found a workaround and it is working.

First I tried getting the parent of the header I'm passing, removing it, and then pass it to the setParallaxHeader method. But that got me weird results. The header itself was missing.

But then, I tried inflating the header every time the loader completes. It is a little expensive, but seems to be working..

P.S - using your old adapter itself.

@westlinkin
Copy link

Hey, I have the same problem you've got, I want to set the parallaxHeader multiple times.

I'm using the old adapter, I'm not completely understand your workaround solution, can you paste some code here. Thank you very much. @manujosephv

Here is the set header code:

private void setHeader(boolean hasLogin) {
        Log.d(FRAGMENT_TAG, "set header");
        View header;
        if (hasLogin) {
            // todo: fix the header
            header = LayoutInflater.from(getActivity()).inflate(R.layout.header_login, makeOrderList, false);

            // todo: init the header's child views
        } else {
            header = LayoutInflater.from(getActivity()).inflate(R.layout.header_unlogin, makeOrderList, false);
        }
        adapter.setParallaxHeader(header, makeOrderList);
        adapter.notifyDataSetChanged();
    }

Every time, I inflate a header view, and then set it, but the header won't change.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants