在Android开发中,DataBinding是一种允许开发者将布局中的UI组件与数据源直接绑定的技术。通过DataBinding,可以减少大量的findViewById和手动设置数据的代码,提高代码的可读性和可维护性。
DataBinding库允许你通过XML布局文件声明式地绑定数据到视图上。它使用了一种特殊的数据绑定表达式语言,可以在XML中使用变量、表达式和函数。
DataBinding主要分为两种类型:
假设我们有一个自定义视图CustomTextView
,我们想通过DataBinding传递一个字符串到它的customText
属性。
public class CustomTextView extends TextView {
private String customText;
public CustomTextView(Context context) {
super(context);
}
public CustomTextView(Context context, AttributeSet attrs) {
super(context, attrs);
init(context, attrs);
}
private void init(Context context, AttributeSet attrs) {
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CustomTextView);
customText = a.getString(R.styleable.CustomTextView_customText);
a.recycle();
setText(customText);
}
public void setCustomText(String text) {
this.customText = text;
setText(customText);
}
}
res/values/attrs.xml
中定义自定义属性:<declare-styleable name="CustomTextView">
<attr name="customText" format="string" />
</declare-styleable>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<data>
<variable
name="viewModel"
type="com.example.ViewModel" />
</data>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<com.example.CustomTextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:customText="@{viewModel.text}" />
</LinearLayout>
</layout>
public class ViewModel extends BaseObservable {
private String text;
@Bindable
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
notifyPropertyChanged(BR.text);
}
}
ActivityMainBinding binding = DataBindingUtil.setContentView(this, R.layout.activity_main);
ViewModel viewModel = new ViewModel();
viewModel.setText("Hello, DataBinding!");
binding.setViewModel(viewModel);
binding.executePendingBindings();
attrs.xml
文件位于res/values
目录下。build.gradle
文件中启用了DataBinding:build.gradle
文件中启用了DataBinding:<layout>
。@Bindable
注解,并调用了notifyPropertyChanged(BR.propertyName)
。通过以上步骤,你可以成功地将字符串从DataBinding传入自定义视图的xml属性中。更多详细信息和示例代码可以参考Android官方文档。
没有搜到相关的沙龙
领取专属 10元无门槛券
手把手带您无忧上云