简体   繁体   中英

Most efficient way of having two different layouts in Android RecyclerView

im working on a chat layout and i need TWO "different" layouts for send & received messages. The 2 layouts are almost the same, so it could be posible to have just one and dynamically change its background and some of its gravity/margin/padding properties.

After working with RecyclerView i have a doubt about efficiency. To achieve my goal i see two approaches:

  1. Use 1 view and modify it programatically inside onBindViewHolder()
  2. Use 2 view types.
  3. ¿Any more efficient way?

After searching a bit, i am not sure what is the best and most efficient approach here, so some expert advise would be nice. Thank you.

PD: Backgrounds are 9patch images and in scenario 1, im loading them using getResources() and setBackground(). Scroll feels a bit slow on old devices.

This functionality is actually built into RecyclerView. You will notice that the method signature for createViewHolder is createViewHolder(ViewGroup parent, int viewType) . The viewType is in fact what you need. To do this, you override getItemViewType so that depending on the position, it returns a different integer for sent or received messages. This will allow you to, in createViewHolder create a simple switch statement to pick the appropriate view type.

@Override
public int getItemViewType(int position) {
        if(listOfMessages.get(position).isSentMessage())
           return 1;
        else
           return 2;
}

@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType){
        if(viewType == 1)
            //inflate sent message layout
        else if(viewType == 2)
            //inflate received message layout.
}

First of all, measure and see if it is critical session worth effort.

After that, it is generally a good practice to merge types unless it is costly to swap them. Just changing the background should be fine. Framework will mutate an already cached drawable id but I'm not sure how cheap it will be depending on your drawable. If it turns out to be expensive, you can recycle those background drawables manually.

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