在Android Kotlin中如何根据视图的宽度将圆角应用于视图

在Android Kotlin中如何根据视图的宽度将圆角应用于视图,android,xml,android-layout,kotlin,progress-bar,Android,Xml,Android Layout,Kotlin,Progress Bar,我正在制作自定义进度条,如下图所示: 基本上,我创建了一个可绘制的xml背景文件: <?xml version="1.0" encoding="UTF-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android"> <solid android:color="@color/jungleGreen"/> <corners a

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

基本上,我创建了一个可绘制的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

谢谢。

试试这个

    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);
        }

来源:

Madhav的解决方案对我很有效,因此基本上我需要通过视图的宽度,然后计算角半径数并将其放入gradientDrawable中,如下所示:

    private fun setupGraphBackground(view: View, graphWidth: Int) {
            val gradientDrawable = GradientDrawable()
            gradientDrawable.shape = GradientDrawable.RECTANGLE
            gradientDrawable.setColor(resources.getColor(R.color.jungleGreen))
            gradientDrawable.setStroke(0, null)
            gradientDrawable.cornerRadii = floatArrayOf(45f, 45f, 
                graphWidth * calculationRules, graphWidth * calculationRules, 
                graphWidth * calculationRules, graphWidth * calculationRules, 
                45f, 45f)
            view.background = gradientDrawable
        }

其中as calculation rules是我想要的规则,这样我就可以得到右上角和右下角的正确半径

我不完全确定如何在原始XML中进行绘制,但您始终可以绘制所有4个圆角,并应用一个剪辑(矩形)来删除可绘制图形中不需要的部分。@Pawel您能更具体一点吗?我知道有一种方法可以绘制视图的背景,但不确定如何根据其宽度更改角?测试类似于此的内容。宽度-((view.width)/(n))更改(n)无论你想要什么,我想我现在明白该怎么做了:)谢谢,伙计,我会试试。如果你需要kotlin版本,我可以帮你。试过了,它对我很好,我把它转换成kotlin,贴在下面。谢谢你的帮助。