Question

I m making an app and i want to use custom button skins . The code i use for changing background when the button is pressed is the following :

 button3.setOnTouchListener(new OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            if(event.getAction() == MotionEvent.ACTION_DOWN) {
                button3.setBackgroundResource(R.drawable.blue_buttonn);
            } else if (event.getAction() == MotionEvent.ACTION_UP) {
                button3.setBackgroundResource(R.drawable.black_buttonn);
            }else if (event.getAction() == MotionEvent.ACTION_HOVER_MOVE) {
                button3.setBackgroundResource(R.drawable.black_buttonn);
            }
            return false;
        }
    });

This code is supposed to make a button blue when its being pressed and return it to black when released. It works but if you click the button and drag away from it the event ACTION_UP is not triggered . What event should i use in this case ?

I edited my code adding the event HOVER_MOVE which works when you move the finger out of the button. But because these buttons are inside an item of a custom list view if you move the finger outside of the current item the event HOVER_MOVE is not triggered.

enter image description here

Was it helpful?

Solution

Try this

<?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/default_bgnd" />

<item     android:state_focused="true"        
android:drawable="@drawable/new_green" />

<item     android:state_pressed="true"        
android:drawable="@drawable/new_green" />

<item     android:state_checked="true"        
android:drawable="@drawable/new_green"/>

<item     android:state_selected="true"        
android:drawable="@drawable/new_green" /> 
</selector> 

Place this xml in drawables folder and Set this as the Backgroud to your button in xml Good Luck

OTHER TIPS

Try returning true instead of false. True indicates that listener consumed the TouchEvent.

Try this.

onButton.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if(ParentalSet.equalsIgnoreCase("OFF")){
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
((TextView) v).setTextColor(0xFF000000);
onButton.setBackgroundDrawable(getResources().getDrawable(buttonGlow));
break;
case MotionEvent.ACTION_UP:
onButton.setTextColor(Color.parseColor                                                                 (OptimumConstants.CODE_000000));
onButton.setBackgroundDrawable(getResources().getDrawable                                           (R.drawable.new_off));
break;
default:
break;
 }
}
return false;
}
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top