![](/img/trans.png)
[英]Android: Images in recycler view item shuffle a lot on scrolling fast
[英]Recycler View with images lags a lot
我正在從我的應用程序內的本地數據庫中獲取數據。 數據庫有 43 行,所以它不是一個很長的列表。 這是我的代碼中獲取數據的部分:
fun readAllPoets(): ArrayList<Poet> {
val poetList: ArrayList<Poet> = arrayListOf<Poet>()
val db = readableDatabase
val stringQuery = "SELECT * FROM info"
val cursor: Cursor = db.rawQuery(stringQuery,null)
var poetid: String
var faname: String
var enname: String
while (cursor.moveToNext()) {
poetid = cursor.getString(cursor.getColumnIndex(DBPoet.UserEntry.COLUMN_POET_ID))
faname = cursor.getString(cursor.getColumnIndex(DBPoet.UserEntry.COLUMN_FANAME))
enname = cursor.getString(cursor.getColumnIndex(DBPoet.UserEntry.COLUMN_ENNAME))
poetList.add(Poet(poetid, faname, enname))
}
cursor.close()
return poetList
}
然后在 MainActivity 我調用這個函數:
private fun fetchPoets() {
poetList = DBHelper.UsersDBHelper(this).readAllPoets()
rvPoetList.layoutManager = LinearLayoutManager(this)
poetList.forEach {
it.imageId = this.baseContext.resIdByName(it.enName.toLowerCase(),"drawable")
}
val adapter = PoetListAdapter()
adapter.setData(poetList)
rvPoetList.adapter = adapter
}
如您所見,我正在將圖片資源 ID 添加到我的 Poet 對象。 沒有從互聯網下載。 一切都是本地的。 這是我的適配器代碼:
class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
fun bind(poet: Poet) {
itemView.poet_title.setText(poet.faName)
itemView.img_poet.setImageResource(poet.imageId)
}
}
fun setData(poets: List<Poet>) {
this.poets = poets
notifyDataSetChanged()
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val view = LayoutInflater.from(parent.context)
.inflate(R.layout.single_poet_view, parent, false)
return ViewHolder(view)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
poets?.get(position)?.let { poet ->
holder.bind(poet)
}
holder.itemView.setOnClickListener { v ->
listener?.onItemClickListener(v, holder.layoutPosition)
}
}
正如你所看到的,我並沒有經常調用 R.id,我知道這是一個代價高昂的調用,它使回收者視圖滯后。 即使一切都是本地的,我在本地獲取的圖像相當小(每個大約 150kb)而且我沒有經常調用 R.id,滾動時它仍然很滯后。 那么這里的問題是什么?
以 kb 為單位的 jpeg 大小與其以像素為單位的大小幾乎沒有聯系,因此 10 kb jpeg 很容易成為 10_000*10_000 圖像,操作系統必須分配適當數量的 ram 來創建位圖。 這是昂貴的並且需要時間。 此外,如果您查看ImageView::setImageResource文檔,您可以看到一條注釋This does Bitmap reading and decoding on the UI thread, which can cause a latency hiccup. If that's a concern, consider using setImageDrawable(android.graphics.drawable.Drawable) or setImageBitmap(android.graphics.Bitmap) and BitmapFactory instead.
This does Bitmap reading and decoding on the UI thread, which can cause a latency hiccup. If that's a concern, consider using setImageDrawable(android.graphics.drawable.Drawable) or setImageBitmap(android.graphics.Bitmap) and BitmapFactory instead.
為了克服麻煩,您可以簡單地使用圖像加載庫,例如畢加索
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.