RecyclerView适配器不会在notifyDataSetChanged()(不是Collection)上更新

时间:2019-02-08 09:24:45

标签: android kotlin android-recyclerview recycler-adapter

这是我第一次遇到此问题,它与ArrayList,List或任何种类的集合无关-与Int有关。

我正在使用Kotlin和Moxy的Presenter初始化适配器。 这是我初始化的方式:

adapter = WeeksAdapter(context, weeks, chosenWeekPosition, this)

这是我的WeeksAdapter部分:

    class WeeksAdapter (private val context: Context, private val weeks: ArrayList<WeekChoice>, var chosenPosition: Int, private val listener: OnCurrentWeekChangedListener):
        RecyclerView.Adapter<WeeksAdapter.ViewHolder>() {
        override fun onBindViewHolder(holder: ViewHolder, position: Int) {
            val week = weeks[position]
            holder.tv.background = context.resources.getDrawable(
                if (position == chosenPosition) R.drawable.week_circle_background_active else  R.drawable.week_circle_background_inactive , null)
            holder.tv.setTextColor( context.resources.getColor ( if (position == chosenPosition) android.R.color.white else  R.color.textColor ))
            holder.tv.text = "${week.numberOfWeek}"
            holder.tv.setOnClickListener {
                listener.onWeekClick(position)
            }
        }
}

因此,当我在演示者中更改selectedPosition字段并调用adapter?.notifyDataSetChanged()时-selectedPosition不会在适配器中更改或更新-我在调试中检查了它-不会更改。

请问我该如何解决

2 个答案:

答案 0 :(得分:0)

我不熟悉此演示者,但您的selectedPosition不变。创建适配器后,它不会更改。您需要对其进行更新的功能

class WeeksAdapter (private val context: Context, private val weeks: ArrayList<WeekChoice>, var chosenPosition: Int, private val listener: OnCurrentWeekChangedListener):
        RecyclerView.Adapter<WeeksAdapter.ViewHolder>() {


    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val week = weeks[position]
        holder.tv.background = context.resources.getDrawable(
                if (position == chosenPosition) R.drawable.week_circle_background_active else  R.drawable.week_circle_background_inactive , null)
        holder.tv.setTextColor( context.resources.getColor ( if (position == chosenPosition) android.R.color.white else  R.color.textColor ))
        holder.tv.text = "${week.numberOfWeek}"
        holder.tv.setOnClickListener {
            listener.onWeekClick(position)
        }
    }

    fun updatePosition(newPosition: Int) {
        chosenPosition = newPosition
    }
}

通过此函数更新位置,然后调用适配器?.notifyDataSetChanged()

答案 1 :(得分:0)

从UI线程中调用notifyDataSetChanged()。