Domanda

This has probably already been asked but I can't find it.

So I made a custom button in android with a normal image and a "pressed" image. Only problem is, when I press the button on the phone, and while pressed I drag my finger off the image and release, the button image remains as pressed instead of reverting back to the normal, unpressed image. The default android button is formatted so that when you do this "drag-off" event, the button goes back to normal as soon as your finger leaves the dimensions of the button.

main.java:

but1.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                but1.setBackgroundResource(R.drawable.bluewhiteplainpressed);
                return false;
            }
        });

        but1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(!but1.isActivated()){
                    but1.setBackgroundResource(R.drawable.bluewhiteplain);

button's code in menu.xml:

<Button
            android:id="@+id/button1pos"
            android:layout_width="0dip"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:background="@drawable/bluewhiteplain"
            />
È stato utile?

Soluzione

Remove OnTouchListener and put a drawable selector in background button.

Android: How to Make A Drawable Selector

Altri suggerimenti

You can make a custom drawable selector for 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/cell_top_selected" />
    <item android:drawable="@drawable/cell_top" />
</selector>
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top