我正在尝试在Android Studio中构建一个进度条,其中最大值是根据我拥有的表格中的数据动态选择的。在一个类中,我创建一个全局变量并将其设置为整数。
然后我想在我的布局.xml文件中阅读它,这样我就可以动态更改进度条。即像这样:
<ProgressBar
android:id="@+id/determinateBar"
style="@android:style/Widget.ProgressBar.Horizontal"
android:progress="67"
android:max= // IntVariable here />
如何将类中的变量拉取到此文件中?
您可以像这样以编程方式设置进度栏值
在活动中
ProgressBar progressBarView = findViewById(R.id.progressBar);
// later when you want to set the value
progressBar.setProgress(progressStatus)
或在片段中
View root = inflater.inflate(R.layout.fragment_example, container, false);
ProgressBar progressBarView = root.findViewById(R.id.progressBar);
// later when you want to set the value
progressBar.setProgress(progressStatus)
有两种不同的方法来实现您想要的,第一种是推荐的方法,方法是通过将其添加到 android 标签中的应用级 build.gradle 文件中来启用项目中的数据绑定:
dataBinding {
enabled = true
}
然后,您必须将活动的表示者(包含所需的变量(添加到活动的布局 XML,如下所示:
<data>
<variable
name="presenter"
type="com.main.TheNameOfYourPresenter" />
</data>
最后,您可以在进度条中使用存储在演示器中的值,如下所示:
<ProgressBar
android:id="@+id/determinateBar"
style="@android:style/Widget.ProgressBar.Horizontal"
android:progress="67"
android:max="@{presenter.someIntStoredInThePresenter}"/>
第二种方法是通过访问活动类内的进度条并根据需要设置 max 属性以编程方式更改它:
progressBar.setMax(someInt);