【问题标题】:Change TextView background based on width percentage根据宽度百分比更改 TextView 背景
【发布时间】:2022-01-18 03:53:37
【问题描述】:

我有一个浅绿色背景的简单 TextView:

<TextView
    android:layout_width="match_parent"
    android:layout_height="20dp"
    android:background="@color/lightgreen"
/>

基本上,我将此 TextView 用作自定义“概览/进度条”。 因此,我想改变不同颜色的背景。

例如:

0%-25% 的宽度 = 浅绿色

25%-66% 的宽度 = 黄色

66%-100% 的宽度 = 红色

所以看起来像这样:


它应该是这样的:

有什么好的解决办法吗?

我尝试过使用不同的 Segment ProgressBar 库,但是它们都没有设置颜色“分隔符”的百分比时间的选项

【问题讨论】:

  • 文本视图是否包含文本?还是只是一种背景颜色?
  • @Amjad 它只是一个背景色
  • 你可以为 4 个孩子使用带有权重的 LinearLayout 吗?它会更快。您还可以使用 xml 来声明三种形状颜色。
  • 也许this 会从我以前的回答中得到帮助。

标签: android background textview background-color android-progressbar


【解决方案1】:

您可以使用ClipDrawable 执行此操作。 使用进度层列表创建一个层列表 (LayerDrawable),例如:

progress_bg.xml

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <clip android:drawable="@color/red" />
    </item>
    <item>
        <clip android:drawable="@color/yellow" />
    </item>
    <item>
        <clip android:drawable="@color/green" />
    </item>
</layer-list>

并将其用作 TextView 的背景。

<TextView
    android:id="@+id/progress_text_view"
    android:layout_width="match_parent"
    android:layout_height="20dp"
    android:background="@drawable/progress_bg" />

应用进度值:

private static final int MAX_LEVEL = 10_000;
private static final float[] LEVELS_PCT = new float[]{.25f, .66f, 1f};
//
final LayerDrawable progressBg = (LayerDrawable) progressTextView.getBackground();
for (int index = 0, count = LEVELS_PCT.length; index < count; index++) {
    progressBg.getDrawable(count - 1 - index)
            .setLevel((int) (MAX_LEVEL * LEVELS_PCT[index]));
}

【讨论】:

    【解决方案2】:

    试试这个方法:

    //Get the percentage ProgressBar and then apply the command to the text
    float x = LoadingProgress.getProgress() ;
            
    
    if (x > 0.2 && x < 0.6){
                    MyTextView.setTextColor(getResources().getColor(R.color.colorGreen));
                }
                else if (x > 0.7)
                {
                    MyTextView.setTextColor(getResources().getColor(R.color.colorYellow));
                } else {
                    MyTextView.setTextColor(getResources().getColor(R.color.colorRed));
                }
    

    希望此解决方案对您有所帮助

    【讨论】:

    • 1) 这会改变文本颜色,而不是背景颜色。 2)它一次只显示一种颜色,而不是三种
    • 只改变进度条的背景颜色和颜色分割?
    • 这里有一些关于如何创建自定义进度条的答案,您可以稍微控制一下编程文件以获得所需的结果
    猜你喜欢
    • 2020-06-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-03
    • 2012-12-17
    • 2023-03-03
    相关资源
    最近更新 更多