gpt4 book ai didi

android - MVVM-包含布局内的 Recyclerview 从未初始化

转载 作者:行者123 更新时间:2023-12-02 10:41:22 25 4
gpt4 key购买 nike

我有一个通用列表,需要在我的应用程序中的大多数 Activity/fragment 上显示。为此,我创建了一个布局并在其中添加了回收器,如下面的代码所示。然后根据需要将该布局包含在 Activity/fragment 中。我正在使用 MVVM 和 android 绑定(bind)。我的问题是 recyclerview 的 onCreateViewHolder 甚至 getItemCount 从未被调用。我的 updateList 函数从 View 模型成功调用,列表中有 2 项,但 notifydatasetchanged 没有任何效果。我做错了什么?这是我的代码。适配器类

class FaqsAdapter : RecyclerView.Adapter<FaqsAdapter.MyViewHolder>() {
lateinit var binding: FaqItemBinding
lateinit var listFaqs: List<ModelFaqs>

override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
val inflater = LayoutInflater.from(parent.context)
binding = DataBindingUtil.inflate(inflater, R.layout.faq_item, parent, false)
return MyViewHolder(binding)
}

override fun getItemCount(): Int {
return if (::listFaqs.isInitialized) listFaqs.size else 0
}

override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
holder.bind(listFaqs[position])
}

fun updateList(faqs: List<ModelFaqs>) {
this.listFaqs = faqs //this line executes
notifyDataSetChanged() // line also executes but does nothing.
}

class MyViewHolder(binding: FaqItemBinding) : RecyclerView.ViewHolder(binding.root) {
private val mBinding = binding
fun bind(modelFaqs: ModelFaqs) {
val viewModel = FaqItemViewModel()
viewModel.bind(modelFaqs)
mBinding.mViewModel = viewModel
}
}
}

fragment

class FragLoan : Fragment() {
//other code

override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
binding.viewFaqs.rcFaqs.layoutManager = LinearLayoutManager(context)
viewModel = ViewModelProviders.of(this).get(FragLoanViewModel::class.java)

}
}

viewModel 类

class FragLoanViewModel : BaseViewModel() {
//other code

private fun onLoanSuccess(response: AdvanceLoanDetails?) {
Log.d(TAG, "LoanViewModel--On Success")
val modelFaqs: MutableList<ModelFaqs> = mutableListOf()
if (response?.result == true) {
if (response.resultContent?.faqs != null) {
for (faqs in response.resultContent.faqs) {
val model = ModelFaqs(faqs?.question, faqs?.answer)
modelFaqs.add(model)
}
updateFaq(modelFaqs)
}
}
}

//other code.
}

基础 View 模型这是我的基本 View 模型

abstract class BaseViewModel : ViewModel() {
val faqsAdapter = FaqsAdapter()

private val injector: ViewModelInjector = DaggerViewModelInjector
.builder()
.networkModule(NetworkModule)
.build()

init {
inject()
}

private fun inject() {
when (this) {
//code here
}
}

fun updateFaq(listFaqs: List<ModelFaqs>) {
faqsAdapter.updateList(listFaqs)
}
}

fragment 布局

 <?xml version="1.0" encoding="utf-8"?>

<layout 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">

<data>

<variable
name="viewModel"
type="com.mypackage.viewmodel.FragLoanViewModel" />
</data>

<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/colorViewBackgroundGrey"
tools:context="com.mypackage.myfragments.FragLoan">

<ImageView
android:id="@+id/ivLoanBanner"
android:layout_width="0dp"
android:layout_height="@dimen/_60sdp"
android:layout_marginTop="16dp"
android:contentDescription="@null"
android:scaleType="fitXY"
app:imageurl="@{viewModel.banner}"
app:layout_constraintLeft_toLeftOf="@id/guideLeft"
app:layout_constraintRight_toRightOf="@id/guideRight"
app:layout_constraintTop_toTopOf="parent" />

