android数据绑定在自定义控件 [英] android databinding in custom controls
问题描述
在官方android文档中 - 有一些指导如何在片段和活动中使用数据绑定。不过我有很多复杂的选择器,具有很高的设置。类似于:
In official android docs - there is some guidance how to use databinding in fragments and activities. However I have pretty complex picker with high ammount of settings. Something like:
class ComplexCustomPicker extends RelativeLayout{
PickerViewModel model;
}
所以我的问题是我需要覆盖的方法是什么在其中使用绑定,而不是设置/检查诸如textfield等的单个值?
So my question is what method of the picker I need to override to be able use binding inside it and not seting/checking individual values like textfield, etc?
第二个问题 - 我如何将viewmodel传递给xml文件中的选择器,我需要一些自定义属性吗?
And second question - how could I pass viewmodel to my picker in xml file, do I need some custom attributes for that?
推荐答案
我认为使用自定义设置器可以解决您的问题。 查看本节的开发人员指南。
I think using Custom Setters will solve your problem. Check this section in developers guidelines.
我可以给你一个简单的例子。假设您的视图名称为 CustomView
,并且您的viewmodel为 ViewModel
,则在任何类中,创建一个方法如下:
I can give you a brief example for it. Suppose the name of your view is CustomView
and of your viewmodel is ViewModel
, then in any of your class, create a method like this:
@BindingAdapter({"bind:viewmodel"})
public static void bindCustomView(CustomView view, ViewModel model) {
// Do whatever you want with your view and your model
}
在您的布局中,执行以下操作:
And in your layout, do the following:
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/tools">
<data>
<variable
name="viewModel"
type="com.pkgname.ViewModel"/>
</data>
// Your layout
<com.pkgname.CustomView
// Other attributes
app:viewmodel="@{viewModel}"
/>
</layout>
从您的活动
使用此设置ViewModel:
And from your Activity
use this to set the ViewModel:
MainActivityBinding binding = DataBindingUtil.setContentView(this, R.layout.main_activity);
ViewModel viewModel = new ViewModel();
binding.setViewModel(viewModel);
或者您可以直接从自定义视图中膨胀:
Or you can directly inflate from your custom view:
LayoutViewCustomBinding binding = DataBindingUtil.inflate(LayoutInflater.from(getContext()), R.layout.layout_view_custom, this, true);
ViewModel viewModel = new ViewModel();
binding.setViewModel(viewModel);
这篇关于android数据绑定在自定义控件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!