如何在ViewHolder中为RecyclerView充气View

时间:2018-05-21 03:22:19

标签: android android-layout android-recyclerview

我正在尝试为ViewHolder for RecyclerView内部的视图充气,但它不起作用。 如果有人就以下示例代码给我建议,我将不胜感激。

class MyProfileViewHolder(
    itemView: View,
    private val myProfileViewModel: MyProfileViewModel) : RecyclerView.ViewHolder(itemView) {

private val userImageView: ImageView = itemView.myProfileMainUserImageView
private val myProfileSelfIntroductionText: TextView = itemView.myProfileSelfIntroductionText
private val favoriteEmptyFrame: FrameLayout = itemView.favoriteEmptyFrame

fun bind() {
    // DefaultImage
    val url = myProfileViewModel.user.getProfileImageUrl(myProfileViewModel.selectedImageIndex, "medium")
    profileViewHelper.setProfileMainImage(
            userImageView,
            myProfileViewModel.user.getProfileImageUrl(myProfileViewModel.selectedImageIndex, "medium"),
            myProfileViewModel.user.gender
    )
    // Self introduction
    myProfileSelfIntroductionText.text = myProfileViewModel.user.description

    // favorite empty frame
    when(myProfileViewModel.emptyViewType) {
        MyProfileViewModel.EMPTY_VIEW_TYPE_FAVORITE -> {
            // it doesn't work
            LayoutInflater.from(itemView.context).inflate(R.layout.section_favorite_empty, favoriteEmptyFrame, false)
        }
    }
}

}

这是我在Cacher上尝试的示例代码,包括Adapter和xml等其他文件。 https://snippets.cacher.io/snippet/e02fb192f90c21765e7e

1 个答案:

答案 0 :(得分:0)

我找不到解决办法,在创建viewHolder之前,必须先增加布局。

但是您可以使用以下代码解决此限制:

class MyProfileViewHolder(
    itemView: View) : RecyclerView.ViewHolder(itemView) {

...

MyProfileViewHolder(LayoutInflater.from(context)
                    .inflate(R.layout.m_layout, container, false))