我的适配器将图像正确地应用于RecyclerView并正确滚动...直到添加大量项目为止。然后,它变得非常不稳定,我知道这是我的方法的问题。请参见下面的代码:
class FragmentMenuViewAdapter(private val menuItems: ArrayList<MenuItemModel>, private val clickListener: (MenuItemModel) -> Unit) : RecyclerView.Adapter<FragmentMenuViewAdapter.CustomViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CustomViewHolder {
val policy = StrictMode.ThreadPolicy.Builder().permitAll().build()
StrictMode.setThreadPolicy(policy)
val layoutInflater = LayoutInflater.from(parent.context)
val cellForRow = layoutInflater.inflate(R.layout.recyclerview_list_items, parent, false)
return CustomViewHolder(cellForRow)
}
override fun getItemCount(): Int {
return menuItems.size
}
override fun onBindViewHolder(holder: CustomViewHolder, position: Int) {
var menuItemIconURI = RouteManager.mAppModel?.resourcesURL + menuItems[position].icon
menuItemIconURI = menuItemIconURI.replace("\$platform", "iOS")
menuItemIconURI = menuItemIconURI.replace("\$scale", "@3x")
val inputStream = URL(menuItemIconURI).openStream()
holder.view.menuButton.setImageBitmap(BitmapFactory.decodeStream(inputStream))
holder.bind(menuItems[position], clickListener)
}
class CustomViewHolder(val view: View): RecyclerView.ViewHolder(view) {
fun bind(menuItem: MenuItemModel, clickListener: (MenuItemModel) -> Unit) {
view.setOnClickListener{clickListener(menuItem)}
}
}
}
正在通过URL链接设置图像。我可以使用它,但是我怀疑我在某个地方犯了新手错误,或者只是采取了错误的方法。任何有关如何调整我的代码的建议将不胜感激。
答案 0 :(得分:1)
我认为问题出在主线程中解码位图图像。尝试改用Glide
。它有助于我们在需要时异步加载图像。例如,如果您想快速滚动RecyclerView
,则不需要解码并显示所有图像。此外,它还具有缓存机制以使此过程更流畅。
build.gradle
dependencies {
implementation 'com.github.bumptech.glide:glide:4.7.1'
}
FragmentMenuViewAdapter.kt
override fun onBindViewHolder(holder: CustomViewHolder, position: Int) {
var menuItemIconURI = RouteManager.mAppModel?.resourcesURL + menuItems[position].icon
menuItemIconURI = menuItemIconURI.replace("\$platform", "iOS")
menuItemIconURI = menuItemIconURI.replace("\$scale", "@3x")
Glide.with(holder.view.menuButton.context)
.load(menuItemIconURI)
.into(holder.view.menuButton)
holder.bind(menuItems[position], clickListener)
}