Extra elements in recyclerView

时间:2017-04-08 22:31:07

标签: android android-layout android-recyclerview

RecyclerView improve finding element on list, but I want to do somethink like that:

enter image description here

As you can see, there I have simply item list, but I want to group in a few items and mark them by header.

Header and item list are different classes (have other data inside it)

So, how to add two different layouts(with different data) in recyclerView ?

1 个答案:

答案 0 :(得分:1)

You need two different layouts and two diffrent view holders, and in your adapter you do the following:

1 - Implement the getItemViewType() method and return a different view type when needed (based on position for example). You can define constants like private static final int VIEW_HEADER = 1; to make it easier

2 - In your onCreateViewHolder(), based on the viewType parameter, return the ViewHolder you need

3 - In your onBindViewHolder() check the getItemViewType() of your ViewHolder, cast it to the right type and implement your binding

Here is an example :

public class HeaderAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
    private final static int VIEW_HEADER = 0;
    private final static int VIEW_ITEM = 1;
    private Context context;

    public HeaderAdapter(Context context) {
        this.context = context;
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view;

        if (viewType == VIEW_HEADER) {
            // Inflate header layout
            view = LayoutInflater.from(context).inflate(R.layout.elem_header, parent, false);
            return new HeaderHolder(view);
        }

        // Inflate item layout
        view = LayoutInflater.from(context).inflate(R.layout.elem_item, parent, false);
        return new ItemHolder(view);

    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        if (getItemViewType(position) == VIEW_HEADER){
            // Do some header stuff
            HeaderHolder headerHolder = (HeaderHolder) holder;
            return;
        }


        // Do some item stuff
        ItemHolder itemHolder = (ItemHolder) holder;

    }

    @Override
    public int getItemCount() {
        // Do some crazy calcuation to return the number of items you will display (headers + items)
        return 0;
    }

    @Override
    public int getItemViewType(int position) {
        // Return the type depending on your logic, could use a modulo or even check some list you've passed
        return position == 0 ? VIEW_HEADER : VIEW_ITEM;
    }

    private class ItemHolder extends RecyclerView.ViewHolder {

        ItemHolder(View itemView) {
            super(itemView);
        }
    }


    private class HeaderHolder extends RecyclerView.ViewHolder {

        HeaderHolder(View itemView) {
            super(itemView);
        }
    }
}