[英]How to get previous position in RecyclerView's Adapter itself?
I'm having a RecyclerView, inside its layout there's a view "tvDateGrouped", I want it to be displayed only when the current position date and previous position date are not same.我有一个 RecyclerView,在它的布局中有一个视图“tvDateGrouped”,我希望它仅在当前 position 日期和以前的 position 日期不同时显示。 Below is the code I tried, but it isn't working
以下是我尝试过的代码,但它不起作用
This Code is inside the adapter class, inside the onBind() method此代码在适配器 class 内,在 onBind() 方法内
if (position != 0 && transactions[position].date ==
transactions[holder.adapterPosition.minus(1)].date) {
holder.view.tvDateGrouped.visibility = View.GONE
} else {
holder.view.tvDateGrouped.text = formattedDateString
}
and if I change position,= 1 , the app crashes如果我更改 position,= 1 ,应用程序崩溃
below is the code when app crashes以下是应用程序崩溃时的代码
if (position != 1 && transactions[position].date ==
transactions[holder.adapterPosition.minus(1)].date) {
holder.view.tvDateGrouped.visibility = View.GONE
} else {
holder.view.tvDateGrouped.text = formattedDateString
}
Edit: I've changed the code as the below, but the app is crashing now-编辑:我已将代码更改如下,但应用程序现在崩溃了-
if ((transactions[position].date == transactions[position - 1].date) &&
(position > 0)) {
holder.view.tvDateGrouped.visibility = View.GONE
} else {
holder.view.tvDateGrouped.visibility = View.VISIBLE
holder.view.tvDateGrouped.text = formattedDateString
}
Please Help me resolve this issue请帮我解决这个问题
Your crash is simply happening when position
is 0
then position - 1
will be -1
which is an invalid index and you will get a runtime exception.当
position
为0
然后position - 1
将为-1
时,您的崩溃只是发生了,这是一个无效索引,您将获得运行时异常。
But why the first solution isn't working?但是为什么第一个解决方案不起作用? One clear reason is because you've forgotten to make the text visible again.
一个明显的原因是因为您忘记让文本再次可见。 So change it to:
所以改成:
if (position > 0 && transactions[position].date == transactions[position - 1].date) {
holder.view.tvDateGrouped.visibility = View.GONE
} else {
holder.view.tvDateGrouped.visibility = View.VISIBLE
holder.view.tvDateGrouped.text = formattedDateString
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.