【问题标题】:How to update Progress Bar Percentage with Data Binding如何使用数据绑定更新进度条百分比
【发布时间】:2019-02-12 06:49:26
【问题描述】:

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

这就是我正在做的 -

  • 我有一个模型用于保存 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 中,我尝试使用变量 progress 附加 ProgressBar

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

问题

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

【问题讨论】:

  • 使当前为ObservableField 也发布 ViewModel 类

标签: android data-binding android-databinding


【解决方案1】:

这应该可以工作,除非(current / total) * 100 不是每次都返回零。 该方法返回 0,因为在将两个整数值相除时,如果分母大于分子,则返回 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);

【讨论】:

  • True!,getProgress() 返回 0,当我将其更改为 (int) (((float)current / (float)total) * 100); 时它起作用了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-08-06
  • 2012-12-23
  • 1970-01-01
  • 1970-01-01
  • 2023-03-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多