w446108264 / StickHeaderLayout

An Android library supports sticking the navigator on the top when ItemView scrolls.
Apache License 2.0
137 stars 39 forks source link

ViewPager用在fragment中报IllegalStateException: ViewHolder views must not be attached when created #8

Open helloworldjie opened 4 years ago

helloworldjie commented 4 years ago

java.lang.IllegalStateException: ViewHolder views must not be attached when created. Ensure that you are not passing 'true' to the attachToRoot parameter of LayoutInflater.inflate(..., boolean attachToRoot) at androidx.recyclerview.widget.RecyclerView$Adapter.createViewHolder(RecyclerView.java:6796) at androidx.recyclerview.widget.RecyclerView$Recycler.tryGetViewHolderForPositionByDeadline(RecyclerView.java:5975) at androidx.recyclerview.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:5858) at androidx.recyclerview.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:5854) at androidx.recyclerview.widget.LinearLayoutManager$LayoutState.next(LinearLayoutManager.java:2230) at androidx.recyclerview.widget.LinearLayoutManager.layoutChunk(LinearLayoutManager.java:1557) at androidx.recyclerview.widget.LinearLayoutManager.fill(LinearLayoutManager.java:1517) at androidx.recyclerview.widget.LinearLayoutManager.onLayoutChildren(LinearLayoutManager.java:612) at androidx.recyclerview.widget.RecyclerView.dispatchLayoutStep2(RecyclerView.java:3924) at androidx.recyclerview.widget.RecyclerView.dispatchLayout(RecyclerView.java:3641) at androidx.recyclerview.widget.RecyclerView.onLayout(RecyclerView.java:4194)

helloworldjie commented 4 years ago

解决了, 加了这段代码 public abstract class RecyclerWithHeaderAdapter extends RecyclerView.Adapter { private static final int TYPE_HEADER = -1616; private View placeHolderView;

public View getPlaceHolderView(){
    return placeHolderView;
}

@Override
public final RecyclerView.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
    if(viewType == TYPE_HEADER){
        if(placeHolderView == null){
            placeHolderView = new View(viewGroup.getContext());
            viewGroup.addView(placeHolderView);
        }

        // 不加这段代码就报错了
        **ViewGroup parent = (ViewGroup)placeHolderView.getParent();
        if (parent != null) {
            parent.removeView(placeHolderView);
        }**

        return new RecyclerPlaceViewHolder(placeHolderView);
    }
    return oncreateViewHolder(viewGroup, viewType);
}