In my RecyclerView
OnLongClicking an item I want to change that item's layout by setting some TextViews
to View.GONE
and others to View.VISIBLE
. Everything works except that when I long press the item and the layout changes my RecyclerView
scrolls to top and I can no longer see the LongPressed view if it was at the bottom.
This is ListAdapter
that I wrote:
class AssetsListAdapter(
private val onAssetClickListener: OnAssetClickListener,
private val onAssetLongClickListener: OnAssetLongClickListener
) :
ListAdapter<Asset, AssetsListAdapter.ViewHolder>(
AssetDiffCallback()
) {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val inflater = LayoutInflater.from(parent.context)
return ViewHolder(
inflater.inflate(
R.layout.list_item,
parent,
false
)
)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
holder.bind(getItem(position), onAssetClickListener, onAssetLongClickListener)
}
class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
fun bind(
asset: Asset,
onAssetClickListener: OnAssetClickListener,
onAssetLongClickListener: OnAssetLongClickListener
) {
itemView.item_name.text = asset.name
// Set icons relatively to category
when (asset.category) {
"Cash" -> itemView.item_image.setImageResource(R.drawable.ic_cash)
"Bank Account" -> itemView.item_image.setImageResource(R.drawable.ic_bank)
"Investment" -> itemView.item_image.setImageResource(R.drawable.ic_invest)
"Salary" -> itemView.item_image.setImageResource(R.drawable.ic_job)
}
itemView.setOnClickListener {
onAssetClickListener.onAssetClick(asset)
}
// On long click listeners pulls up quick action options
itemView.setOnLongClickListener {
view.item_end_text.visibility = View.GONE
view.quick_actions_layout.visibility = View.VISIBLE
onAssetLongClickListener.onAssetLongClick(asset, itemView)
true
}
}
}
class AssetDiffCallback : DiffUtil.ItemCallback<Asset>() {
override fun areItemsTheSame(oldItem: Asset, newItem: Asset): Boolean {
return oldItem.assetId == newItem.assetId
}
override fun areContentsTheSame(oldItem: Asset, newItem: Asset): Boolean {
return oldItem == newItem
}
}
interface OnAssetClickListener {
fun onAssetClick(asset: Asset)
}
interface OnAssetLongClickListener {
fun onAssetLongClick(asset: Asset, view: View)
}
}
Ok, so I found out that if you set View.GONE
the whole item is redrawn and it resets the RecyclerView
? Because setting it to View.INVISIBLE
solves the issue.
itemView.setOnLongClickListener {
view.item_end_text.visibility = View.GONE
view.quick_actions_layout.visibility = View.VISIBLE
onAssetLongClickListener.onAssetLongClick(asset, itemView)
true
}
to
itemView.setOnLongClickListener {
view.item_end_text.visibility = View.INVISIBLE
view.quick_actions_layout.visibility = View.VISIBLE
onAssetLongClickListener.onAssetLongClick(asset, itemView)
true
}