简体   繁体   中英

How to create plus icon in grid recyclerview for adding images?

在此处输入图片说明

How do I create something like this using gridlayoutManager In a reyclerview ? How to do this in an efficient way, so that whenever I click on the plus image I can fetch a new image from my device so that the image shows up in the grid at bottom or in a new column?

You can create two layouts : one with the + icon and other where image will be displayed for your grid adapter. Then you can check for the position and return the layout you want.

      private static final int VIEW_TYPE_ONE = 1;
      private static final int VIEW_TYPE_TWO = 2;

      // Determines the appropriate ViewType according to the position
@Override
public int getItemViewType(int position) {

    if (position == 0 ) {

        return VIEW_TYPE_ONE;
    } else {

        return VIEW_TYPE_TWO;
    }
}

Then in your onCreateviewHolder:

     // Inflates the appropriate layout according to the ViewType.
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View view;

    if (viewType == VIEW_TYPE_ONE) {
        view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.your_plus_icon_layout, parent, false);
        return new PlusIconViewHolder(view);
    } else if (viewType == VIEW_TYPE_MESSAGE_TWO) {
        view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.your_normal_image_layout, parent, false);
        return new NormalViewHolder(view);
    }

    return null;
}

In your onBindViewHolder,

@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
    switch (holder.getItemViewType()) {
        case VIEW_TYPE_ONE:
             holder.bind();
            break;
        case VIEW_TYPE_MESSAGE_TWO:
             holder.bind(imageList.get(position -1));
    }
}

Note that i have send position - 1 item from the list.Its because images will be shown from 1 index because index 0 is occupied by your + icon. And yes you have to create two veiwholders too for their respective functionalities.

You need to create an adapter that supports two types of items - photo one and '+' one. Then add special '+' item at first position in the list that you provide to the adapter.

Check this link: “ A RecyclerView with multiple item types ” by Vitaly Vivchar.

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