【问题标题】:AsyncLayout Inflation for RecyclerviewRecyclerview 的 AsyncLayout 膨胀
【发布时间】:2018-12-05 11:18:17
【问题描述】:

我在单屏中使用两个 recyclerview(适用于 android TV)。每个 recyclerview 都有复杂的布局项。加载需要时间。我在活动中使用 asynclayoutinflator。

    AsyncLayoutInflater inflater = new AsyncLayoutInflater(this);
    inflater.inflate(R.layout.main, null, callback);

我想知道是否有任何方法可以通过 recyclerview 实现相同的效果。 我面临的问题是在 asyncinflation 完成之前调用了 onbindviewholder。

【问题讨论】:

    标签: android asynchronous android-recyclerview layout-inflater android-inflate


    【解决方案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)
            }
        }
    }
    

    使用方法:

    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】:

    不知道这是否正是您要找的东西,但我正在考虑在充气机完成工作后将这些物品放入您的回收站适配器中。这样,在 inflate(...) 方法之前,您的适配器 getCount() 将返回 0 并且不会再调用 onBindViewHolder。

    【讨论】:

    • 是的。这是我面临的问题。有什么方法可以对我的 recyclerview 项目布局进行背景膨胀?
    • @yadunath.narayanan 你可以做的是 onCreateViewHolder 返回一个带有空 FrameLayout 的视图持有者,同时在回调中使用 frameLayout.addView(asyncInflatedView) 启动异步通胀。如果视图在通货膨胀完成之前被回收,我可以想象一些潜在的赛车问题(只是提一下)
    猜你喜欢
    • 2022-09-30
    • 2015-04-13
    • 2021-08-30
    • 1970-01-01
    • 2017-11-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-18
    相关资源
    最近更新 更多