AsyncLayout Inflation for Recyclerview

匆匆过客 提交于 2021-02-07 08:08:40

问题


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.


回答1:


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 {

    }
}



回答2:


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.



来源:https://stackoverflow.com/questions/53631079/asynclayout-inflation-for-recyclerview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!