Tuesday, 6 October 2015

android.support.v7.widget.RecyclerView java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.



you may have this error when you are using:

RecyclerView


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





// Create new views (invoked by the layout manager)@Overridepublic MyAdapterX.ViewHolder onCreateViewHolder(ViewGroup parent,
                                               int viewType) {
    // create a new view    View v = LayoutInflater.from(parent.getContext())
            .inflate(R.layout.customer_cell, parent, false);
    // set the view's size, margins, paddings and layout parameters    TextView mTextView = (TextView)v.findViewById(R.id.customer_name);
    ViewHolder vh = new ViewHolder(mTextView);
    return vh;
}


The problem is you can't pass a sub-view to viewholder, you must pass the call root view.


But you can do this:

public static class ViewHolder extends RecyclerView.ViewHolder {
    // each data item is just a string in this case    public TextView mTextView;
    public ViewHolder(View v) {
        super(v);
        mTextView = (TextView)v.findViewById(R.id.customer_name);
    }
}

// Provide a suitable constructor (depends on the kind of dataset)public MyAdapterX(List<String> myDataset) {
    mDataset = myDataset;
}

// Create new views (invoked by the layout manager)@Overridepublic MyAdapterX.ViewHolder onCreateViewHolder(ViewGroup parent,
                                               int viewType) {
    // create a new view    View v = LayoutInflater.from(parent.getContext())
            .inflate(R.layout.customer_cell, parent, false);
    // set the view's size, margins, paddings and layout parameters    ViewHolder vh = new ViewHolder(v);
    return vh;
}


I think that because ViewHolder super must did something special with layoutmanager.




No comments:

Post a comment