android databinding 之自定义控件

1 在attrs.xml中加入

<declare-styleable name="MultiProgressBar">
    <attr name="progress" format="integer"/>
</declare-styleable>

2 修改构造函数,加入如下代码

TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.MultiProgressBar);
this.currentValue = a.getInt(R.styleable.MultiProgressBar_progress, 0);
a.recycle();

 3.在代码中加入数据绑定注解(测试数据绑定会报错,但是正常使用属性是可以的

@BindingAdapter({"progress"})
public void setProgress(View v,int progress){
    this.currentValue = progress;
    update();
}

4.以上都没有问题后就可以在xml中使用了。看到progress出现了吗?

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
可以通过在自定义件的布局文件中使用 `<layout>` 标签来启用 DataBinding,然后在代码中使用 DataBindingUtil 类来绑定数据。 例如,假设我们有一个自定义件 MyCustomView,它的布局文件为 custom_view.xml,我们想要绑定一个名为 `text` 的字符串属性。我们可以这样做: 1. 在 custom_view.xml 中使用 `<layout>` 标签包裹布局文件的根布局: ```xml <layout xmlns:android="http://schemas.android.com/apk/res/android"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical"> <!-- 自定义件的布局 --> </LinearLayout> </layout> ``` 2. 在 MyCustomView 的构造函数中使用 DataBindingUtil.inflate 方法来获取绑定对象,并将它与自定义件的根布局绑定: ```java public MyCustomView(Context context, AttributeSet attrs) { super(context, attrs); // 获取绑定对象 CustomViewBinding binding = DataBindingUtil.inflate(LayoutInflater.from(context), R.layout.custom_view, this, true); // 绑定数据 binding.setText("Hello, world!"); } ``` 3. 在 MyCustomView 中添加一个 `text` 属性,并在 custom_view.xml 中使用 `@{}` 语法来绑定该属性: ```java public class MyCustomView extends LinearLayout { private String text; public MyCustomView(Context context, AttributeSet attrs) { super(context, attrs); CustomViewBinding binding = DataBindingUtil.inflate(LayoutInflater.from(context), R.layout.custom_view, this, true); binding.setCustomView(this); } public String getText() { return text; } public void setText(String text) { this.text = text; } } ``` ```xml <layout xmlns:android="http://schemas.android.com/apk/res/android"> <data> <variable name="customView" type="com.example.MyCustomView" /> </data> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@{customView.text}" /> </LinearLayout> </layout> ``` 这样,当 MyCustomView 的 `text` 属性发生变化时,custom_view.xml 中的 TextView 的文本也会自动更新。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值