如何给条形图这样的背景渐变

How to give background gradation like bar chart

如果我想在TextView中做如下图的渐变,我应该怎么做?有什么想法或解决办法吗??

(渐变的宽长取决于TextView中文本的值)

像这样定义可绘制资源文件

<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <gradient
        android:angle="180"
        android:endColor="@color/your_color"
        android:startColor="@color/your_color2"
        android:type="linear" />
</shape>

并将其用作视图的背景

<FrameLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <View
        android:layout_width="match_parent"
        android:layout_height="20dp"
        android:id="@+id/view"
        android:background="@drawable/your_gradient"
        />

    <TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="30"
    android:id="@+id/percentageTextview"
    />

</FrameLayout>

在你的 activity 上使用这个

View background = (View) findViewById(R.id.view);
TextView textView = (TextView) findViewById(R.id.percentageTextview);

DisplayMetrics displayMetrics = getResources().getDisplayMetrics();
int  screenWidthInPix = displayMetrics.widthPixels;

ViewGroup.LayoutParams params = background.getLayoutParams();
params.width = (screenWidthInPix * Integer.parseInt(textView.getText().toString()))/100;
background.setLayoutParams(params);