简体   繁体   中英

itemview may not be null error in RecyclerViewAdapter

I'm trying to add multiple views in a recyclerview. So first I added getItemView method,

 @Override
    public int getItemViewType(int position) {

            return type.get(position);

    }

Then in the oncreateviewholder method I added this

        @Override
            public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
                View v = null;
                switch (viewType){

                    case 0:
                        v = LayoutInflater.from (parent.getContext ()).inflate (R.layout.view1, parent, false);



                    case 1:
                        v = LayoutInflater.from (parent.getContext ()).inflate (R.layout.view2, parent, false);;




                    case 2:
                        v = LayoutInflater.from (parent.getContext ()).inflate (R.layout.view3, parent, false);


    }

    return new ViewHolder(v);

}

But when run it it's giving me java.lang.IllegalArgumentException: itemView may not be null error...

Either your type collection returns wrong types that do not fall into this switch or your error lies somewhere else.

This is a snippet from my adapter and it works perfectly fine.

@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    int layoutResId = (viewType == VIEW_TYPE_HEADER) ? R.layout.item_header : R.layout.item_content;
    return new ViewHolder(LayoutInflater.from(parent.getContext()).inflate(layoutResId, parent, false));
}

Try adding a default case to this switch and see if it parses the layout then.

EDIT: and please clarify what types is in your code and how you initialize it

Adapter's getItemViewType() returns the number of view type. As you have 3 views( view1, view2, view3 ), you should return 3 from getItemViewType() method.

Try this:

@Override
public int getItemViewType(int position) {
        return 3;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM