输入事件跟踪器

时间:2015-03-11 10:57:58

标签: android events

在我的项目中,我需要捕获与事件相对应的视图(事件可以是触摸,单击或任何适用的事件)。我认为最好的方法不是注入某种检测机制。我需要知道的是如何在不重构之前创建的所有侦听器的情况下执行此操作,因为我建议不要更改已创建的内容。或者如果不可能,最简单的解决办法是什么?

到目前为止,我能够通过检测触摸事件的坐标从Activity中捕获ViewId,然后在循环中检查布局的子项。

//I put this in Activity
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
    Log.d("DISPATCH",ev.getRawX()+","+ev.getRawY());
    if(layout!=null){
        for(int _numChildren = 0; _numChildren<((ViewGroup)layout).getChildCount();_numChildren++)
        {
            View _child = ((ViewGroup)layout).getChildAt(_numChildren);
            Log.d("CHILD ID",_child.getId()+"");
            Rect _bounds = new Rect();
            _child.getHitRect(_bounds);

            if (isPointInsideView(ev.getRawX(),ev.getRawY(),_child))
                try {
                    Log.d("VIEW CAPTURED",_child.getResources().getResourceName(_child.getId()));
                    tv.setText(_child.getResources().getResourceName(_child.getId()));
                    return super.dispatchTouchEvent(ev);
                }catch (Exception e){

                }
        }
    }
    return super.dispatchTouchEvent(ev);
}

http://pierrchen.blogspot.com/2014/03/pipeline-of-android-touch-event-handling.html

从这个链接,我相信触摸事件将从活动发送到我能够捕获的相应监听器,但是当事件处理流程返回顶部时,它是否可以检测到视图本身(活动) ?

听众位于许多片段,活动和自定义视图中。

谢谢,非常感谢任何帮助。

编辑:如果你有更好的方法/想法请引导我,我愿意接受更好的解决方案

1 个答案:

答案 0 :(得分:0)

您可以使用常规的onTouchListener,其中在onTouch方法中,您可以检查发生的触摸类型.... 例如

@Override
    public boolean onTouch(View view, MotionEvent motionEvent) {
        if (mViewWidth < 2) {
            mViewWidth = mRecyclerView.getWidth();
        }

        switch (motionEvent.getActionMasked()) {
        case MotionEvent.ACTION_DOWN: {
              //Do something here
              break;
        }
        case MotionEvent.ACTION_MOVE: {
              //Do something here
              break;
        }
        case MotionEvent.ACTION_UP: {
              //Do something here
              break;
        }
        }
         ........

希望这有帮助。