OnKeyListener or OnKeydown not work if children views take the focus

久未见 提交于 2019-12-05 05:34:51

Thanks @Jeffrey. But I found a better way to do it. Just override the dispatchkeyevent method in ScrollView and handle trackball/keyboard events there. It works well.

public class MyScroller extends ScrollView {

public MyScroller(Context context, AttributeSet attrs) {
    super(context, attrs);
}

@Override
public boolean dispatchKeyEvent(KeyEvent event) {
    if ((KeyEvent.KEYCODE_DPAD_UP == event.getKeyCode() || KeyEvent.KEYCODE_DPAD_DOWN == event.getKeyCode())) {
            //handle key events here
    }
    return super.dispatchKeyEvent(event);
}

}

touch events are passed from child to parent. if any child consumes the even (returns true), then it stops; it is not passed to the parent. so, 2 solutions,

first is to extend the view container class and override onInterceptTouchEvent(). here's an example where i did it for TabHost, but for you it might be LinearLayout, or whatever,

public class FlingableTabHost extends TabHost {
    private GestureDetector gestureDetector;

    public FlingableTabHost(Context context, AttributeSet attrs) {
        super(context, attrs);
        initGestureListener();
    }

    public FlingableTabHost(Context context) {
        super(context);
        initGestureListener();
    }

    public boolean onInterceptTouchEvent(MotionEvent event){
        super.onInterceptTouchEvent(event);
        // handle touch event. only return true if you handle it yourself here.
    }
}

second way is to set the recursively set the touch listen for all child view to your custom touch listener,

ViewGroup myLayout = ...;
registerTouchListener(myLayout, myTouchListener);

private void registerTouchListener(View view, View.OnTouchListener listener) {
  view.setOnTouchListener(listener);
  if (view instanceof ViewGroup) {
    ViewGroup vg = (ViewGroup)view;
    for (int i = 0, n = vg.getChildCount(); i < n; i++) {
      View v = vg.getChildAt(i);
      registerTouchListener(v, listener);
    }
  }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!