android - GradientDrawable绘制不同颜色的setColor方法

标签 android android-ui android-drawable shapedrawable

我在 layer-list 中有一个 shape,我的目标是在运行时以编程方式更改 shape 的颜色。我有十六进制代码的字符串,我使用 Color.parseColor() 解析它,然后传递给 setColor 方法。每当我运行该应用程序时,它都会显示与我预期不同的颜色。

这是我的 XML 文件代码:

<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >


<item 
    android:id="@+id/lvbg"
    android:top="1dp">
    <shape
        android:id="@+id/listview_background"
        android:shape="rectangle" >
        <size
            android:height="220dp"
            android:width="600dp" >
        </size>

        <solid android:color="@android:color/black"></solid>

        <corners android:radius="15dp" />
    </shape>
</item>
</layer-list>

这是我在 CustomAdapter 中的代码:

convertView = mInflater.inflate(R.layout.student_info_selection_fragment_icon, null);
holder = new ViewHolder();
holder.collegeBG=(LayerDrawable)convertView.getResources().getDrawable(R.drawable.rectangle);
holder.bg = (GradientDrawable)holder.collegeBG.findDrawableByLayerId(R.id.lvbg);
String color = "#FF" + rowItem.getCollegeColor();
holder.bg.setColor(Color.parseColor(color));

例如,当我输入 #FF1D0A63 时,我会得到黑色或棕色,完全不同的颜色。 谢谢

最佳答案

我仍然不知道问题出在哪里,但我意识到当我在 xml 中使用 layer-list 并将其作为背景分配给 View ,并尝试更改 的颜色时layer-list 中的 >shape 我遇到了这个问题。

所以我解决了将我的背景 shapelayer-list 分开的问题。

我将我的背景 shape 放到另一个文件中:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/listview_background"
    android:shape="rectangle" >

    <size
        android:height="220dp"
        android:width="600dp" >
    </size>
    <solid android:color="@android:color/black" > </solid>
    <corners android:radius="15dp" />

</shape>

我将它作为背景分配给 TextView

我使用 layer-list 的原因是组合 2-3 个形状并使它们渐变并给它们圆角。相反,我使用了 ViewTextView 并将形状分配给它们作为背景并且它起作用了。

这是我的新 CustomAdapter:

convertView = mInflater.inflate(R.layout.student_info_selection_fragment_icon, null);
holder = new ViewHolder();
holder.tvBackground = (TextView) convertView.findViewById(R.id.tvSelectionCollegeBackground);
GradientDrawable background = (GradientDrawable) holder.tvBackground.getBackground();


String color = "#FF" + rowItem.getCollegeColor();
background.setColor(Color.parseColor(color));
holder.tvBackground.setBackground(background);

关于android - GradientDrawable绘制不同颜色的setColor方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16964916/

相关文章:

java - 格式化日期并返回日期,而不是字符串

android - "The layout has no declaration in the base layout folder"

android - 更改 ActionBarSherlock 背景颜色

android - 从对话框中删除边框,填充

android - 如何覆盖 Android 应用程序中音量按钮的行为?

java - 在没有 Google Cloud 的情况下同步 Android 设备

Android View.onDraw() 总是有一个干净的 Canvas

java - 循环加载许多图像时抛出 Resources.NotFoundException

java - imageview和drawables之间的碰撞检测

android - 为什么 LinearGradient 构造函数的这个参数似乎不起作用?