android mvvm --databinding

本文详细介绍了Android中MVVM架构模式下DataBinding的使用,包括数据导入、变量声明、布局绑定、单项和双向数据绑定,以及如何使用Observable、ObservableField和ObservableMap进行数据观察。同时,展示了在XML中如何引用和操作这些绑定的数据。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

第一部分 databinding (ktn)

布局 <layout> 中包含两部分 

一部分 数据  数据必须 <data></data>包含 

xml文件

1.<import 导包

2.<variable 数据     
 

<data>
    <import type="android.util.SparseArray"/>
    <import type="java.util.Map"/>
    <import type="java.util.List"/>
    <variable name="list" type="List&lt;String>"/>
    <variable name="sparse" type="SparseArray&lt;String>"/>
    <variable name="map" type="Map&lt;String, String>"/>
    <variable name="index" type="int"/>
    <variable name="key" type="String"/>
</data>
…
android:text="@{list[index]}"
…
android:text="@{sparse[index]}"
…
android:text="@{map[key]}"

二部分 布局 跟以前xml类似 多了绑定数据

基本符合都支持

单项绑定

1.绑定基本数据

android:text="@{map[`firstName`]}"
<include layout="@layout/name"
           bind:user="@{user}"/>
<ImageView app:imageUrl="@{venue.imageUrl}" app:error="@{@drawable/venueError}" />

 

 

2. 绑定事件

android:onClick="@{handlers::onClickFriend}"
   android:onClick="@{() -> presenter.onSaveClick(task)}" />

 

3.绑定 adpter

app:setAdapter="@{model.getAdapter()}"

4.显示 

 android:visibility="@{user.isAdult ? View.VISIBLE : View.GONE}"/>

  

双向绑定 (@={}符号,其重要的包括符号“=”,接收数据的变化的属性,并在同一时间收听用户的更新。)

<CheckBox
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:checked="@ = {viewmodel.rememberMe}"/>
public class LoginViewModel extends BaseObservable {
    // private Model data = ...

    @Bindable
    public Boolean getRememberMe() {
        return data.rememberMe;
    }

    public void setRememberMe(Boolean value) {
        // Avoids infinite loops.
        if (data.rememberMe != value) {
            data.rememberMe = value;

            // React to the change.
            saveData();

            // Notify observers of a new value.
            notifyPropertyChanged(BR.remember_me);
        }
    }
}

双向绑定 支持者

属性(S)绑定适配器
AdapterViewandroid:selectedItemPosition
android:selection
AdapterViewBindingAdapter
CalendarViewandroid:dateCalendarViewBindingAdapter
CompoundButtonandroid:checkedCompoundButtonBindingAdapter
DatePickerandroid:year
android:month
android:day
DatePickerBindingAdapter
NumberPickerandroid:valueNumberPickerBindingAdapter
RadioButtonandroid:checkedButtonRadioGroupBindingAdapter
RatingBarandroid:ratingRatingBarBindingAdapter
SeekBarandroid:progressSeekBarBindingAdapter
TabHostandroid:currentTabTabHostBindingAdapter
TextViewandroid:textTextViewBindingAdapter
TimePickerandroid:hour
android:minute
TimePickerBindingAdapter
代码绑定
class ViewModelActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        // Obtain the ViewModel component.
        UserModel userModel = ViewModelProviders.of(getActivity())
                                                  .get(UserModel.class)

        // Inflate view and obtain an instance of the binding class.
        val binding: UserBinding = DataBindingUtil.setContentView(this, R.layout.user)

        // Assign the component to a property in the binding class.
        binding.viewmodel = userModel
    }
}

数据观察用法 Observable   BaseObservable   ObservableField

observable  简单数据类型

实现Observable接口,它有以下两种方法:

addOnPropertyChangedCallback

removeOnPropertyChangedCallback

当您的字段发生更改时,必须通知 OnPropertyChangedCallback

public class Foo implements Observable {
private PropertyChangeRegistry registry =
new PropertyChangeRegistry();
private int bar;

@Bindable
public int getBar() {
return bar;
}

public void setBar(int bar) {
this.bar = bar;
registry.notifyChange(this, BR.bar);
}

@Override
public void addOnPropertyChangedCallback(
OnPropertyChangedCallback callback) {
registry.add(callback);
}

@Override
public void removeOnPropertyChangedCallback(
OnPropertyChangedCallback callback) {
registry.remove(callback);
}
}

注意:该类还必须注释应该使用“@Bindable”观察到的任何getter。

BaseObservable 和 observable 功能类似 更简单些 

public class Foo extends BaseObservable {
private int bar;

@Bindable
public int getBar() {
return bar;
}

public void setBar(int bar) {
this.bar = bar;
notifyPropertyChanged(BR.bar);
}
}

 ObservableField 复杂数据类型 

代码使用  

public class Foo {
public final ObservableInt bar = new ObservableInt();
public final ObservableField<String> baz =
new ObservableField<>();
}

代码 操作

 foo.bar.set(age);
String name = foo.baz.get();

xml引用 
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@{foo.baz}"
/>

ObservableMap 数据类型不确定 或者 不一样

代码实现 

ObservableMap<String, Object> product = new ObservableArrayMap<>();
binding.setProduct(product);
product.put("name", "Golf Ball");

xml引用 

<data>
<variable name="product"
type="android.databinding.ObservableMap<String, Object>
/>
</data>

<!-- ... -->
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text='@{product["name"]}'
/>

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值