使用RealmObject进行双向数据绑定。交易要求

时间:2017-02-17 06:48:38

标签: android realm android-databinding

我想在RealmObject项的数据绑定布局中使用RecycleView作为视图模型。某些属性必须双向绑定到视图 - 例如AppCompatCheckBox。但是当数据绑定执行setter的回调时,会发生下一个异常:

  

java.lang.IllegalStateException:只能在事务内部更改Realm数据。

为双向数据绑定打开Realm事务哪种方式更好?

item_layout.xml

<?xml version="1.0" encoding="utf-8"?>
<layout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:card_view="http://schemas.android.com/apk/res-auto">

    <data>
        <variable
            name="shoppingItem"
            type="com.example.ShoppingListItem"/>
    </data>

    <android.support.v7.widget.CardView
        android:id="@+id/product_card_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:foreground="?selectableItemBackground"
        card_view:cardElevation="@dimen/cardview_default_elevation"
        card_view:cardUseCompatPadding="true"
        card_view:cardCornerRadius="@dimen/cardview_default_radius">

        <android.support.v7.widget.AppCompatCheckBox
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@{shoppingItem.product.title}"
            android:checked="@={shoppingItem.purchased}"/>

    </android.support.v7.widget.CardView>
</layout>

ShoppingListItem.java

public class ShoppingListItem extends RealmObject implements Identifiable {

    @PrimaryKey private long id;
    private Product product;
    private boolean manual;
    private boolean purchased;

    @Override public long getId() { return id; }
    @Override public void setId(long id) { this.id = id; }

    public Product getProduct() { return product; }
    public void setProduct(Product product) { this.product = product; }

    public boolean isManual() { return manual; }
    public void setManual(boolean manual) { this.manual = manual; }

    public boolean isPurchased() { return purchased; }
    public void setPurchased(boolean purchased) { this.purchased = purchased; }
}

0 个答案:

没有答案