使用Recyclerview儿童使用构造函数而不是膨胀以创建它们时,请匹配父母的高度



我试图拥有一个带有自定义子视图(CustomView)的回收库。自定义子查看中有一些有限的视图逻辑,这就是为什么我不想将其夸大为View,而是将其构建为专用视图(CustomView)。

我声明了我的CustomView的布局:

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_margin="20dp"
    app:cardCornerRadius="5dp">
<!-- ... -->
</android.support.v7.widget.CardView>

CustomView的构造函数看起来像:

inflate(context, R.layout.layout_custom_view, this)

onCreateViewHolder然后构造视图:

override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): CustomViewHolder {
            val view = CustomView(parent!!.context)
            val viewHolder = ...
            return viewHolder
}

通常运行良好。但是,我的CustomView应该与Recylerview的高度和宽度相匹配,但只需呈现渲染即可。

我如何使CustomView实际上匹配RecyClerview的高度和宽度?

好吧,当您考虑时,解决方案很简单。只需添加

view.layoutParams = RecyclerView.LayoutParams(RecyclerView.LayoutParams.MATCH_PARENT, RecyclerView.LayoutParams.MATCH_PARENT)

构建视图解决了问题。

最新更新