I have managed to create an automatic layout update. I have a list of CardView
that is displayed inside a RecyclerView
. Upon clicking a CardView
, said CardView
will expand and cause other potentially expanded CardView
to retract. I have managed to do that by:
- Maintaining a variable that holds the position of the
CardView
to be expanded inside myRecyclerView
's adapter - Updating said variable when a click happens inside any of the
CardView
- If another
CardView
is expanded, retract the previousCardView
and expand the newly clickedCardView
The code of doing the above can be seen below:
// Inside RecyclerView.Adapter
private var expandedViewHolder = -1
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val cardView = LayoutInflater.from(parent.context)
.inflate(R.layout.recyclerview_cardview, parent, false) as CardView
val holder = ViewHolder(cardView)
cardView.setOnClickListener {
notifyItemChanged(expandedPosition)
expandedPosition = if (expandedPosition == holder.adapterPosition) -1 else holder.adapterPosition
notifyItemChanged(expandedPosition)
}
return holder
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
holder.headline.text = dataset[position].name
holder.desc.text = dataset[position].desc
if (position == expandedPosition) {
holder.desc.visibility = View.VISIBLE
}
else {
holder.desc.visibility = View.GONE
}
}
As can be seen, I am forcing the RecyclerView
to re-trigger onBindViewHolder
using notifyItemChanged()
. Inside onBindViewHolder
, a CardView
's description's visibility is going to be altered accordingly. onBindViewHolder
automatically redraws the new layout with an automatic transition/animation.
However, there is a slight problem with retraction when a CardView
is expanded and another is retracted like below (note that expanding and retracting one CardView
creates no problem):
If you look closely, upon retraction, the text is partially visible when the CardView
's height is fully retracted. Ideally, I want the text to be invisible (alpha set to 0) much faster (like probably 10ms). Thus, my questions are:
- How do I smoothly retract a
CardView
while expanding anotherCardView
and adjusting the duration of the alpha value? (The problem, as can be seen from the gif, is that the animation is visually unappealing.) - Is there a better way to achieve the simple animation I want besides using
notifyItemChanged
that re-triggersonBindViewHolder
?
Here's a clearer picture of what I mean by the text's visibility being partially visible: