Two-way databinding(in xml), ObservableField, BaseObservable , which one I should use for the two-way databinding?

前端 未结 2 1545
误落风尘
误落风尘 2021-02-05 10:30

I have used data-binding for a while, even now it is not available for JDK 8 and API 24 now. I still find a way to use the data binding in a easier way. But when I use the follo

2条回答
  •  醉梦人生
    2021-02-05 11:22

    Your Student_XML2WAY.java won't work with 2-way Binding, since it does not fulfill the requirements to do so (BaseObservable, Bindable or something like that).

    I would use BaseObservable if I will directly access the model, just like in your Student_Extend. I will have an instance of Student_Extend in my Activity and I will set the variable in onCreate:

    Student mStudent = new Student("John Doe", 42); //
    binding.setStudent(mStudent);
    //later:
    mStudent.setAge(37);
    

    If implemented correctly, this will also change the Age in your UI (as well as in your model).

    If you do not want to access your model directly and want to use a ViewModel, I work with ObervableFields:

    public class Student {
        private String name;
        private int age;
        //Corresponding setters and getters
    }
    
    
    public class StudentViewModel {
        private ObservableField mStudentField = new ObservableField<>();
    
        //if I have a large model class, and only want to use some fields, 
        //I create some getters (and setters, for the two way attributes)
        //Something like this:
    
        public int getAge() {
            return mStudentField.get().getAge();
        }
        public void setAge(int newAge) {
            return mStudentField.get().setAge(newAge);
        }
    }
    

    So, I create an instance of StudentViewModel in my Activity and set it to the binding. Pseudo-xml would look like this:

    
        
             
        
        
    
    

    So, the ViewModel approach is "clearer" since you outsource almost everything that has to do with views. Put your BindingAdapter, click methods, converter methods there and keep your Activity clean. Also, you do not directly change your model. This approach can be an overkill for simple classes and projects. ;)

    If you want to see a full, example that uses DataBinding and MVVM, check out Droids on roids approach on this.

提交回复
热议问题