Android: View.setClickable consumes click event

I have a custom gallery view for horizontal scrolling and several child views that need to be clicked.

The setting childview.setOnClickListener()does not work because it always consumes a touch event.

Therefore, I used childview.setOnTouchListener()and let its onTouch method return false so that the gallery becomes scrollable.

Everything is fine.

The problem is that the onTouch method for childView fires the ACTION_DOWN event . It does not pass MotionEvent ACTION_UP unless I make the View clickable by setting childview.setClickable(). However, setting the Clickable view itself seems to be consuming the onTouch event to make the gallery view insecure.

Looks like I'm going around here. I would be grateful for any help.

Here is my code

Gallery view:

public class myGallery extends Gallery {

    public myGallery(Context ctx, AttributeSet attrSet) {
        super(ctx, attrSet);
        // TODO Auto-generated constructor stub
    }

    private boolean isScrollingLeft(MotionEvent e1, MotionEvent e2){ 
           return e2.getX() > e1.getX(); 
        }

    @Override
    public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY){
      int kEvent;
      if(isScrollingLeft(e1, e2)){ //Check if scrolling left
        kEvent = KeyEvent.KEYCODE_DPAD_LEFT;
      }else{ //Otherwise scrolling right
        kEvent = KeyEvent.KEYCODE_DPAD_RIGHT;
      }
      onKeyDown(kEvent, null);
      return true;  
    }
}

in my activity:

gallery.setOnItemSelectedListener(new OnItemSelectedListener(){
     public void onItemSelected(AdapterView<?> parent, View view,
                    int position, long id) {


         //  childView.setClickable(true);   // can't use this
                                             // click event would get consumed
                                            // and gallery would not scroll 

         // therefore, I can only use the ACTION_DOWN event below:

         childView.setOnTouchListener(new OnTouchListener() {
              public boolean onTouch(View v, MotionEvent event) {

              switch (event.getAction()) {
                  case MotionEvent.ACTION_DOWN:
                       //doStuff();
              }

              return false;
              }
         });
    }

    public void onNothingSelected(AdapterView<?> arg0) {}
     });
}
+5
source share
2 answers

If I were you, I would try to override the method ViewGroup.onInterceptTouchEvent(...)instead of setting OnTouchListener. Thus, you should be able to intercept touch events without actually consuming them.

Check out javadoc .

+2
source

OnTouch should return true to indicate that you want the rest of the events. Here is the frame:

• onTouch() - , , . , , . , false , , . , - , .

android dev

0

All Articles