<androidx.cardview.widget.CardView
android:id="@+id/cvLoanDetails"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:background="@color/colorWhite"
app:cardCornerRadius="@dimen/card_content_radius"
app:layout_constraintEnd_toEndOf="@id/guideRight"
app:layout_constraintStart_toStartOf="@id/guideLeft"
app:layout_constraintTop_toBottomOf="@id/ivLoanBanner">

<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="@dimen/_16sdp">

<TextView
android:id="@+id/tvAdvanceLoadTitle"
mutableText="@{viewModel.title}"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="@dimen/_6sdp"
android:textColor="@color/colorBlack"
android:textStyle="bold"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />

<TextView
android:id="@+id/tvAdvanceLoanValidity"
mutableText="@{viewModel.validity}"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="3dp"
android:textColor="@color/lightGrey"
app:layout_constraintStart_toStartOf="@+id/tvAdvanceLoadTitle"
app:layout_constraintTop_toBottomOf="@+id/tvAdvanceLoadTitle" />


<TextView
android:id="@+id/tvAdvanceLoanPrice"
mutableText="@{viewModel.amount}"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="@color/colorPrimary"
android:textStyle="bold"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="@+id/tvAdvanceLoadTitle" />

<TextView
android:id="@+id/tvAdvanceLoanTax"
mutableText="@{viewModel.inclusiveTax}"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="3dp"
android:textColor="@color/lightGrey"
app:layout_constraintEnd_toEndOf="@+id/tvAdvanceLoanPrice"
app:layout_constraintTop_toBottomOf="@+id/tvAdvanceLoanPrice" />

<TextView
android:id="@+id/tvAdvanceLoanDetail"
mutableText="@{viewModel.description}"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginTop="@dimen/_8sdp"
android:background="@drawable/edit_text_history"
android:gravity="center"
android:minHeight="@dimen/_50sdp"
android:padding="@dimen/_6sdp"
android:textColor="@color/lightGrey"
android:textSize="12sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/tvAdvanceLoanValidity" />

<androidx.constraintlayout.widget.Barrier
android:id="@+id/barrier"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:barrierDirection="left"
app:constraint_referenced_ids="tvAdvanceLoanTax,tvAdvanceLoanPrice"
tools:layout_editor_absoluteX="369dp" />
</androidx.constraintlayout.widget.ConstraintLayout>
</androidx.cardview.widget.CardView>

<androidx.constraintlayout.widget.Guideline
android:id="@+id/guideLeft"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
app:layout_constraintGuide_begin="16dp" />

<androidx.constraintlayout.widget.Guideline
android:id="@+id/guideRight"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
app:layout_constraintGuide_end="16dp" />

<!-- <androidx.recyclerview.widget.RecyclerView-->
<!-- android:id="@+id/rcFaqs"-->
<!-- app:layout_constraintEnd_toEndOf="@id/guideRight"-->
<!-- app:layout_constraintStart_toStartOf="@id/guideLeft"-->
<!-- app:layout_constraintTop_toBottomOf="@+id/cvLoanDetails"-->
<!-- android:layout_width="0dp"-->
<!-- android:layout_height="wrap_content"-->
<!-- app:adapter="@{viewModel.faqsAdapter}" />-->
<include
android:id="@+id/viewFaqs"
layout="@layout/view_faq"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
app:layout_constraintEnd_toEndOf="@id/guideRight"
app:layout_constraintStart_toStartOf="@id/guideLeft"
app:layout_constraintTop_toBottomOf="@+id/cvLoanDetails" />

<include
android:id="@+id/viewTerms"
layout="@layout/view_terms_conditions"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
app:layout_constraintEnd_toEndOf="@id/guideRight"
app:layout_constraintStart_toStartOf="@id/guideLeft"
app:layout_constraintTop_toBottomOf="@+id/viewFaqs" />

