I am working with two recyclerview in single screen(For android TV).Each recyclerview have complex layout item.And it's taking time to load.I worked with asynclayoutinflator in activities.
AsyncLayoutInflater inflater = new AsyncLayoutInflater(this);
inflater.inflate(R.layout.main, null, callback);
I want to know whether there is any ways to achieve the same with recyclerview. Problem I am facing is onbindviewholder is getting called before asyncinflation finished.
import android.content.Context
import android.util.AttributeSet
import android.view.View
import android.view.ViewGroup.LayoutParams.MATCH_PARENT
import android.widget.FrameLayout
import androidx.asynclayoutinflater.view.AsyncLayoutInflater
class AsyncFrameLayout @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0,
defStyleRes: Int = 0
) : FrameLayout(
context,
attrs,
defStyleAttr,
defStyleRes
) {
init {
layoutParams = LayoutParams(MATCH_PARENT, MATCH_PARENT)
}
private var isInflated = false
private var pendingActions: MutableList<AsyncFrameLayout.() -> Unit> = ArrayList()
fun inflateAsync(layoutResId: Int) {
AsyncLayoutInflater(context).inflate(layoutResId, this) { view, _, _ ->
addView(view)
isInflated = true
pendingActions.forEach { action -> action() }
pendingActions.clear()
}
}
fun invokeWhenInflated(action: AsyncFrameLayout.() -> Unit) {
if (isInflated) {
action()
} else {
pendingActions.add(action)
}
}
}
How to use:
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
val itemView = AsyncFrameLayout(parent.context)
itemView.inflateAsync(R.layout.my_layout)
return MyViewHolder(itemView)
}
override fun onBindViewHolder(viewHolder: MyViewHolder, position: Int) {
viewHolder.itemView.invokeWhenInflated {
}
}
Don't know if it's exactly what you're looking for but I am thinking about setting the items in your recycler's adapter after the inflater done his job. This way, before the inflate(...) method your adapter getCount() will return 0 and onBindViewHolder will not be called anymore.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With