RecyclerView.Adapter和spanCount大于4的GridLayoutManager连续重新创建ViewHolders

时间:2018-10-26 10:30:34

标签: android android-recyclerview android-viewholder recyclerview-layout gridlayoutmanager

我正在使用GridLayoutManager,并且遇到了意外的RecyclerView行为。如果spanCount大于4,则RecyclerView会在滚动时连续重新创建ViewHolders。

    override fun onCreate(savedInstanceState: Bundle?) {
       super.onCreate(savedInstanceState)
       setContentView(R.layout.main_activity)

       val recyclerView = findViewById<RecyclerView>(R.id.recyclerView)
       recyclerView.layoutManager = GridLayoutManager(this, 7)
       recyclerView.adapter = Adapter()
   }

   private class Adapter : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
       //continuously invokes while scrolling:
       override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
           val view:View = TextView(parent.context).apply {
               text = "Hello!"
           }
           return object : RecyclerView.ViewHolder(view) {}
       }

       override fun getItemCount(): Int = 3500

       override fun onBindViewHolder(viewHolder: RecyclerView.ViewHolder, position: Int) {}
   } 

如何修复它并强制RecyclerView.Adapter重用ViewHolders?

1 个答案:

答案 0 :(得分:0)

我用以下代码复制了您的问题(可复制粘贴,不需要资源文件):

class RecActivity : AppCompatActivity() {
    lateinit var recyclerView: RecyclerView

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        recyclerView = RecyclerView(this)
        setContentView(recyclerView)
        recyclerView.layoutManager = GridLayoutManager(this, 7)
        recyclerView.adapter = Adapter()
    }

    inner class Adapter : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
        var vhCount = 0
        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
            val txtView = AppCompatTextView(this@RecActivity)
            txtView.tag = vhCount++.toString()
            txtView.gravity = Gravity.CENTER
            title = vhCount.toString()  // display # of created VHs in title
            return object : RecyclerView.ViewHolder(txtView){}
        }

        override fun getItemCount() = 3500

        override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
            (holder.itemView as TextView).text = "$position (${holder.itemView.tag})"
        }
    }
}

问题是没有足够的视图来填充RecycledViewPool中的整个行。默认情况下,每个ViewType仅包含5个项目,因此,如果有7行很宽的行,则会在滚动时强制创建更多ViewHolders。要解决此问题,只需增加RecycledViewPool的大小即可(在onCreate中):

recyclerView.layoutManager = GridLayoutManager(this, 7)
recyclerView.adapter = Adapter()
// add line below: 0 is default itemViewType, 14 is two rows of items which should be enough
recyclerView.recycledViewPool.setMaxRecycledViews(0, 14)