如何在片段中实现onTouchEvent()?

时间:2017-01-30 03:34:54

标签: android android-fragmentactivity fragmentmanager

在Android中,我需要在片段中使用onTouchEvent()。如何在片段而不是活动中使用此事件?

1 个答案:

答案 0 :(得分:1)

class RecyclerTouchListener implements RecyclerView.OnItemTouchListener {

    private GestureDetector gestureDetector;
    private ClickListener clickListener;

    public RecyclerTouchListener(Context context, final RecyclerView recyclerView, final ClickListener clickListener) {
        Log.d("TAG", "Constructer invoked");
        this.clickListener = clickListener;
        gestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
            @Override
            public boolean onSingleTapUp(MotionEvent e) {
                Log.d("TAG", "onSingleTapUp" + e);
                return true;
            }

            @Override
            public void onLongPress(MotionEvent e) {
                View child = recyclerView.findChildViewUnder(e.getX(), e.getY());
                if (child != null && clickListener != null) {
                    clickListener.onLongClick(child, recyclerView.getChildAdapterPosition(child));
                }
                Log.d("TAG", "onLongPress" + e);
            }
        });
    }

    @Override
    public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
        Log.d("TAG", "onInterceptTouchEvent" + gestureDetector.onTouchEvent(e) + " " + e);

        View child = rv.findChildViewUnder(e.getX(), e.getY());
        if (child != null&& gestureDetector.onTouchEvent(e)) {
            clickListener.onClick(child, rv.getChildAdapterPosition(child));
        }
        return false;
    }

    @Override
    public void onTouchEvent(RecyclerView rv, MotionEvent e) {
        Log.d("TAG", "onTouchEvent" + e);
    }

    @Override
    public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {

    }
}

此链接肯定会帮助您 - https://www.youtube.com/watch?v=RS7HIaRalhw