I am unable to update ProgressBar progress with data binding.
Here's what I am doing -
ModelProgress.java
public class ModelProgress extends BaseObservable {
private int total;
private int current;
public void setCurrent(int current) {
this.current = current;
notifyPropertyChanged(BR.progress);
}
@Bindable
public int getProgress() {
return (current / total) * 100;
}
}
Please Note I have made getProgress() @Bindable
and notifying BR.progress
on updation of value current
. So that UI attached to BR.progress
update when change in variable current
.
In XML I tried to attach ProgressBar
with variable progress
.
<ProgressBar
style="@style/Widget.AppCompat.ProgressBar.Horizontal"
android:progress="@{model.progress}"
tools:progress="50" />
It's all set for me. Now when I call setCurrent() method, it should reflect on UI. Like binding.getModel().setCurrent(50);
. But it doesn't.
This should work unless (current / total) * 100
is not returning zero each time.
The method returns 0, because when dividing two integer values, if denominator is greater than numerator then it returns 0. Check the explained answer . You can change your getProgress()
method's implementation.
public class ModelProgress extends BaseObservable {
private int total=100;
private int current;
public void setCurrent(int current) {
this.current = current;
notifyPropertyChanged(BR.progress);
}
@Bindable
public int getProgress() {
return current * 100 / total;
}
}
Also check you have to initialized total
first. and check how are you calculating the progress.
Make sure you should not forget to set model .
modelProgress=new ModelProgress();
mainBinding.setModel(modelProgress);