简体   繁体   中英

Change Colors States of Button using a Generic Drawable

I have Button that is using a custom drawable to make rounded corners. But I would like to change the background colors for the different states, focused, pressed etc..

I have used the below in onCreate to change the overall background color. But I don't know how to target the state_pressed to change its color too.

Any help?

in onCreate

DrawableCompat.setTint(btnLogin.getBackground(), ContextCompat.getColor(getApplicationContext(), R.color.colorGreen));

Button

 <Button
            android:id="@+id/btnLogin"
            style="?android:textAppearanceSmall"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="16dp"
            android:background="@drawable/button_rounded"
            android:text="Sign In"
            android:textColor="@android:color/white"
            android:textStyle="bold" />

button_rounded.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true">
        <shape android:shape="rectangle">
            <corners android:radius="10dip" />

            <solid android:color="#5c89c1" />
        </shape>
    </item>
    <item android:state_focused="true">
        <shape android:shape="rectangle">
            <corners android:radius="10dip" />

            <solid android:color="#204778" />
        </shape>
    </item>
    <item>
        <shape android:shape="rectangle">
            <corners android:radius="10dip" />

            <solid android:color="#204778" />
        </shape>
    </item>
</selector>

Try this and it work for me:

 Drawable drawable = getResources().getDrawable(R.drawable.button_rounded); drawable = DrawableCompat.wrap(drawable); DrawableCompat.setTint(drawable.mutate(), getResources().getColor(R.color.colorGreen)); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM