我已经坚持了几个小时。尊重任何可以帮助我解决这个问题的人。
每当我更改MutableLiveData时,视图都不会更新。
在我的锻炼应用程序中,我有一个锻炼列表:MutableLiveData>,这些锻炼使用回收者视图显示。回收者视图持有者正在使用数据绑定来显示此ArrayList中的各个练习。每当我更新整个列表(使用setValue)时,我都希望视图能够更新。
但是,由于我的数据绑定xml实际上未引用MutableLiveData>(),因此列表中仅包含ExerciseEntity元素,我认为它没有观察到任何更改。因此,它没有更新。我不知道如何使其正确更新。
SelectorActivity:
class SelectorActivity : AppCompatActivity() {
private lateinit var mExerciseSelectAdapter: ExerciseSelectAdapter
private lateinit var mViewModel: SelectorViewModel
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_selector)
mViewModel = ViewModelProviders.of(this).get(SelectorViewModel::class.java)
mExerciseSelectAdapter = ExerciseSelectAdapter(this, mViewModel)
setupRecyclerView()
loadExerciseList(intent.hasExtra("LOAD_FROM_DB"), resources)
}
private fun setupRecyclerView(){
rv_select_exers.layoutManager = LinearLayoutManager(this)
rv_select_exers.setHasFixedSize(true)
rv_select_exers.adapter = mExerciseSelectAdapter
}
private fun loadExerciseList(loadFromDB: Boolean, resources: Resources) {
doAsync {
val myDBExercises = loadExersFromDB()
mViewModel.populateExerciseListFromDB(myDBExercises)
mExerciseSelectAdapter.notifyDataSetChanged()
}
}
}
}
SelectorViewModel:
class SelectorViewModel : ViewModel() {
private val mExerciseList = MutableLiveData<ArrayList<ExerciseEntity>>()
val exerciseList : LiveData<ArrayList<ExerciseEntity>>
get() = mExerciseList
init {
mExerciseList.value = ArrayList()
}
fun populateExerciseListFromDB(myDBExercises: List<ExerciseEntity>) {
// .... Load our exer list from DB ... //
mExerciseList.value?.addAll(myDBExercises)
// Use the "setValue" method to notify observers of change
mExerciseList.value = mExerciseList.value
}
private fun updateRepsInExercise(exercise: ExerciseEntity, reps1: Int, reps2: Int, reps3: Int) {
exercise.set1Reps = reps1
exercise.set2Reps = reps2
exercise.set3Reps = reps3
// Force our livedata to detect a change
// TODO: not doing anything after increment set, our view is not updating
mExerciseList.value = mExerciseList.value
}
fun incrementSet(exercise: ExerciseEntity, smallIncrement: Boolean) {
// ... Compute the new reps ... //
updateRepsInExercise(exercise, numReps1, numReps2, numReps3)
}
}
ExerciseSelectAdapter:
class ExerciseSelectAdapter(priv val mLifecycleOwner:LifecycleOwner, 私有val mViewModel:SelectorViewModel): RecyclerView.Adapter(){ 私人lateinit var mExerciseList:ArrayList
init {
// Use this to avoid blinking of list when data is changed
setHasStableIds(true)
// Get a reference to our viewmodel's exercise list
if (mViewModel.exerciseList.value != null ) mExerciseList = mViewModel.exerciseList.value!!
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ExerciseSelectViewHolder {
val layoutInflater = LayoutInflater.from(parent.context)
val dataBinding: ExerciseSelectBinding = DataBindingUtil.inflate(layoutInflater, R.layout.exercise_select, parent, false);
dataBinding.setLifecycleOwner(mLifecycleOwner)
return ExerciseSelectViewHolder(dataBinding, mLifecycleOwner, mViewModel)
}
override fun onBindViewHolder(holder: ExerciseSelectViewHolder, index: Int) {
holder.bindExerciseSelectView(mExerciseList[index])
}
override fun getItemCount(): Int {
return mExerciseList.size
}
// Use this to avoid blinking of list when data is changed
override fun getItemId(position: Int): Long {
return mExerciseList[position].exerciseNum.toLong()
}
}
ExerciseSelectViewHolder:
class ExerciseSelectViewHolder(private val mDataBinding: ExerciseSelectBinding,
private val mLifecycleOwner: LifecycleOwner,
private val mViewModel: SelectorViewModel):
RecyclerView.ViewHolder(mDataBinding.root){
init {
// Used to enable proper observation of LiveData
mDataBinding.setLifecycleOwner(mLifecycleOwner)
}
fun bindExerciseSelectView(exerciseEntity: ExerciseEntity) {
mDataBinding.exerciseEntity = exerciseEntity
mDataBinding.viewModel = mViewModel
mDataBinding.spinnerAdapter = ArrayAdapter(mLifecycleOwner as Context,
R.layout.simple_spinner_dropdown_item,
exerciseEntity.allProgressions)
// Forces the bindings to run immediately
mDataBinding.executePendingBindings()
}
}
activity_selector.xml:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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"
tools:context="com.epsilon.startbodyweight.selectorActivity.SelectorActivity">
<android.support.v7.widget.RecyclerView
android:id="@+id/rv_select_exers"
android:layout_width="match_parent"
android:layout_height="0dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
exercise_select.xml:
<?xml version="1.0" encoding="utf-8"?>
<layout>
<data>
<import type="android.view.View"/>
<variable
name="exerciseEntity"
type="com.epsilon.startbodyweight.data.ExerciseEntity"/>
<variable
name="viewModel"
type="com.epsilon.startbodyweight.selectorActivity.SelectorViewModel"/>
<variable
name="spinnerAdapter"
type="android.widget.ArrayAdapter" />
</data>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
<Spinner
android:id="@+id/sp_sel_exer"
//... Styling stuff
android:spinnerMode="dropdown"
android:adapter="@{spinnerAdapter}"
android:selection="@{exerciseEntity.progressionNumber}"
android:onItemSelected="@{(parent,view,position,id) -> viewModel.onItemSelectedSpinner(parent,position,exerciseEntity)}"/>
<Button
android:id="@+id/b_sel_increase_reps_small"
android:layout_width="wrap_content"
//... Styling stuff
android:onClick="@{() -> viewModel.incrementSet(exerciseEntity, true)}"
android:text="↑" />
<TextView
android:id="@+id/tv_sel_rep_1"
// ... Styling stuff
android:text="@{String.valueOf(exerciseEntity.set1Reps)}"
android:visibility="@{!exerciseEntity.isTimedExercise ? View.VISIBLE : View.GONE}"/>
<TextView
android:id="@+id/tv_sel_rep_2"
//... Styling stuff
android:text="@{String.valueOf(viewModel.exerciseList)}"
android:visibility="@{!exerciseEntity.isTimedExercise ? View.VISIBLE : View.GONE}"/>
<TextView
android:id="@+id/tv_sel_rep_3"
//... Styling stuff
android:text="@{String.valueOf(exerciseEntity.set3Reps)}"
android:visibility="@{!exerciseEntity.isTimedExercise ? View.VISIBLE : View.GONE}"/>
</LinearLayout>
</layout>
当在布局XML中根本不使用此列表时,是否需要使数据绑定观察对MutableLiveData>的更改?我想将ArrayList的每个成员都当作另一个可变的实时数据,例如:MutableLiveData >>,但这似乎相当复杂...
编辑:我找到了一个解决方案,这很简单,但并不理想。还在寻找建议。
我没有将ExerciseEntity直接绑定到我的数据绑定XML布局,而是绑定了元素在列表中的位置。然后在我的xml中,使用列表和此索引访问元素。
在exercise_select.xml中,我替换了
android:text="@{String.valueOf(exerciseEntity.set2Reps)}"
通过
android:text="@{String.valueOf(viewModel.exerciseList[index].set2Reps)}"
这似乎说服了数据绑定最终观察到对ArrayList的修改。
我不满意,有没有更多的“最佳做法”来做到这一点?