DropDownListView.java revision 8375d639986529969ea5e118de548d29db16ec97
1/*
2 * Copyright (C) 2015 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.widget;
18
19
20import com.android.internal.widget.AutoScrollHelper.AbsListViewAutoScroller;
21
22import android.animation.Animator;
23import android.animation.AnimatorListenerAdapter;
24import android.animation.ObjectAnimator;
25import android.content.Context;
26import android.graphics.drawable.Drawable;
27import android.util.IntProperty;
28import android.view.MotionEvent;
29import android.view.View;
30import android.view.animation.AccelerateDecelerateInterpolator;
31import android.widget.TextView;
32import android.widget.ListView;
33
34
35/**
36 * Wrapper class for a ListView. This wrapper can hijack the focus to
37 * make sure the list uses the appropriate drawables and states when
38 * displayed on screen within a drop down. The focus is never actually
39 * passed to the drop down in this mode; the list only looks focused.
40 *
41 * @hide
42 */
43public class DropDownListView extends ListView {
44    /** Duration in milliseconds of the drag-to-open click animation. */
45    private static final long CLICK_ANIM_DURATION = 150;
46
47    /** Target alpha value for drag-to-open click animation. */
48    private static final int CLICK_ANIM_ALPHA = 0x80;
49
50    /** Wrapper around Drawable's <code>alpha</code> property. */
51    private static final IntProperty<Drawable> DRAWABLE_ALPHA =
52            new IntProperty<Drawable>("alpha") {
53                @Override
54                public void setValue(Drawable object, int value) {
55                    object.setAlpha(value);
56                }
57
58                @Override
59                public Integer get(Drawable object) {
60                    return object.getAlpha();
61                }
62            };
63
64    /*
65     * WARNING: This is a workaround for a touch mode issue.
66     *
67     * Touch mode is propagated lazily to windows. This causes problems in
68     * the following scenario:
69     * - Type something in the AutoCompleteTextView and get some results
70     * - Move down with the d-pad to select an item in the list
71     * - Move up with the d-pad until the selection disappears
72     * - Type more text in the AutoCompleteTextView *using the soft keyboard*
73     *   and get new results; you are now in touch mode
74     * - The selection comes back on the first item in the list, even though
75     *   the list is supposed to be in touch mode
76     *
77     * Using the soft keyboard triggers the touch mode change but that change
78     * is propagated to our window only after the first list layout, therefore
79     * after the list attempts to resurrect the selection.
80     *
81     * The trick to work around this issue is to pretend the list is in touch
82     * mode when we know that the selection should not appear, that is when
83     * we know the user moved the selection away from the list.
84     *
85     * This boolean is set to true whenever we explicitly hide the list's
86     * selection and reset to false whenever we know the user moved the
87     * selection back to the list.
88     *
89     * When this boolean is true, isInTouchMode() returns true, otherwise it
90     * returns super.isInTouchMode().
91     */
92    private boolean mListSelectionHidden;
93
94    /**
95     * True if this wrapper should fake focus.
96     */
97    private boolean mHijackFocus;
98
99    /** Whether to force drawing of the pressed state selector. */
100    private boolean mDrawsInPressedState;
101
102    /** Current drag-to-open click animation, if any. */
103    private Animator mClickAnimation;
104
105    /** Helper for drag-to-open auto scrolling. */
106    private AbsListViewAutoScroller mScrollHelper;
107
108    /**
109     * Creates a new list view wrapper.
110     *
111     * @param context this view's context
112     */
113    public DropDownListView(Context context, boolean hijackFocus) {
114        this(context, hijackFocus, com.android.internal.R.attr.dropDownListViewStyle);
115    }
116
117    /**
118     * Creates a new list view wrapper.
119     *
120     * @param context this view's context
121     */
122    public DropDownListView(Context context, boolean hijackFocus, int defStyleAttr) {
123        super(context, null, defStyleAttr);
124        mHijackFocus = hijackFocus;
125        // TODO: Add an API to control this
126        setCacheColorHint(0); // Transparent, since the background drawable could be anything.
127    }
128
129    @Override
130    protected boolean shouldShowSelector() {
131        View selectedView = getSelectedView();
132        return selectedView != null && selectedView.isEnabled() || super.shouldShowSelector();
133    }
134
135    @Override
136    public boolean onHoverEvent(MotionEvent ev) {
137        final int action = ev.getActionMasked();
138        if (action == MotionEvent.ACTION_HOVER_ENTER
139                || action == MotionEvent.ACTION_HOVER_MOVE) {
140            final int position = pointToPosition((int) ev.getX(), (int) ev.getY());
141            if (position != INVALID_POSITION && position != mSelectedPosition) {
142                final View hoveredItem = getChildAt(position - getFirstVisiblePosition());
143                if (hoveredItem.isEnabled()) {
144                    // Force a focus so that the proper selector state gets used when we update.
145                    requestFocus();
146
147                    positionSelector(position, hoveredItem);
148                    setSelectedPositionInt(position);
149                    setNextSelectedPositionInt(position);
150                }
151                updateSelectorState();
152            }
153        } else {
154            // Do not cancel the selected position if the selection is visible by other reasons.
155            if (!super.shouldShowSelector()) {
156                setSelectedPositionInt(INVALID_POSITION);
157            }
158        }
159        return super.onHoverEvent(ev);
160    }
161
162    /**
163     * Handles forwarded events.
164     *
165     * @param activePointerId id of the pointer that activated forwarding
166     * @return whether the event was handled
167     */
168    public boolean onForwardedEvent(MotionEvent event, int activePointerId) {
169        boolean handledEvent = true;
170        boolean clearPressedItem = false;
171
172        final int actionMasked = event.getActionMasked();
173        switch (actionMasked) {
174            case MotionEvent.ACTION_CANCEL:
175                handledEvent = false;
176                break;
177            case MotionEvent.ACTION_UP:
178                handledEvent = false;
179                // $FALL-THROUGH$
180            case MotionEvent.ACTION_MOVE:
181                final int activeIndex = event.findPointerIndex(activePointerId);
182                if (activeIndex < 0) {
183                    handledEvent = false;
184                    break;
185                }
186
187                final int x = (int) event.getX(activeIndex);
188                final int y = (int) event.getY(activeIndex);
189                final int position = pointToPosition(x, y);
190                if (position == INVALID_POSITION) {
191                    clearPressedItem = true;
192                    break;
193                }
194
195                final View child = getChildAt(position - getFirstVisiblePosition());
196                setPressedItem(child, position, x, y);
197                handledEvent = true;
198
199                if (actionMasked == MotionEvent.ACTION_UP) {
200                    clickPressedItem(child, position);
201                }
202                break;
203        }
204
205        // Failure to handle the event cancels forwarding.
206        if (!handledEvent || clearPressedItem) {
207            clearPressedItem();
208        }
209
210        // Manage automatic scrolling.
211        if (handledEvent) {
212            if (mScrollHelper == null) {
213                mScrollHelper = new AbsListViewAutoScroller(this);
214            }
215            mScrollHelper.setEnabled(true);
216            mScrollHelper.onTouch(this, event);
217        } else if (mScrollHelper != null) {
218            mScrollHelper.setEnabled(false);
219        }
220
221        return handledEvent;
222    }
223
224    /**
225     * Sets whether the list selection is hidden, as part of a workaround for a touch mode issue
226     * (see the declaration for mListSelectionHidden).
227     * @param listSelectionHidden
228     */
229    public void setListSelectionHidden(boolean listSelectionHidden) {
230        this.mListSelectionHidden = listSelectionHidden;
231    }
232
233    /**
234     * Starts an alpha animation on the selector. When the animation ends,
235     * the list performs a click on the item.
236     */
237    private void clickPressedItem(final View child, final int position) {
238        final long id = getItemIdAtPosition(position);
239        final Animator anim = ObjectAnimator.ofInt(
240                mSelector, DRAWABLE_ALPHA, 0xFF, CLICK_ANIM_ALPHA, 0xFF);
241        anim.setDuration(CLICK_ANIM_DURATION);
242        anim.setInterpolator(new AccelerateDecelerateInterpolator());
243        anim.addListener(new AnimatorListenerAdapter() {
244                @Override
245            public void onAnimationEnd(Animator animation) {
246                performItemClick(child, position, id);
247            }
248        });
249        anim.start();
250
251        if (mClickAnimation != null) {
252            mClickAnimation.cancel();
253        }
254        mClickAnimation = anim;
255    }
256
257    private void clearPressedItem() {
258        mDrawsInPressedState = false;
259        setPressed(false);
260        updateSelectorState();
261
262        final View motionView = getChildAt(mMotionPosition - mFirstPosition);
263        if (motionView != null) {
264            motionView.setPressed(false);
265        }
266
267        if (mClickAnimation != null) {
268            mClickAnimation.cancel();
269            mClickAnimation = null;
270        }
271    }
272
273    private void setPressedItem(View child, int position, float x, float y) {
274        mDrawsInPressedState = true;
275
276        // Ordering is essential. First, update the container's pressed state.
277        drawableHotspotChanged(x, y);
278        if (!isPressed()) {
279            setPressed(true);
280        }
281
282        // Next, run layout if we need to stabilize child positions.
283        if (mDataChanged) {
284            layoutChildren();
285        }
286
287        // Manage the pressed view based on motion position. This allows us to
288        // play nicely with actual touch and scroll events.
289        final View motionView = getChildAt(mMotionPosition - mFirstPosition);
290        if (motionView != null && motionView != child && motionView.isPressed()) {
291            motionView.setPressed(false);
292        }
293        mMotionPosition = position;
294
295        // Offset for child coordinates.
296        final float childX = x - child.getLeft();
297        final float childY = y - child.getTop();
298        child.drawableHotspotChanged(childX, childY);
299        if (!child.isPressed()) {
300            child.setPressed(true);
301        }
302
303        // Ensure that keyboard focus starts from the last touched position.
304        setSelectedPositionInt(position);
305        positionSelectorLikeTouch(position, child, x, y);
306
307        // Refresh the drawable state to reflect the new pressed state,
308        // which will also update the selector state.
309        refreshDrawableState();
310
311        if (mClickAnimation != null) {
312            mClickAnimation.cancel();
313            mClickAnimation = null;
314        }
315    }
316
317    @Override
318    boolean touchModeDrawsInPressedState() {
319        return mDrawsInPressedState || super.touchModeDrawsInPressedState();
320    }
321
322    /**
323     * Avoids jarring scrolling effect by ensuring that list elements
324     * made of a text view fit on a single line.
325     *
326     * @param position the item index in the list to get a view for
327     * @return the view for the specified item
328     */
329    @Override
330    View obtainView(int position, boolean[] isScrap) {
331        View view = super.obtainView(position, isScrap);
332
333        if (view instanceof TextView) {
334            ((TextView) view).setHorizontallyScrolling(true);
335        }
336
337        return view;
338    }
339
340    @Override
341    public boolean isInTouchMode() {
342        // WARNING: Please read the comment where mListSelectionHidden is declared
343        return (mHijackFocus && mListSelectionHidden) || super.isInTouchMode();
344    }
345
346    /**
347     * Returns the focus state in the drop down.
348     *
349     * @return true always if hijacking focus
350     */
351    @Override
352    public boolean hasWindowFocus() {
353        return mHijackFocus || super.hasWindowFocus();
354    }
355
356    /**
357     * Returns the focus state in the drop down.
358     *
359     * @return true always if hijacking focus
360     */
361    @Override
362    public boolean isFocused() {
363        return mHijackFocus || super.isFocused();
364    }
365
366    /**
367     * Returns the focus state in the drop down.
368     *
369     * @return true always if hijacking focus
370     */
371    @Override
372    public boolean hasFocus() {
373        return mHijackFocus || super.hasFocus();
374    }
375}