Android中的Android滑动侦听器

时间:2017-06-05 12:02:48

标签: android android-fragments ontouchlistener

我正在按照本教程http://www.brightec.co.uk/ideas/android-listview-alphabet-scroller来实现一个字母列表视图,其中包含可以滚动的字母的侧视图,使列表视图直接滚动到该字母。它适用于他们的示例,但我需要将此代码放在一个片段中,并且滚动不再起作用。我不知道如何转换以下内容,因此它可以在一个片段中运行:

private class SideIndexGestureListener extends GestureDetector.SimpleOnGestureListener {
    @Override
    public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
        Log.d("DEBUG", "SideIndexGestureListener.onScroll() distanceX=" + distanceX + " distanceY=" + distanceY);
        // we know already coordinates of first touch
        // we know as well a scroll distance
        sideIndexX = sideIndexX - distanceX;
        sideIndexY = sideIndexY - distanceY;

        // when the user scrolls within our side index
        // we can show for every position in it a proper
        // item in the country list
        if (sideIndexX >= 0 && sideIndexY >= 0) {
            displayListItem();
        }

        return super.onScroll(e1, e2, distanceX, distanceY);
    }
}

@Override
public boolean onTouchEvent(MotionEvent event) {
    if (mGestureDetector.onTouchEvent(event)) {
        return true;
    } else {
        return false;
    }
}

我厌倦了以下事情:

@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.activity_main_fragment_contacts, container, false);

    mGestureDetector = new GestureDetector(context, new SideIndexGestureListener());

    rootView.setOnTouchListener(new View.OnTouchListener() {
        public boolean onTouch(View v, MotionEvent event) {
            if (mGestureDetector.onTouchEvent(event)) {
                return true;
            } else {
                return false;
            }
        }
    });

    return rootView;
}

但它永远不会达到onScroll方法所以我不知道我做错了什么?

1 个答案:

答案 0 :(得分:0)

好吧,我对代码进行了一些调整,并设法通过在我设置为rootwiew的监听器的onTouch方法中返回true来使其工作。