Recyclerview的AsyncLayout膨胀

时间:2018-12-05 11:18:17

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

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

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

我想知道recyclerview是否有任何方法可以达到相同的目的。 我面临的问题是在异步完成之前调用onbindviewholder。

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分: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 {

    }
}