notifyDataSetChanged无法正确刷新ListFragment UI

时间:2019-11-16 21:00:23

标签: android kotlin android-listfragment

我有一个带有自定义适配器的ListFragment。当我在适配器上调用notifyDataSetChanged()时,列表会在内部刷新,但只有在手动拉下页面进行刷新或从其导航到该页面之后,UI才会刷新。

如何在notifyDataSetChanged()调用后立即刷新UI?

这是我的ListFragment的代码

class ListFragment(): ListFragment() {
    var list = ArrayList<MainActivity.ListItem>()

    constructor(list: ArrayList<MainActivity.ListItem>): this() {
        this.list = list
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        listAdapter = ListViewAdapter()
    }

    fun updateList(list: ArrayList<MainActivity.ListItem>) {
        this.list.clear()
        this.list.addAll(list)
        (listAdapter as ArrayAdapter<*>).notifyDataSetChanged()
    }

    internal lateinit var callback: OnListItemClickListener
    fun setOnListItemClickListener(callback: OnListItemClickListener) {
        this.callback = callback
    }
    interface OnListItemClickListener {
        fun onListItemClick(uri: String, title: String)
    }

    override fun onListItemClick(l: ListView, v: View, position: Int, id: Long) {
        callback.onListItemClick(list[position].uri, list[position].title)
    }

    inner class ListViewAdapter : BaseAdapter() {
        override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View? {
            val view: View?
            val vh: ViewHolder

            if (convertView == null) {
                view = layoutInflater.inflate(R.layout.listview_item, parent, false)
                vh = ViewHolder(view)
                view.tag = vh
            } else {
                view = convertView
                vh = view.tag as ViewHolder
            }
            vh.textView.text = list[position].title

            return view
        }

        override fun getItem(position: Int): Any {
            return list[position]
        }

        override fun getItemId(position: Int): Long {
            return position.toLong()
        }

        override fun getCount(): Int {
            return list.size
        }
    }

    private class ViewHolder(view: View?) {
        val textView = view?.findViewById(R.id.textView) as TextView
    }
}

0 个答案:

没有答案