Как использовать таймер в recyclerView на Android - PullRequest
0 голосов
/ 05 февраля 2019

Почему бы не помочь мне с людьми ???

В моем приложении я хочу показать Таймер в пунктах recyclerView!
Я пишуниже коды с Kotlin язык, но когда прокрутка recyclerView таймеры сброшены и начать снова с startTime непродолжить!
Моя проблема в таймер сброс, я хочу, чтобы при прокрутке recyclerView элементы, таймеры не были сброшены, и я хочу продолжить таймер !

Мои коды адаптеров:

class AuctionsTodayAdapter(val context: Context, val model: MutableList<AuctionsTodayResponse.Res.Today>) :
    RecyclerView.Adapter<AuctionsTodayAdapter.MyHolder>() {

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyHolder {
        val view = LayoutInflater.from(context).inflate(R.layout.row_bidzila_list, parent, false)
        return MyHolder(view)
    }

    override fun getItemCount(): Int {
        return model.size
    }

    override fun onBindViewHolder(holder: MyHolder, position: Int) {
        val modelUse = model[position]
        holder.setData(modelUse)
    }

    override fun onViewAttachedToWindow(holder: MyHolder) {
        val pos = holder.adapterPosition
        val modelUse = model[pos]
        holder.handler.post { holder.timer(modelUse.calculateEnd, 1000) }
    }

    override fun onViewDetachedFromWindow(holder: MyHolder) {
        if (holder.timmer != null) {
            holder.timmer.cancel()
        }
    }

    inner class MyHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {

        var handler = Handler(Looper.getMainLooper())
        lateinit var timmer: CountDownTimer

        fun setData(model: AuctionsTodayResponse.Res.Today) {
            model.image.let {
                Glide.with(context)
                    .load(Constants.BIDZILA_BASE_URL + it)
                    .apply(RequestOptions.diskCacheStrategyOf(DiskCacheStrategy.RESOURCE))
                    .into(itemView.rowBidzila_img)
            }
            model.title.let { itemView.rowBidzila_title.text = it }
        }

        fun timer(millisInFuture: Long, countDownInterval: Long): CountDownTimer {
            timmer = object : CountDownTimer(millisInFuture * 1000, countDownInterval) {
                override fun onTick(millisUntilFinished: Long) {
                    var seconds = (millisUntilFinished / 1000).toInt()
                    val hours = seconds / (60 * 60)
                    val tempMint = seconds - hours * 60 * 60
                    val minutes = tempMint / 60
                    seconds = tempMint - minutes * 60
                    itemView.rowBidzila_timer.rowBidzila_timer.text =
                        String.format("%02d", hours) + ":" + String.format(
                            "%02d",
                            minutes
                        ) + ":" + String.format("%02d", seconds)
                }

                override fun onFinish() {
                    itemView.rowBidzila_timer.rowBidzila_timer.text = "Finished"
                }
            }.start()

            return timmer
        }
    }
}

Мои модели:

data class Today(
    @SerializedName("auction_status")
    val auctionStatus: String = "", // accept
    @SerializedName("base_price")
    val basePrice: Int = 0, // 120000
    @SerializedName("bid_number")
    val bidNumber: Int = 0, // 1
    @SerializedName("calculate_end")
    var calculateEnd: Long = 0, // -9815
    @SerializedName("can_offer_before")
    val canOfferBefore: Int = 0, // 1
    @SerializedName("capacity")
    val capacity: Int = 0, // 25
    @SerializedName("current_price")
    val currentPrice: Int = 0, // 224000
    @SerializedName("discount")
    val discount: Int = 0, // 400000
    @SerializedName("end")
    val end: Int = 0, // 1548650312
    @SerializedName("end_date")
    val endDate: String = "", // 2019-01-28 08:08:32
    @SerializedName("end_time")
    val endTime: String = "", // 2019-01-28 08:08:32
    @SerializedName("final_discount")
    val finalDiscount: Int = 0, // 176000
    @SerializedName("final_price")
    val finalPrice: Int = 0, // 224000
    @SerializedName("id")
    val id: Int = 0, // 2629
    @SerializedName("image")
    val image: String = "", // /img/product/5bd94ed3cb9d2.png
    @SerializedName("lastbid")
    val lastbid: Any = Any(), // null
    @SerializedName("live")
    val live: String = "",
    @SerializedName("max_price")
    val maxPrice: Int = 0, // 240000
    @SerializedName("max_price_percent")
    val maxPricePercent: Int = 0, // 60
    @SerializedName("name")
    val name: String = "",
    @SerializedName("number_of_users")
    val numberOfUsers: Int = 0, // 14
    @SerializedName("order")
    val order: Int = 0, // 0
    @SerializedName("price")
    val price: Int = 0, // 400000
    @SerializedName("product_id")
    val productId: Int = 0, // 671
    @SerializedName("registered")
    val registered: String = "", // null
    @SerializedName("registereduser")
    val registereduser: Int = 0, // 14
    @SerializedName("second_image")
    val secondImage: String = "",
    @SerializedName("start_date")
    val startDate: String = "", // 2019-01-28 08:00:00
    @SerializedName("tag")
    val tag: String = "",
    @SerializedName("tag_color")
    val tagColor: String = "", // ff3232
    @SerializedName("tag_description")
    val tagDescription: String = "",
    @SerializedName("title")
    val title: String = "",
    @SerializedName("winner_avatar")
    val winnerAvatar: String = "", // /img/avatar/009-social-11.png
    @SerializedName("winner_id")
    val winnerId: Int = 0, // 57582
    @SerializedName("winner_name")
    val winnerName: String = "", // Arashr1

    val running: Boolean = true,
    var thread: Thread
) {
    init {
        thread = Thread(Runnable {
            while (running) {
                calculateEnd--
                try {
                    Thread.sleep(1000)
                } catch (e: InterruptedException) {
                    e.printStackTrace()
                }
            }
        })
        thread.start()
    }
}

Как я могу это исправить?

1 Ответ

0 голосов
/ 05 февраля 2019

Вы можете использовать модель.И в этой модели вы можете установить последнее подсчитанное значение.и в вашем ViewHolder вы начнете время с последнего подсчитанного значения вашей модели.Я надеюсь, что вы понимаете

...