Solution 1 :
Look at the below code.
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns_android="http://schemas.android.com/apk/res/android">
<item android_drawable="@drawable/button_pressed"
android_state_pressed="true" />
<item android_drawable="@drawable/button_focused"
android_state_focused="true" />
<item android_drawable="@drawable/button_default" />
</selector>
the attribute state_pressed or the state_focused should do the job.
see the following link for more guidance
Solution 2 :
UPDATE
I can do it with this code:
private Rect rect; // Variable rect to hold the bounds of the view
public boolean onTouch(View v, MotionEvent event) {
if(event.getAction() == MotionEvent.ACTION_DOWN){
// Construct a rect of the view's bounds
rect = new Rect(v.getLeft(), v.getTop(), v.getRight(), v.getBottom());
}
if(event.getAction() == MotionEvent.ACTION_MOVE){
if(!rect.contains(v.getLeft() + (int) event.getX(), v.getTop() + (int) event.getY())){
// User moved outside bounds
}
}
return false;
}
Problem :
I use a XML file to display a button with 2 states (normal, pressed). How can I
find out when the button is touched but the cursor is out?
I want button effect like this
button not touched
button touched
button touched but finger hasn’t been lifted
Here is the XML file I use:
<selector xmlns_android="http://schemas.android.com/apk/res/android">
<item android_state_pressed="true" android_drawable="@drawable/button_press" />
<item android_drawable="@drawable/button_nopress" />
</selector>
And here is my Java class:
button = findViewById(R.id.b1);
button.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN){
button.setPadding(0, 55, 0, 0);
} else if (event.getAction() == MotionEvent.ACTION_UP) {
button.setPadding(0, 0, 0, 0);
}
return false;
}
});
And here is my button with my code:
button touched but finger hasn’t been lifted
Comments
Comment posted by Lucas
It’s not working.