Android:如何以编程方式更改Drawable选择器的颜色取决于条件?

MKY*_*MKY 1 java android android-selector android-drawable

我有一个按钮

<Button
 android:id="@+id/loginButton"
 android:layout_width="35dp"
 android:layout_height="35dp"
 android:background="@drawable/button_shape"
 android:text="@string/login"
 android:textColor="#ffffff"
 android:textSize="12sp" />
Run Code Online (Sandbox Code Playgroud)

以下是button_shape.xml

<?xml version="1.0" encoding="utf-8"?>
 <selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_focused="true" android:state_pressed="true" android:drawable="@drawable/button_gradient_login" />
<item android:state_focused="false" android:state_pressed="true" android:drawable="@drawable/button_gradient_login" />
<item>
    <shape xmlns:android="http://schemas.android.com/apk/res/android"
        android:shape="rectangle">
        <size android:height="16dp" />
        <solid android:color="@color/valid_btn_clr"></solid>
        <corners android:radius="10dp"></corners>
    </shape>
</item>
Run Code Online (Sandbox Code Playgroud)

以下是button_gradient_login.xml

<?xml version="1.0" encoding="utf-8"?>
   <layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
<item>
   <shape xmlns:android="http://schemas.android.com/apk/res/android">
        <gradient android:angle="360" android:startColor="@color/red"     android:endColor="@color/green"/>
        <corners android:radius="4dp"></corners>
    </shape>
</item></layer-list>
Run Code Online (Sandbox Code Playgroud)

现在我想更改button_shape.xml的背景颜色,并在运行时按下button_gradient_login.xml的开始和结束颜色取决于我的条件

小智 5

您可以以编程方式创建可绘制选择器这是state_activated的代码.请参考以下代码.

        GradientDrawable gradientDrawable = new GradientDrawable();
        gradientDrawable.setStroke((int) context.getResources().getDimension(R.dimen.dp1), Color.BLACK);
        gradientDrawable.setCornerRadius(context.getResources().getDimension(R.dimen.dp5));
        gradientDrawable.setColor(((MainActivity) context).getBgColor());

        GradientDrawable gradientDrawableDefault = new GradientDrawable();
        gradientDrawableDefault.setStroke((int) context.getResources().getDimension(R.dimen.dp1), Color.BLACK);
        gradientDrawableDefault.setCornerRadius(context.getResources().getDimension(R.dimen.dp5));
        gradientDrawableDefault.setColor(Color.WHITE);

        StateListDrawable stateListDrawable = new StateListDrawable();
        stateListDrawable.addState(new int[]{android.R.attr.state_activated}, gradientDrawableDefault); // if activated true
        stateListDrawable.addState(StateSet.WILD_CARD, gradientDrawable); // rest all the state
Run Code Online (Sandbox Code Playgroud)