ListViewAutoScrollHelper.java revision 6cf8db91596dd60eee4bb90925e4711cebb202d4
1/*
2 * Copyright (C) 2013 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package android.support.v4.widget;
18
19import android.view.View;
20import android.widget.ListView;
21
22/**
23 * An implementation of {@link AutoScrollHelper} that knows how to scroll
24 * through a {@link ListView}.
25 */
26public class ListViewAutoScrollHelper extends AutoScrollHelper {
27    private final ListView mTarget;
28
29    public ListViewAutoScrollHelper(ListView target) {
30        super(target);
31
32        mTarget = target;
33    }
34
35    @Override
36    public boolean onScrollBy(int deltaX, int deltaY) {
37        final ListView target = mTarget;
38        final int itemCount = target.getCount();
39        final int childCount = target.getChildCount();
40        final int firstPosition = target.getFirstVisiblePosition();
41        final int lastPosition = firstPosition + childCount;
42
43        if (deltaY > 0) {
44            // Are we already showing the entire last item?
45            if (lastPosition >= itemCount) {
46                final View lastView = target.getChildAt(childCount - 1);
47                if (lastView.getBottom() <= target.getHeight()) {
48                    return false;
49                }
50            }
51        } else if (deltaY < 0) {
52            // Are we already showing the entire first item?
53            if (firstPosition <= 0) {
54                final View firstView = target.getChildAt(0);
55                if (firstView.getTop() >= 0) {
56                    return false;
57                }
58            }
59        } else {
60            // We're not scrolling anywhere, and we're good at it.
61            return true;
62        }
63
64        final View firstView = target.getChildAt(0);
65        target.setSelectionFromTop(firstPosition, firstView.getTop() - deltaY);
66        return true;
67    }
68}
69