4

How can I add a event OnTouchListener and OnclickListener at a time in LinearLayout?

Here is my code but doesn't work

final LinearLayout llTimeTable=(LinearLayout) findViewById(R.id.llSehriIftar);
    llTimeTable.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {

            Intent intent = new Intent(MainActivity.this, Ramadandate.class);
            startActivity(intent);

        }
    });
    llTimeTable.setOnTouchListener(new View.OnTouchListener() {

        @Override
        public boolean onTouch(View v, MotionEvent event) {

            switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:

            llTimeTable.setBackgroundColor(Color.rgb(51, 51, 255));
                break;

            case MotionEvent.ACTION_UP:

                // set color back to default
                llTimeTable.setBackgroundColor(Color.rgb(76, 106, 225));

                break;
            }
            return true;
        }
    });

But when I only use OnclickListener it works, and when I use only onTouch method it works, but both at the same time doesn't work.

Steve Lillis
  • 3,263
  • 5
  • 22
  • 41
Mostasim Billah
  • 4,447
  • 3
  • 19
  • 28
  • Your concept is not clear for touch and click please read it first – Anand Savjani Jun 24 '15 at 07:28
  • http://stackoverflow.com/questions/11578718/how-to-combine-onclicklistener-and-ontouchlistener-for-an-imagebutton – Karthik Jun 24 '15 at 07:34
  • You may take a look at this. I think it is helpful to grasp the onTouch vs onClick http://stackoverflow.com/a/9123001/1239911 – Amt87 Jun 24 '15 at 07:35

2 Answers2

9

Since Touch Event is more general, it is called first, then the onClick gets fired, however, since your onTouch returns true, the event is consumed and onClick is never reached.

Simply change onTouch to return false and your onClick will be called.

Lavekush Agrawal
  • 6,040
  • 7
  • 52
  • 85
Antwan Kakki
  • 240
  • 3
  • 11
4
 llTimeTable.setOnTouchListener(new View.OnTouchListener() {

        @Override
        public boolean onTouch(View v, MotionEvent event) {

        //Your code.......
            return false;
        }
    });

Make sure you return false in the TouchListener becuase if you return true then that event will not be passed to other listeners.

Kartheek
  • 7,104
  • 3
  • 30
  • 44