Android中带文本的内部圆角垂直ProgressBar实现问询
实现带圆角的垂直ProgressBar
你当前的实现问题出在<clip>标签的裁剪逻辑上——当进度从底部向上增长时,<clip>会直接裁切形状,导致进度部分的顶部圆角被切掉。下面是两种可行的解决方法:
方案一:用scale替代clip(推荐)
通过缩放形状实现进度增长,能完整保留圆角效果:
<?xml version="1.0" encoding="utf-8"?> <layer-list xmlns:android="http://schemas.android.com/apk/res/android"> <!-- 背景层 --> <item android:id="@android:id/background"> <shape> <solid android:color="#ffffff" /> <corners android:radius="@dimen/xxs" /> </shape> </item> <!-- 进度层 --> <item android:id="@android:id/progress"> <scale android:scaleHeight="100%" android:scaleGravity="bottom"> <shape> <solid android:color="#E9E9E9" /> <corners android:radius="@dimen/xxs" /> </shape> </scale> </item> </layer-list>
布局中使用该Drawable时,需指定垂直样式:
<ProgressBar android:id="@+id/vertical_progress" android:layout_width="wrap_content" android:layout_height="200dp" android:progressDrawable="@drawable/vertical_progress_bar" android:indeterminate="false" style="?android:attr/progressBarStyleVertical" />
方案二:适配低版本的动态 inset 方案
如果需要兼容Android 3.0以下版本,可通过inset配合代码动态调整进度区域:
- 定义进度形状(
progress_shape.xml):
<?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android"> <solid android:color="#E9E9E9" /> <corners android:radius="@dimen/xxs" /> </shape>
- 修改layer-list布局:
<?xml version="1.0" encoding="utf-8"?> <layer-list xmlns:android="http://schemas.android.com/apk/res/android"> <item android:id="@android:id/background"> <shape> <solid android:color="#ffffff" /> <corners android:radius="@dimen/xxs" /> </shape> </item> <item android:id="@android:id/progress"> <inset android:insetTop="0dp" android:insetBottom="0dp"> <bitmap android:src="@drawable/progress_shape" android:gravity="bottom" /> </inset> </item> </layer-list>
- 代码中动态调整inset值:
ProgressBar progressBar = findViewById(R.id.vertical_progress); progressBar.setProgress(50); // 设置目标进度 Drawable progressDrawable = progressBar.getProgressDrawable(); if (progressDrawable instanceof LayerDrawable) { LayerDrawable layerDrawable = (LayerDrawable) progressDrawable; Drawable progressLayer = layerDrawable.findDrawableByLayerId(android.R.id.progress); if (progressLayer instanceof InsetDrawable) { InsetDrawable insetDrawable = (InsetDrawable) progressLayer; int totalHeight = progressBar.getHeight(); int progressHeight = (int) (totalHeight * (progressBar.getProgress() / 100f)); int insetTop = totalHeight - progressHeight; insetDrawable.setInset(0, insetTop, 0, 0); } }
注意事项
- 确保
@dimen/xxs是有效圆角尺寸,比如4dp或8dp - 方案一仅支持Android 3.0(API 11)及以上版本
- 测试时覆盖不同进度值(10%、50%、100%),验证圆角在所有状态下的显示效果
内容的提问来源于stack exchange,提问作者Shakib hasan
相关产品推荐
相关产品推荐

