我在尝试使用自定义视图中的片段ViewModel与属性之间实现双向绑定方面遇到了困难。将String
与EditText
进行双向绑定没有问题,而且我的自定义SearchView
也可以正常进行单向绑定。但是,当我将自定义视图上的"@{vm.entry.item}"
更改为"@={vm.entry.item}"
时,项目就无法编译并抛出以下错误:
error: cannot find symbol import com.test.test.databinding.FragmentTestBindingImpl;
我已经阅读了一些教程,例如这篇文章,并尝试使用 BindingAdapter
进行调整,但没有得到好的结果。感觉自己可能只是忽略了某些明显的东西。
Kotlin
data class TestModel(
var item: String? = null,
var quantity: String? = null
)
class TestViewModel : ViewModel() {
val entry = TestModel()
}
class TestFragment : Fragment() {
private val vm: TestViewModel by lazy {
ViewModelProvider(this).get(TestViewModel::class.java)
}
override fun onCreateView(
inflater: LayoutInflater,
parent: ViewGroup?,
savedInstanceState: Bundle?
): View {
val binding: FragmentTestBinding =
DataBindingUtil.inflate(inflater, R.layout.fragment_test, parent, false)
binding.setVariable(BR.vm, vm)
binding.lifecycleOwner = viewLifecycleOwner
return binding.root
}
}
class SearchView(context: Context, attrs: AttributeSet) : FrameLayout(context, attrs, 0) {
var selected: String? = null
init {
inflate(context, R.layout.view_search, this)
val input: AutoCompleteTextView = findViewById(R.id.search_input)
input.threshold = 1
input.setAdapter(SearchAdapter(context))
input.setOnItemClickListener { adapterView, _, position, _ ->
val item: SearchModel = adapterView.getItemAtPosition(position) as SearchModel
input.setText(item.name)
selected = item.code
}
}
}
碎片布局
<?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="vm"
type="com.test.test.ui.TestViewModel" />
</data>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<com.test.test.ui.views.SearchView
android:id="@+id/test_search"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:selected="@={vm.entry.item}" />
<EditText
android:id="@+id/test_edit_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@={vm.entry.quantity}" />
</LinearLayout>
</layout>
搜索视图布局
<?xml version="1.0" encoding="utf-8"?>
<merge xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="@dimen/paddingDouble"
android:orientation="horizontal">
<AutoCompleteTextView
android:id="@+id/search_input"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</merge>