Search code examples
androidontouchlistenermotionevent

Android onTouchListener MotionEvent unwanted release


I have this code that performs action when I touch and release a button. But turns out it releases immediately even though i'm not releasing it yet

switch (v.getId())

        {
        case(R.id.turnoffall):
            if(event.getAction() == MotionEvent.ACTION_DOWN);
            {
                v.setBackgroundResource(R.drawable.boffall2);
                Toast.makeText(getApplicationContext(), "Pressed! ! !",Toast.LENGTH_SHORT).show();
            }
            if(event.getAction() == MotionEvent.ACTION_UP);
            {
                v.setBackgroundResource(R.drawable.boffall1);
                Toast.makeText(getApplicationContext(), "Released.",Toast.LENGTH_SHORT).show();
            }
            break;
}

how can I do this right?


Solution

  • Try to change your code like this. I tested it. It works!

    main_activity.xml

    <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent" >
    
        <Button
            android:id="@+id/button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Button"
            android:layout_gravity="center" />
    </FrameLayout>
    

    MainActivity.java

    public class MainActivity extends ActionBarActivity {
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main_activity);
    
            Button button = (Button) findViewById(R.id.button);
            button.setOnTouchListener(new View.OnTouchListener() {
                @Override
                public boolean onTouch(View view, MotionEvent motionEvent) {
                    switch (view.getId()) {
                        case R.id.button:
                            switch (motionEvent.getAction()) {
                                case MotionEvent.ACTION_DOWN:
                                    Toast.makeText(getApplicationContext(), "Pressed! ! !", Toast.LENGTH_SHORT).show();
                                    return true;
                                case MotionEvent.ACTION_UP:
                                    Toast.makeText(getApplicationContext(), "Released! ! !", Toast.LENGTH_SHORT).show();
                                    return true;
                                default:
                                    return false;
                            }
                        default:
                            return false;
                    }
                }
            });
        }
    }