【问题标题】:How to bind object with two layouts?如何将对象与两个布局绑定?
【发布时间】:2017-03-10 00:10:58
【问题描述】:

我有这样的模型

public class MyCheckedVM extends BaseObservable {
     @Bindable
ObservableBoolean observableBoolean = new ObservableBoolean();


@Bindable
public ObservableBoolean getObservableBoolean() {
    return observableBoolean;
}

@Bindable
public void setObservableBoolean(ObservableBoolean observableBoolean) {
    this.observableBoolean = observableBoolean;
}

public void onCheckChanged(CompoundButton view, boolean isChecked) {
    Log.d(TAG, "onCheckChanged");

}

我将此模型设置为与ToggleButton 和内部Fragment 的主要活动绑定,其中也有这样的按钮

   <ToggleButton
    android:onCheckedChanged="@{viewModel.onCheckChanged}"
    android:checked="@{viewModel.observableBoolean}"
    android:id="@+id/toggle"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

但是当我尝试点击任何按钮时,它们都在相互独立地发生变化。也许我将模型绑定到Fragmnet的方式是错误的@

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
  FragmentExampleBinding fragmentExampleBinding =   DataBindingUtil.inflate(inflater, R.layout.fragment_example, container, false);

    fragmentExampleBinding.setViewModel(((MainActivity) getActivity()).getViewModel()); //getter in MainActivity for instance of viewModel

    return fragmentExampleBinding.getRoot();
}

【问题讨论】:

    标签: android mvvm data-binding observable


    【解决方案1】:

    我看到的一个问题是您使用了setObservableBoolean。您有一个BaseObservable,因此如果您调用 setter,您应该通知属性更改。

    但这只是因为您以不寻常的方式使用ObservableBoolean。最佳做法是始终将它们用作public final 字段。如果这样做,则不需要使用BaseObservable 作为基类:

    public class MyCheckedVM {
        public final ObservableBoolean observableBoolean = new ObservableBoolean();
    
        public void onCheckChanged(CompoundButton view, boolean isChecked) {
            Log.d(TAG, "onCheckChanged");
        }
    }
    

    您可以在 Observable 类(或 BaseObservable)中混合可观察字段。只需将您的可观察字段设为public final 并确保在可绑定属性的设置器中调用notifyPropertyChanged(BR.myField)

    【讨论】:

    • 感谢您的建议!我尝试通过在 onCheckedChanged 中将我的可观察布尔字段设置为 true 以使它们都被检查,但是我将由你来完成
    猜你喜欢
    • 2016-07-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-02
    • 2020-09-07
    • 2019-09-30
    • 2018-04-08
    相关资源
    最近更新 更多