我怎样才能动态改变任何已经使用选择器的视图的颜色 xml

How can I DYNAMICALLY change the color of any VIEW which is already using a SELECTOR xml

例如,我有一个 selector xml 这样的:

view_round_corner_with_border.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle" >
 <corners
        android:bottomRightRadius="7dp" 
         android:bottomLeftRadius="7dp" 
         android:topLeftRadius="7dp" 
         android:topRightRadius="7dp"/>
 <stroke 
     android:color="@color/black"
     android:width="1dp"/>

 <solid 
     android:color="@color/primary_color"/>
 </shape>

在上面selector中我定义了背景色为primary_color。现在我想要做的是,我必须应用这个选择器,它将使圆角变为多个 EditTextTextView with不同颜色的背景。但问题是,如果我使用上面的选择器,它只会使背景成为 primary_color,而我想要不同的背景颜色。

如果我像这样动态改变颜色:

editText.setBackgroundResource(R.color.anyColor);

那么选择器状态将受到影响并且 editText 将不会保留圆角边缘。

What I have done for now is to make multiple selector with different color and use them depending on the logic for multiple EditText and TextView.

那么有什么东西可以让我使用单个选择器,它可以用于多个 EditTextTextView 来动态改变不影响圆角的背景颜色。

你可以试试这样的

Drawable background = textView.getBackground();
if (background instanceof ShapeDrawable) {
   ((ShapeDrawable)background).getPaint().
       setColor(getResources().getColor(R.color.anycolor));
} else if (background instanceof GradientDrawable) {
   ((GradientDrawable)background).
       setColor(getResources().getColor(R.color.anycolor));
}

我已经用下面的代码解决了它:

GradientDrawable drawable = (GradientDrawable) statusTextView
                            .getBackground();
drawable.setColor(context.getResources().getColor(
                            R.color.green_color));