onClickListener for the WHOLE screen

13,517

Solution 1

in your layout verify that :

android:clickable="true"
android:focusable="true"
android:focusableInTouchMode="true"

then try to use onTouchListener

then try :

yourActivityLayout.setOnTouchListener(new View.OnTouchListener() {  
        @Override
        public boolean onTouch(View arg0, MotionEvent arg1) {
           // action to do
            return true;//always return true to consume event
        }
    });

Solution 2

Do this way to put touch event on Whole Activity

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {

        if (event.getAction() == MotionEvent.ACTION_UP) {

            // do your work here
            return true;
        } else {
            return false;
        }
    }

}

Solution 3

Have your Activity or Fragment implement OnClickListener, and then assign it as your click listener to every view and or layout.

in the first line of the function just run some logic,

@override
public void onClick(view v)
{
   if(isMusicPlaying)
      stopMusic();

   // here run the rest of your logic
   if (v == someButton){}

}

Solution 4

If you want if touch the layout , set click listener to the layout it self

Share:
13,517
Yogi_Bear
Author by

Yogi_Bear

Updated on July 24, 2022

Comments

  • Yogi_Bear
    Yogi_Bear almost 2 years

    I am making an alarm clock. I want to make an activity which on the layout part is empty (exept a photo on the background) I want to do, that if i touch anywhere on the screen, the music will stop.

    I thought about making the img as a imageview... but it dosent strach on the screen when I do it (even if the parameters are on the whole screen)

    help?