好的,所以我现在正在尝试双向数据绑定,从逻辑上讲,我认为代码中的所有内容都很完美,但是无论如何,只要运行应用程序,我总是会遇到相同的错误:“执行组织时发生故障。 jetbrains.kotlin.gradle.internal.KaptExecution”。基本上,如果我的数据库中没有数据,我会尝试使用Data Binding ofc隐藏ImageView可见性。
fragment_list.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"
xmlns:tools="http://schemas.android.com/tools">
<data>
<variable
name="listViewModel"
type="com.jovanovic.stefan.tododemo.fragments.list.ListViewModel" />
</data>
<androidx.constraintlayout.widget.ConstraintLayout
android:id="@+id/listLayout"
... >
<ImageView
android:id="@+id/no_data_imageView"
emptyDatabase="@={listViewModel.emptyDatabase}"
... />
</androidx.constraintlayout.widget.ConstraintLayout>
</layout>
ListViewModel(我的片段的ViewModel)
class ListViewModel: ViewModel() {
val emptyDatabase: MutableLiveData<Boolean> = MutableLiveData<Boolean>(true)
fun checkDatabase(toDoData: List<ToDoData>){
emptyDatabase.value = toDoData.isEmpty()
}
}
ListFragment
class ListFragment : Fragment(), SearchView.OnQueryTextListener {
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val listViewModel = ViewModelProvider(this).get(ListViewModel::class.java)
val binding = FragmentListBinding.inflate(inflater, container, false)
binding.lifecycleOwner = this
binding.listViewModel = listViewModel
val toDoViewModel= ViewModelProvider(this).get(ToDoViewModel::class.java)
// Observing LiveData object for Room DB which is reading all data
toDoViewModel.allData.observe(viewLifecycleOwner, Observer { data ->
// Using checkDatabase method from ListViewModel
listViewModel.checkDatabase(data)
})
return binding.root
}
BindingAdapter
@BindingAdapter("emptyDatabase")
@JvmStatic
fun emptyDatabase(view: View, emptyDatabase: MutableLiveData<Boolean>){
if(emptyDatabase.value == true){
view.visibility = View.VISIBLE
}else{
view.visibility = View.INVISIBLE
}
}
答案 0 :(得分:1)
emptyDatabase="@={listViewModel.emptyDatabase}"
"="我们仅用于android模型的双向数据绑定。"="表示如果模型通过get调用更新视图,如果视图通过set调用更新其更新模型。它不适用于数据绑定适配器功能>
答案 1 :(得分:0)
我记得我对kapt有类似的问题。请清理您的构建,然后重试,这对我有用。同样,按照您为emptyDatabase.value == true描述的方案,view.visibility应该是View.Insivisble。
答案 2 :(得分:0)
在(4:29)观看了此视频后:https://youtu.be/TW9dSEgJIa8
我看到我忘记为DataBinding添加此依赖项
//DataBinding
kapt "com.android.databinding:compiler:3.2.0-alpha10"
即使我添加了这种依赖性,在从"="
删除"@={listViewModel.emptyDatabase}"
之前,仍然有一个错误