android - Update component element from @Bindable POJO property - data binding

237 Views Asked by At

I am experiencing with Data Binding. I know by making my POJO (User) extending BaseObservable I can update the linked element in the layout by, for example using android:text="@={user.name}" but I am interested in doing different staff on property changed. For example, applying some logic, or showing a toast message. I expected was something like the liveDataObject.observe() method but it is not reacting when a property is changed. Here is my code:

ViewModel:

public class MainViewModel extends ViewModel {
  private MutableLiveData<User> user; //getter and setter

Model:

public class User extends BaseObservable {
 private String name;
 public User() {}

 @Bindable
 public String getName() {
  return name;
 }

 public void setName(String name) {
  this.name = name;
  notifyPropertyChanged(BR.name);
 }
}

Fragment:

@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
 @Nullable Bundle savedInstanceState) {
 mDataBinding = DataBindingUtil.inflate(getLayoutInflater(), R.layout.main_fragment, container, false);
 mDataBinding.setLifecycleOwner(this);
 return mDataBinding.getRoot();
}

@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
 super.onActivityCreated(savedInstanceState);
 mViewModel = new ViewModelProvider(getActivity()).get(MainViewModel.class);

 mViewModel.getUser().observe(getViewLifecycleOwner(), user ->
  Toast.makeText(getActivity().getApplicationContext(), user.getName(), Toast.LENGTH_SHORT).show()
 );
}
0

There are 0 best solutions below