android.widget.ProgressBar
是 Android 系统中用于显示操作进度的视图组件,它可以显示不确定进度的旋转动画或确定进度的水平进度条。
当遇到 "android.widget.ProgressBar中没有可用的默认构造函数" 错误时,通常是因为以下原因之一:
ProgressBar 通常应该在 XML 布局文件中声明:
<ProgressBar
android:id="@+id/progressBar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true" />
然后在 Activity/Fragment 中通过 findViewById 获取:
ProgressBar progressBar = findViewById(R.id.progressBar);
如果需要在代码中创建 ProgressBar,必须提供 Context 参数:
ProgressBar progressBar = new ProgressBar(context);
如果创建自定义 ProgressBar 子类,必须实现所有必要的构造函数:
public class CustomProgressBar extends ProgressBar {
public CustomProgressBar(Context context) {
super(context);
}
public CustomProgressBar(Context context, AttributeSet attrs) {
super(context, attrs);
}
public CustomProgressBar(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public CustomProgressBar(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
}
}
ProgressBar
或 ProgressBar(Indeterminate)
ProgressBar(horizontal)
并设置 progress
属性CircularProgressIndicator
或 LinearProgressIndicator
(在 Material Components 库中)// 显示
progressBar.setVisibility(View.VISIBLE);
// 隐藏
progressBar.setVisibility(View.GONE);
progressBar.setMax(100); // 设置最大值
progressBar.setProgress(50); // 设置当前进度
通过以上方法,可以避免 ProgressBar 构造函数相关的问题,并正确使用 ProgressBar 组件。
没有搜到相关的文章