DropDownListView.java revision 23087be7792c2d22173cf022a72d0648aa430ab5
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    @Override
163    public boolean onTouchEvent(MotionEvent event) {
164        final int x = (int) event.getX();
165        final int y = (int) event.getY();
166        final int position = pointToPosition(x, y);
167        if (position == INVALID_POSITION) {
168            return super.onTouchEvent(event);
169        }
170
171        if (position != mSelectedPosition) {
172            setSelectedPositionInt(position);
173            setNextSelectedPositionInt(position);
174        }
175
176        return super.onTouchEvent(event);
177    }
178
179    /**
180     * Handles forwarded events.
181     *
182     * @param activePointerId id of the pointer that activated forwarding
183     * @return whether the event was handled
184     */
185    public boolean onForwardedEvent(MotionEvent event, int activePointerId) {
186        boolean handledEvent = true;
187        boolean clearPressedItem = false;
188
189        final int actionMasked = event.getActionMasked();
190        switch (actionMasked) {
191            case MotionEvent.ACTION_CANCEL:
192                handledEvent = false;
193                break;
194            case MotionEvent.ACTION_UP:
195                handledEvent = false;
196                // $FALL-THROUGH$
197            case MotionEvent.ACTION_MOVE:
198                final int activeIndex = event.findPointerIndex(activePointerId);
199                if (activeIndex < 0) {
200                    handledEvent = false;
201                    break;
202                }
203
204                final int x = (int) event.getX(activeIndex);
205                final int y = (int) event.getY(activeIndex);
206                final int position = pointToPosition(x, y);
207                if (position == INVALID_POSITION) {
208                    clearPressedItem = true;
209                    break;
210                }
211
212                final View child = getChildAt(position - getFirstVisiblePosition());
213                setPressedItem(child, position, x, y);
214                handledEvent = true;
215
216                if (actionMasked == MotionEvent.ACTION_UP) {
217                    clickPressedItem(child, position);
218                }
219                break;
220        }
221
222        // Failure to handle the event cancels forwarding.
223        if (!handledEvent || clearPressedItem) {
224            clearPressedItem();
225        }
226
227        // Manage automatic scrolling.
228        if (handledEvent) {
229            if (mScrollHelper == null) {
230                mScrollHelper = new AbsListViewAutoScroller(this);
231            }
232            mScrollHelper.setEnabled(true);
233            mScrollHelper.onTouch(this, event);
234        } else if (mScrollHelper != null) {
235            mScrollHelper.setEnabled(false);
236        }
237
238        return handledEvent;
239    }
240
241    /**
242     * Sets whether the list selection is hidden, as part of a workaround for a touch mode issue
243     * (see the declaration for mListSelectionHidden).
244     * @param listSelectionHidden
245     */
246    public void setListSelectionHidden(boolean listSelectionHidden) {
247        this.mListSelectionHidden = listSelectionHidden;
248    }
249
250    /**
251     * Starts an alpha animation on the selector. When the animation ends,
252     * the list performs a click on the item.
253     */
254    private void clickPressedItem(final View child, final int position) {
255        final long id = getItemIdAtPosition(position);
256        final Animator anim = ObjectAnimator.ofInt(
257                mSelector, DRAWABLE_ALPHA, 0xFF, CLICK_ANIM_ALPHA, 0xFF);
258        anim.setDuration(CLICK_ANIM_DURATION);
259        anim.setInterpolator(new AccelerateDecelerateInterpolator());
260        anim.addListener(new AnimatorListenerAdapter() {
261                @Override
262            public void onAnimationEnd(Animator animation) {
263                performItemClick(child, position, id);
264            }
265        });
266        anim.start();
267
268        if (mClickAnimation != null) {
269            mClickAnimation.cancel();
270        }
271        mClickAnimation = anim;
272    }
273
274    private void clearPressedItem() {
275        mDrawsInPressedState = false;
276        setPressed(false);
277        updateSelectorState();
278
279        final View motionView = getChildAt(mMotionPosition - mFirstPosition);
280        if (motionView != null) {
281            motionView.setPressed(false);
282        }
283
284        if (mClickAnimation != null) {
285            mClickAnimation.cancel();
286            mClickAnimation = null;
287        }
288    }
289
290    private void setPressedItem(View child, int position, float x, float y) {
291        mDrawsInPressedState = true;
292
293        // Ordering is essential. First, update the container's pressed state.
294        drawableHotspotChanged(x, y);
295        if (!isPressed()) {
296            setPressed(true);
297        }
298
299        // Next, run layout if we need to stabilize child positions.
300        if (mDataChanged) {
301            layoutChildren();
302        }
303
304        // Manage the pressed view based on motion position. This allows us to
305        // play nicely with actual touch and scroll events.
306        final View motionView = getChildAt(mMotionPosition - mFirstPosition);
307        if (motionView != null && motionView != child && motionView.isPressed()) {
308            motionView.setPressed(false);
309        }
310        mMotionPosition = position;
311
312        // Offset for child coordinates.
313        final float childX = x - child.getLeft();
314        final float childY = y - child.getTop();
315        child.drawableHotspotChanged(childX, childY);
316        if (!child.isPressed()) {
317            child.setPressed(true);
318        }
319
320        // Ensure that keyboard focus starts from the last touched position.
321        setSelectedPositionInt(position);
322        positionSelectorLikeTouch(position, child, x, y);
323
324        // Refresh the drawable state to reflect the new pressed state,
325        // which will also update the selector state.
326        refreshDrawableState();
327
328        if (mClickAnimation != null) {
329            mClickAnimation.cancel();
330            mClickAnimation = null;
331        }
332    }
333
334    @Override
335    boolean touchModeDrawsInPressedState() {
336        return mDrawsInPressedState || super.touchModeDrawsInPressedState();
337    }
338
339    /**
340     * Avoids jarring scrolling effect by ensuring that list elements
341     * made of a text view fit on a single line.
342     *
343     * @param position the item index in the list to get a view for
344     * @return the view for the specified item
345     */
346    @Override
347    View obtainView(int position, boolean[] isScrap) {
348        View view = super.obtainView(position, isScrap);
349
350        if (view instanceof TextView) {
351            ((TextView) view).setHorizontallyScrolling(true);
352        }
353
354        return view;
355    }
356
357    @Override
358    public boolean isInTouchMode() {
359        // WARNING: Please read the comment where mListSelectionHidden is declared
360        return (mHijackFocus && mListSelectionHidden) || super.isInTouchMode();
361    }
362
363    /**
364     * Returns the focus state in the drop down.
365     *
366     * @return true always if hijacking focus
367     */
368    @Override
369    public boolean hasWindowFocus() {
370        return mHijackFocus || super.hasWindowFocus();
371    }
372
373    /**
374     * Returns the focus state in the drop down.
375     *
376     * @return true always if hijacking focus
377     */
378    @Override
379    public boolean isFocused() {
380        return mHijackFocus || super.isFocused();
381    }
382
383    /**
384     * Returns the focus state in the drop down.
385     *
386     * @return true always if hijacking focus
387     */
388    @Override
389    public boolean hasFocus() {
390        return mHijackFocus || super.hasFocus();
391    }
392}