简体   繁体   中英

How to smoothly change colors when hold on button on android?

In my app, I have a button, that uses a style, and the style references a selector background, which then defined a shape xml for its default and pressed states.

If I click the button, it instantly changes to the pressed state.

How can I make it so it, smoothly changes color as you hold it, and it takes 1 second to fully transition, like a transition effect? (if you let go, it should transition back to original state)

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:state_enabled="false"
        android:drawable="@drawable/circle_button_default" />
    <item
        android:state_pressed="true"
        android:state_enabled="true"
        android:drawable="@drawable/circle_button_pressed" />
    <item
        android:state_enabled="true"
        android:drawable="@drawable/circle_button_default" />
</selector>

circle_button_default.xml

<?xml version="1.0" encoding="utf-8"?>

<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="oval">
    <solid android:color="#ff9517"/>
    <stroke android:width="2sp" android:color="#fff" />
</shape>

circle_button_pressed.xml

<?xml version="1.0" encoding="utf-8"?>

<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="oval">
    <solid android:color="#d47300"/>
    <stroke android:width="2sp" android:color="#fff" />
</shape>

Anyone know how to do this?

Thanks

you can use this to set animation for the button

Animation fadeout = AnimationUtils.loadAnimation(this, R.anim.fadeout);

press Ctrl+Shift+'O' to add necessary packages then apply the animation to the buttons as follows:

public void click (View v){
 button1.startAnimation(fadeout);}

If you are planning to animate many buttons stick them to a grid and apply the animation to it.

you can create a OnTouchListener on your button and then from there you can check if button current pressed or already pressed

example:

    youBUtton.setOnTouchListener(new OnTouchListener() {

    public boolean onTouch(View v, MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_UP) {
           // on release
        }else{
           // on touch
        }
        return false;
    }
});

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