Android:View.setClickable消耗点击事件

Chr*_*ser 6 android clickable ontouchlistener

我有一个用于水平滚动的自定义图库视图和几个所有应该可点击的子视图.

设置childview.setOnClickListener()不起作用,因为它总是消耗触摸事件.

因此,我使用childview.setOnTouchListener()并让其onTouch方法返回false,以使Gallery变为可滚动.

这一切都很好.

现在的问题是,childView的onTouch方法只会触发ACTION_DOWN事件.除非我通过设置使View可单击,否则它不会传递MotionEvent ACTION_UPchildview.setClickable().但是,设置View clickable本身似乎会消耗onTouch事件,以便库视图变为不可滚动.

好像我在这里走了一圈.我会感激任何帮助.

这是我的代码

图库视图:

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;  
    }
}
Run Code Online (Sandbox Code Playgroud)

在我的活动中:

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) {}
     });
}
Run Code Online (Sandbox Code Playgroud)

Mic*_*ian 5

如果我是你,我会尝试重写ViewGroup.onInterceptTouchEvent(...)方法而不是设置OnTouchListener。这样您应该能够拦截触摸事件而不实际消耗它们。

查看 javadoc