RecyclerView how to pass the data to two different layouts?

0

Good I have two layouts created odd and even in the form of a card and I want them to be sent according to odd or even the position to the main layout that would be the recyclerView and I do not know how to work the adapter so that I can only send the data to 1 layout.

class AdaptadorCustumon(var contexto: Context, items: ArrayList<BookItem>): RecyclerView.Adapter<AdaptadorCustumon.ViewHolder>() {

  var items:ArrayList<BookItem>? = null
  var viewHolder : ViewHolder? = null
  init {
    this.items = items
  }

  override fun onCreateViewHolder(parent: ViewGroup, viewType : Int): AdaptadorCustumon.ViewHolder {

    val vista = LayoutInflater.from(contexto).inflate(R.layout.card_impar, parent,false)

    viewHolder = ViewHolder(vista)

    return  viewHolder!!

  }

  override fun getItemCount(): Int {
    return this.items?.count()!!
  }

  override fun onBindViewHolder(holder :ViewHolder, position: Int) {

    val item = items?.get(position)

    holder.autor?.text = item?.autor
    holder.titulo?.text = item?.titulo
  }

  class ViewHolder(vista : View) : RecyclerView.ViewHolder(vista){

    var vista = vista

    var autor : TextView? = null
    var titulo : TextView? = null

    init {
      titulo = vista.findViewById(R.id.tvTitulo1)
      autor = vista.findViewById(R.id.tvAutor1)
    }
  }
}
    
asked by Daniel Montil 29.09.2018 в 19:38
source

1 answer

0

If what you want is to use a layout for items in even positions and another layout for items in odd positions you will have to use the parameter viewType of onCreateViewHolder and thus decide which layout you should use.

To be able to use the viewType you must implement in the adapter the method of getItemViewType where from the position you can return the viewType that you would then use in onCreateViewHolder

override fun getItemViewType(position: Int): Int {
   return position % 2;//0 si es par y 1 si es impar
}

override fun onCreateViewHolder(parent: ViewGroup, viewType : Int): AdaptadorCustumon.ViewHolder {

    val vista:View
    if (viewType == 0) {
        vista = LayoutInflater.from(contexto).inflate(R.layout.card_par, parent, false)
    }else{
        vista = LayoutInflater.from(contexto).inflate(R.layout.card_impar, parent, false)
    }
    viewHolder = ViewHolder(vista)

    return  viewHolder!!
}
    
answered by 03.10.2018 / 17:48
source