首页 > 解决方案 > 如何在Android Kotlin中根据其宽度将圆角应用于视图

问题描述

我正在制作一个自定义进度条,如下图所示:

在此处输入图像描述

在此处输入图像描述

在此处输入图像描述

基本上,我创建了一个可绘制的 xml 背景文件:

<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <solid
        android:color="@color/jungleGreen"/>
    <corners
        android:bottomLeftRadius="40dp"
        android:topLeftRadius="40dp"/>
</shape>

然后我将它应用于我正在使用的视图:

<View
            android:id="@+id/progress_bar_placeholder_view"
            android:layout_width="match_parent"
            android:layout_height="30dp"
            android:layout_marginEnd="45dp"
            android:background="@drawable/background_filled_patronage_progressbar"
            app:layout_constraintTop_toTopOf="parent"/>

完全没问题,我可以实现场景 1 和 2,但是当栏越来越接近末端时,如何以编程方式设置视图右上角和右下角的圆角,直到看起来像照片3?

谢谢。

标签: androidxmlandroid-layoutkotlinprogress-bar

解决方案


试试这个

    public static void customView(View v, int backgroundColor, int borderColor)
 {
            GradientDrawable shape = new GradientDrawable();
            shape.setShape(GradientDrawable.RECTANGLE);
            shape.setCornerRadii(new float[] { 8, 8, 8, 8, 0, 0, 0, 0 });
            shape.setColor(backgroundColor);
            shape.setStroke(3, borderColor);
            v.setBackground(shape);
        }

资料来源:如何以编程方式创建 android 形状背景?


推荐阅读