如何使用数据绑定更新进度条百分比

How to update Progress Bar Percentage with Data Binding

我无法使用数据绑定更新 ProgressBar 进度。

这是我正在做的 -

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;
    }
}

请注意我已制作getProgress() @Bindable并通知BR.progress更新值current。这样当变量 current.

发生变化时,附加到 BR.progress 的 UI 会更新

在 XML 中,我尝试将 ProgressBar 附加到变量 progress

<ProgressBar
    style="@style/Widget.AppCompat.ProgressBar.Horizontal"
    android:progress="@{model.progress}"
    tools:progress="50" />

问题

一切都为我准备好了。现在,当我调用 setCurrent() 方法时,它应该反映在 UI 上。喜欢binding.getModel().setCurrent(50);。但事实并非如此。

这应该可以工作,除非 (current / total) * 100 不是每次都返回零。 returns 0 的方法,因为当两个整数值相除时,如果分母大于分子则它 returns 0。检查 the explained answer 。您可以更改 getProgress() 方法的实现。

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;
    }
}

还要检查您是否必须先初始化 total。并检查您如何计算进度。 确保你不应该忘记设置模型。

modelProgress=new ModelProgress();
mainBinding.setModel(modelProgress);