Search code examples
androidmotionevent

find out when the user press a button the moves his finger outside of the button in android


suppose that I have a class for signUp button:

public class SignUp extends AppCompatButton {
public SignUp(Context context) {
    this(context, null);
}

public SignUp(Context context, AttributeSet attrs) {
    super(context, attrs, android.support.v7.appcompat.R.attr.buttonStyle);
    setFocusable(true);
    setFocusableInTouchMode(true);
}

@Override
public boolean onTouchEvent(MotionEvent event) {
    super.onTouchEvent(event);
    switch (event.getAction()) {
        case MotionEvent.ACTION_DOWN:
            requestFocus();
            this.setBackgroundColor(getResources().getColor(R.color.darkGreen));
            return true;
        case MotionEvent.ACTION_UP:
            this.setBackgroundColor(getResources().getColor(R.color.green));
            performClick();
            return true;
    }
    return false;
}

@Override
public boolean performClick() {
    super.performClick();
    return false;
    //TODO
}

and I have a button in my app called signUp and I have declared it like this in the XML file:

        <com.example.John.myapplication.SignUp
        android:layout_width="150dp"
        android:layout_height="wrap_content"
        android:text="@string/sign_up"
        android:background="@color/green"
        android:textColor="@color/whiteText"
        app:layout_constraintTop_toBottomOf="@+id/verify_password"
        android:layout_marginTop="40dp"
        app:layout_constraintLeft_toRightOf="parent"
        app:layout_constraintRight_toLeftOf="parent"
        android:id="@+id/sign_up"
        android:textSize="20sp"
        />

now if the user touches the signUp button the color of the button would be dark green and when he releases it the color of the button would be green again. but I want to add this feature so that when the user touches the button and then drag his finger out of the button, the button color change to green but I can't. none of the MotionEvent.ACTION_OUTSIDE,MotionEvent.ACTION_CANCEL and ... works. what should I do?

and I don't want to check that the finger is outside of the button by coordinated because when the button is oval it is such a huge work.


Solution

  • Just use a selector. https://developer.android.com/guide/topics/resources/color-list-resource

    example

    <?xml version="1.0" encoding="utf-8"?>
    <selector xmlns:android="http://schemas.android.com/apk/res/android">
    
        <item android:state_selected="true" android:color="@color/colorTextPrimaryDark" />
        <item android:color="@color/colorAccent3" />
    
    </selector>