我处理问题好几天了。我在recyclerView(具有秒表的用户列表)中有类似秒表的东西。问题是我不知道如何在onBindViewHolder上同步它以及如何将每秒1秒添加到他们的时间。 编辑:我添加了秒表类并实现了它。它工作得很好,但是当我滚动时,一切都很混乱。任何想法如何改进它?
我的适配器
class DashboardAdapter(var context: Context?) : RecyclerView.Adapter<DashboardAdapter.MyViewHolder>() {
lateinit var dataSource: List<User>
class MyViewHolder(view: View) : RecyclerView.ViewHolder(view) {
var stopwatch: Stopwatch? = null
val name = view.findViewById(R.id.name) as TextView
val avatar = view.findViewById(R.id.profile_image) as ImageView
val project = view.findViewById(R.id.project) as TextView
val playImage = view.findViewById(R.id.play) as ImageView
val time = view.findViewById(R.id.time) as TextView
val placement = view.findViewById(R.id.placement) as TextView
}
override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
holder.stopwatch = Stopwatch(object : Stopwatch.StopWatchListener {
override fun onTick(time: String) {
holder.time.text = time
}
})
holder.stopwatch?.start(time.toLong())
}
override fun getItemCount(): Int = dataSource.size
override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): MyViewHolder {
val itemView = LayoutInflater.from(parent?.context).inflate(R.layout.item_dashboard_workers, parent, false)
return MyViewHolder(itemView)
}
private fun getRealHolderPosition(viewHolder: MyViewHolder) : Int = viewHolder.adapterPosition + 1
fun setUsers(dataSource: List<User>) {
this.dataSource = dataSource
}
}
秒表:
class Stopwatch(listener: StopWatchListener) {
interface StopWatchListener {
fun onTick(time: String)
}
private val DELAY : Long = 1000
private var startTime: Long = 0
var isRunning = false
private set
private var currentTime: Long = 0
...
/**
* Starts the stopwatch from an offset
* @param offset The offset in milli seconds
*/
fun start(offset: Long) {
stop()
this.startTime = System.currentTimeMillis() - offset
this.isRunning = true
val handler = Handler()
handler.post(object : Runnable {
override fun run() {
//lock to access running
synchronized(this@Stopwatch) {
if (isRunning) {
listener?.onTick(this@Stopwatch.toString())
handler.postDelayed(this, DELAY)
}
}
}
})
}
@Synchronized
private fun stop() {
this.isRunning = false
}
private fun restart() {
this.stop()
this.start()
}
@Synchronized
private fun pause() {
...
}
private fun resume() {
...
}
}
答案 0 :(得分:-1)
你可以使用具有1000毫秒后延迟的Runnable,每次运行时调用增量秒表/调用Notifydatasetchanged();