0
我處理了幾天的問題。我有類似於在recyclerView中的秒錶(擁有秒錶的用戶列表)。問題是,我不知道如何在BindViewHolder上同步它,以及如何將每秒1秒添加到他們的時間。 編輯:我添加了秒錶類,並實施它。它運行良好,但是當我滾動時,一切都很混亂。任何想法如何改善?recyclerView中的秒錶
我的適配器
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([email protected]) {
if (isRunning) {
listener?.onTick([email protected]())
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() {
...
}
}
我剛剛測試過coutdown,它工作得很好,不幸的是它的做法相反:D您能否製作一些片段? – Stepan