【问题标题】:How to change TextView's background color dynamically?如何动态更改 TextView 背景颜色?
【发布时间】:2015-12-17 05:54:23
【问题描述】:

我已经引用了this question 并使用circle.xml(在 res/drawable 中)为 TextView 实现了圆形背景,并将其设置为 android:background="@drawable/circle" 用于 TextView。但我需要的是,我需要通过代码动态设置背景颜色。就像下图的棒棒糖联系人应用一样

我怎样才能做到这一点?我需要圆形的 TextView 背景总是如上图所示

【问题讨论】:

    标签: android textview background-drawable


    【解决方案1】:

    您可以通过多种方式更改 TextView 背景颜色:

    textView.setBackgroundColor(Color.parseColor("#f44336"));
    

    或

    textView.setBackgroundColor(Color.RED);
    

    或

    textView.setBackgroundColor(Color.rgb(255, 0, 0));
    

    或

    textView.setBackgroundColor(getColor(R.color.red_color));
    

    还有很多其他的方式......

    编辑:

    如果要更改在可绘制文件中定义的 TextView 背景颜色,请按以下方式操作:

    GradientDrawable:

    GradientDrawable tvBackground = (GradientDrawable) textView.getBackground();
    tvBackground.setColor(Color.parseColor("#f44336"));
    

    StateListDrawable:

    StateListDrawable tvBackground = (StateListDrawable) textView.getBackground();
    tvBackground.setColorFilter(Color.parseColor("#f44336"), PorterDuff.Mode.SRC_ATOP);
    

    但如果你不想设置颜色过滤器,你可以按照link中的答案分别获取每个状态的drawable。

    【讨论】:

    • 是的,所有这些都是可以用来达到预期效果的选项。我只是想添加其余部分。
    • 但这并没有给我圆形背景形状。它只改变背景颜色。圆形背景将消失,新颜色将显示在方形背景中
    • 你没有在你的问题中提到你希望它是圆形的。
    • GradientDrawable 不适用于 TextView。出现错误:java.lang.ClassCastException:android.graphics.drawable.StateListDrawable 无法转换为 android.graphics.drawable.GradientDrawable
    • @drod 看来您使用的是 StateListDrawable 而不是 GradientDrawable。 StateListDrawable 可以有许多背景状态,因此没有明确的背景。所以试试我更新的答案。
    【解决方案2】:

    我想您想问一下如何生成随机颜色以设置为您的 textview 背景。嗯,有很多方法。例如;

    textview.setBackgroundColor(Color.rgb((int) (Math.random() * 255), (int) (Math.random() * 255), (int) (Math.random() * 255)));
    

    【讨论】:

    • 是的。但这不适用于生成随机颜色。 new Color((int)(Math.random() * 0x1000000))此声明无效
    【解决方案3】:

    我的文本视图有一个圆形定义为

    //circleshape.xml

    <?xml version="1.0" encoding="utf-8"?> 
    <shape xmlns:android="schemas.android.com/apk/res/android"; android:shape="oval"> 
    <solid android:color="@android:color/darker_gray" /> 
    <corners android:bottomRightRadius="8dp" android:bottomLeftRadius="8dp" android:topRightRadius="8dp" android:topLeftRadius="8dp"/> 
    </shape>
    

    我使用background="@drawable/circleshape"将它应用到Textview

    这使得 textview 循环。现在使用下面的代码来

    GradientDrawable tvBackground = (GradientDrawable) viewHolder.userInitialsText.getBackground();
    
    //myHexColorCode  is like "0xff00ff"
    tvBackground.setColor(Color.parseColor(myHexColorCode));
    

    【讨论】:

      猜你喜欢
      • 2011-12-26
      • 1970-01-01
      • 1970-01-01
      • 2014-04-05
      • 1970-01-01
      • 2013-07-11
      • 1970-01-01
      • 2015-07-22
      相关资源
      最近更新 更多