Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting position in onCreateViewHolder

I am transforming my ListView to RecyclerView using Support Library v7.

I have 2 different layouts to load in a RecyclerView. In ListView, I was getting the position of the item in the getView() method and able to load an appropriate layout for that row. But in RecyclerViewthe onCreateViewHolder doesn't have the position parameter.

Is there any other way to achieve this?

PS:The Inbox app from Google shows different layouts in a RecyclerView(might be). I don't think they might have used the ListView because of the performance improvements in RecyclerView

@Override
    public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
        View v=null;

            MyVO vo = voList.get(???POSITION???);

            switch(vo.getType()){
                case TYPE_1:
                    v = LayoutInflater.from(viewGroup.getContext())
                            .inflate(R.layout.layout1, viewGroup, false);
                    break;
                case TYPE_2:
                    v = LayoutInflater.from(viewGroup.getContext())
                            .inflate(R.layout.layout2, viewGroup, false);
                    break;
            }
        return new ViewHolder(v);
    }
like image 857
Sathesh Avatar asked Nov 03 '14 05:11

Sathesh


1 Answers

Firstly, override getItemViewType method:

@Override
public int getItemViewType(int position) {
    //Implement your logic here
    MyVO vo = voList.get(position);
    return vo.getType();
}

Then you can simply use the second parameter of the onCreateViewHolder:

@Override
public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
    View v=null;

        switch(viewType){
            case TYPE_1:
                v = LayoutInflater.from(viewGroup.getContext())
                        .inflate(R.layout.layout1, viewGroup, false);
                break;
            case TYPE_2:
                v = LayoutInflater.from(viewGroup.getContext())
                        .inflate(R.layout.layout2, viewGroup, false);
                break;
        }
    return new ViewHolder(v);
}
like image 64
romtsn Avatar answered Oct 08 '22 21:10

romtsn