Android数据绑定:为什么getVariable()没有更新?

时间:2016-09-08 15:19:21

标签: java android data-binding

我已开始使用新项目的数据绑定。我已经能够使用binding.setVariable(myVariable)

在EditText中为经典用户表单(lastname,firstname,email ...)设置值

我想用户保存已编辑的信息,所以我尝试使用binding.getVariable()。但是,在用户编辑EditText后,值(姓氏,名字......)不会更新。那么,是否可以像这样使用它并且我做错了,或者我们只能像这样获得更新的EditText? :

String name = binding.editText_lastname.getText().toString();

这是我保存数据的方法(顺便说一句,我使用Retrofit2和Realm):

public void saveBtnClick(View view) {

    String name = binding.lastname.getText().toString(); //here I have the new value, after I edited the EditText


    ProfileREST profileREST = LoginREST.retrofit.create(ProfileREST.class);
    profileREST.updateUser(new ProfileBody(binding.getUserviewmodel().getUser()))
            .enqueue(new Callback<User>() { //here I'm getting User object using data binding, values haven't been updated
        @Override
        public void onResponse(Call<User> call, Response<User> response) {

            realm.beginTransaction();
            user.firstname = binding.getUserviewmodel().getUser().firstname;
            user.lastname = binding.getUserviewmodel().getUser().firstname;
            user.phoneNumber = binding.getUserviewmodel().getUser().firstname;
            user.isDarkMode = binding.getUserviewmodel().getUser().isDarkMode;
            realm.commitTransaction();
        }

        @Override
        public void onFailure(Call<User> call, Throwable t) {
            Toast.makeText(EditProfileActivity.this, getString(R.string.network_error), Toast.LENGTH_SHORT).show();
        }
    });
}

为了您的信息,我为User使用了两个类。一个扩展了RealmObject,一个扩展了BaseObservable(来自android.databinding包)。我必须将RealmObject包装为ViewModel并使用可绑定的注释。因为扩展RealmObject的类不能使用数据绑定。所以我的onCreate方法看起来像这样:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    binding = DataBindingUtil.setContentView(this, R.layout.activity_edit_profile);
    binding.getRoot().requestFocus();
    setSupportActionBar(binding.toolbar);
    getSupportActionBar().setDisplayShowTitleEnabled(false);


    realm = Realm.getDefaultInstance();
    user = realm.where(User.class).findFirst();
    if(user != null) {
        UserViewModel userViewModel = new UserViewModel(user);
        binding.setUserviewmodel(userViewModel);
    }

}

谢谢!

0 个答案:

没有答案