<com.google.android.material.button.MaterialButton
android:id="@+id/btnGetLoan"
android:layout_width="0dp"
android:layout_height="@dimen/button_height"
android:layout_marginBottom="8dp"
android:text="@string/get_loan"
android:textAllCaps="false"
app:cornerRadius="@dimen/button_corner_radius"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="@id/guideRight"
app:layout_constraintStart_toStartOf="@id/guideLeft" />

</androidx.constraintlayout.widget.ConstraintLayout>
</layout>

我的 FaqItemViewModel

class FaqItemViewModel : BaseViewModel() {
private val sequenceNumber = MutableLiveData<String>()
private val question = MutableLiveData<String>()
private val answer = MutableLiveData<String>()
private var sqNo = 0

fun bind(faqs: ModelFaqs) {

sqNo += 1
sequenceNumber.value = sqNo.toString()
question.value = faqs.question
answer.value = faqs.answer

}

fun getSequenceNumber(): MutableLiveData<String> {
return sequenceNumber
}

fun getQuestion(): MutableLiveData<String> {
return question
}

fun getAnswer(): MutableLiveData<String> {
return answer
}

}

和项目 XML

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">

<data>

<variable
name="mViewModel"
type="com.mypackage.viewmodel.FaqItemViewModel" />
</data>

<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">

<TextView
android:id="@+id/tvSerialNumber"
mutableText="@{mViewModel.sequenceNumber}"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="@color/colorAccent"
android:textStyle="bold"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />

<TextView
android:id="@+id/tvQuestion"
mutableText="@{mViewModel.question}"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:paddingLeft="6dp"
android:paddingRight="6dp"
android:textColor="@color/colorAccent"
android:textStyle="bold"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toEndOf="@+id/tvSerialNumber"
app:layout_constraintTop_toTopOf="@+id/tvSerialNumber" />

<TextView
android:id="@+id/tvAnswer"
mutableText="@{mViewModel.answer}"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:paddingLeft="6dp"
android:paddingRight="6dp"
android:textColor="@color/lightGrey"
android:textSize="12sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="@+id/tvQuestion"
app:layout_constraintTop_toBottomOf="@+id/tvQuestion" />
</androidx.constraintlayout.widget.ConstraintLayout>
</layout>

最佳答案

您没有将viewmodel绑定(bind)到您的布局。在您 fragment 的 onActivityCreated 中,您将

override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
binding.viewFaqs.rcFaqs.layoutManager = LinearLayoutManager(context)
viewModel = ViewModelProviders.of(this).get(FragLoanViewModel::class.java)
binding.viewModel = viewModel //this line will fix

//Additionally, bind it to lifecycleOwner
binding.lifecycleOwner = this
}

接下来在适配器中,您不应该有参数绑定(bind),因为它是每个项目的。您应该在 onBindViewHolder

中传递 绑定(bind)
class FaqsAdapter : RecyclerView.Adapter<FaqsAdapter.MyViewHolder>() {
private val listFaqs = mutableListOf<ModelFaqs>()

override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
val inflater = LayoutInflater.from(parent.context)
val binding = DataBindingUtil.inflate(inflater, R.layout.faq_item, parent, false)
return MyViewHolder(binding)
}

override fun getItemCount() = listFaqs.size

override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
holder.bind(listFaqs[position])
}

fun updateList(faqs: List<ModelFaqs>) {
this.listFaqs.clear()
this.listFaqs.addAll(faqs)
notifyDataSetChanged() // line also executes but does nothing.
}

class MyViewHolder(private val binding: FaqItemBinding) :
RecyclerView.ViewHolder(binding.root) {
fun bind(modelFaqs: ModelFaqs) {
val viewModel = FaqItemViewModel()
viewModel.bind(modelFaqs)
binding.mViewModel = viewModel
}
}

关于android - MVVM-包含布局内的 Recyclerview 从未初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58737742/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com