Recyclerview的AsyncLayout膨胀 [英] AsyncLayout Inflation for Recyclerview

查看:130
本文介绍了Recyclerview的AsyncLayout膨胀的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在单个屏幕上使用两个recyclerview(用于android TV).每个recyclerview都有复杂的布局项目.加载时间很长.我在活动中使用了asynclayoutinflator.

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);

我想知道用recyclerview是否有任何方法可以达到相同的效果.我面临的问题是在异步结束之前调用onbindviewholder.

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)
        }
    }
}

使用方法:

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 {

    }
}

这篇关于Recyclerview的AsyncLayout膨胀的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