blob: 3956215b6f83a38b6123ca40ffd86fcfabccdf69 [file] [log] [blame]
/*
* Copyright (C) 2006 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package android.widget;
import android.annotation.ColorInt;
import android.annotation.DrawableRes;
import android.annotation.NonNull;
import android.annotation.TestApi;
import android.annotation.UnsupportedAppUsage;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.TransitionDrawable;
import android.os.Bundle;
import android.os.Debug;
import android.os.Handler;
import android.os.Parcel;
import android.os.Parcelable;
import android.os.StrictMode;
import android.os.Trace;
import android.text.Editable;
import android.text.InputType;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.util.Log;
import android.util.LongSparseArray;
import android.util.SparseArray;
import android.util.SparseBooleanArray;
import android.util.StateSet;
import android.view.ActionMode;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Gravity;
import android.view.HapticFeedbackConstants;
import android.view.InputDevice;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.PointerIcon;
import android.view.VelocityTracker;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewDebug;
import android.view.ViewGroup;
import android.view.ViewHierarchyEncoder;
import android.view.ViewParent;
import android.view.ViewTreeObserver;
import android.view.accessibility.AccessibilityEvent;
import android.view.accessibility.AccessibilityManager;
import android.view.accessibility.AccessibilityNodeInfo;
import android.view.accessibility.AccessibilityNodeInfo.AccessibilityAction;
import android.view.accessibility.AccessibilityNodeInfo.CollectionInfo;
import android.view.animation.Interpolator;
import android.view.animation.LinearInterpolator;
import android.view.inputmethod.BaseInputConnection;
import android.view.inputmethod.CompletionInfo;
import android.view.inputmethod.CorrectionInfo;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.ExtractedText;
import android.view.inputmethod.ExtractedTextRequest;
import android.view.inputmethod.InputConnection;
import android.view.inputmethod.InputContentInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.RemoteViews.OnClickHandler;
import com.android.internal.R;
import java.util.ArrayList;
import java.util.List;
/**
* Base class that can be used to implement virtualized lists of items. A list does
* not have a spatial definition here. For instance, subclasses of this class can
* display the content of the list in a grid, in a carousel, as stack, etc.
*
* @attr ref android.R.styleable#AbsListView_listSelector
* @attr ref android.R.styleable#AbsListView_drawSelectorOnTop
* @attr ref android.R.styleable#AbsListView_stackFromBottom
* @attr ref android.R.styleable#AbsListView_scrollingCache
* @attr ref android.R.styleable#AbsListView_textFilterEnabled
* @attr ref android.R.styleable#AbsListView_transcriptMode
* @attr ref android.R.styleable#AbsListView_cacheColorHint
* @attr ref android.R.styleable#AbsListView_fastScrollEnabled
* @attr ref android.R.styleable#AbsListView_smoothScrollbar
* @attr ref android.R.styleable#AbsListView_choiceMode
*/
public abstract class AbsListView extends AdapterView<ListAdapter> implements TextWatcher,
ViewTreeObserver.OnGlobalLayoutListener, Filter.FilterListener,
ViewTreeObserver.OnTouchModeChangeListener,
RemoteViewsAdapter.RemoteAdapterConnectionCallback {
@SuppressWarnings("UnusedDeclaration")
private static final String TAG = "AbsListView";
/**
* Disables the transcript mode.
*
* @see #setTranscriptMode(int)
*/
public static final int TRANSCRIPT_MODE_DISABLED = 0;
/**
* The list will automatically scroll to the bottom when a data set change
* notification is received and only if the last item is already visible
* on screen.
*
* @see #setTranscriptMode(int)
*/
public static final int TRANSCRIPT_MODE_NORMAL = 1;
/**
* The list will automatically scroll to the bottom, no matter what items
* are currently visible.
*
* @see #setTranscriptMode(int)
*/
public static final int TRANSCRIPT_MODE_ALWAYS_SCROLL = 2;
/**
* Indicates that we are not in the middle of a touch gesture
*/
static final int TOUCH_MODE_REST = -1;
/**
* Indicates we just received the touch event and we are waiting to see if the it is a tap or a
* scroll gesture.
*/
static final int TOUCH_MODE_DOWN = 0;
/**
* Indicates the touch has been recognized as a tap and we are now waiting to see if the touch
* is a longpress
*/
static final int TOUCH_MODE_TAP = 1;
/**
* Indicates we have waited for everything we can wait for, but the user's finger is still down
*/
static final int TOUCH_MODE_DONE_WAITING = 2;
/**
* Indicates the touch gesture is a scroll
*/
static final int TOUCH_MODE_SCROLL = 3;
/**
* Indicates the view is in the process of being flung
*/
static final int TOUCH_MODE_FLING = 4;
/**
* Indicates the touch gesture is an overscroll - a scroll beyond the beginning or end.
*/
static final int TOUCH_MODE_OVERSCROLL = 5;
/**
* Indicates the view is being flung outside of normal content bounds
* and will spring back.
*/
static final int TOUCH_MODE_OVERFLING = 6;
/**
* Regular layout - usually an unsolicited layout from the view system
*/
static final int LAYOUT_NORMAL = 0;
/**
* Show the first item
*/
static final int LAYOUT_FORCE_TOP = 1;
/**
* Force the selected item to be on somewhere on the screen
*/
static final int LAYOUT_SET_SELECTION = 2;
/**
* Show the last item
*/
static final int LAYOUT_FORCE_BOTTOM = 3;
/**
* Make a mSelectedItem appear in a specific location and build the rest of
* the views from there. The top is specified by mSpecificTop.
*/
static final int LAYOUT_SPECIFIC = 4;
/**
* Layout to sync as a result of a data change. Restore mSyncPosition to have its top
* at mSpecificTop
*/
static final int LAYOUT_SYNC = 5;
/**
* Layout as a result of using the navigation keys
*/
static final int LAYOUT_MOVE_SELECTION = 6;
/**
* Normal list that does not indicate choices
*/
public static final int CHOICE_MODE_NONE = 0;
/**
* The list allows up to one choice
*/
public static final int CHOICE_MODE_SINGLE = 1;
/**
* The list allows multiple choices
*/
public static final int CHOICE_MODE_MULTIPLE = 2;
/**
* The list allows multiple choices in a modal selection mode
*/
public static final int CHOICE_MODE_MULTIPLE_MODAL = 3;
/**
* The thread that created this view.
*/
private final Thread mOwnerThread;
/**
* Controls if/how the user may choose/check items in the list
*/
int mChoiceMode = CHOICE_MODE_NONE;
/**
* Controls CHOICE_MODE_MULTIPLE_MODAL. null when inactive.
*/
@UnsupportedAppUsage
ActionMode mChoiceActionMode;
/**
* Wrapper for the multiple choice mode callback; AbsListView needs to perform
* a few extra actions around what application code does.
*/
MultiChoiceModeWrapper mMultiChoiceModeCallback;
/**
* Running count of how many items are currently checked
*/
int mCheckedItemCount;
/**
* Running state of which positions are currently checked
*/
SparseBooleanArray mCheckStates;
/**
* Running state of which IDs are currently checked.
* If there is a value for a given key, the checked state for that ID is true
* and the value holds the last known position in the adapter for that id.
*/
LongSparseArray<Integer> mCheckedIdStates;
/**
* Controls how the next layout will happen
*/
@UnsupportedAppUsage
int mLayoutMode = LAYOUT_NORMAL;
/**
* Should be used by subclasses to listen to changes in the dataset
*/
@UnsupportedAppUsage
AdapterDataSetObserver mDataSetObserver;
/**
* The adapter containing the data to be displayed by this view
*/
@UnsupportedAppUsage
ListAdapter mAdapter;
/**
* The remote adapter containing the data to be displayed by this view to be set
*/
private RemoteViewsAdapter mRemoteAdapter;
/**
* If mAdapter != null, whenever this is true the adapter has stable IDs.
*/
boolean mAdapterHasStableIds;
/**
* This flag indicates the a full notify is required when the RemoteViewsAdapter connects
*/
private boolean mDeferNotifyDataSetChanged = false;
/**
* Indicates whether the list selector should be drawn on top of the children or behind
*/
boolean mDrawSelectorOnTop = false;
/**
* The drawable used to draw the selector
*/
@UnsupportedAppUsage
Drawable mSelector;
/**
* The current position of the selector in the list.
*/
@UnsupportedAppUsage
int mSelectorPosition = INVALID_POSITION;
/**
* Defines the selector's location and dimension at drawing time
*/
@UnsupportedAppUsage
Rect mSelectorRect = new Rect();
/**
* The data set used to store unused views that should be reused during the next layout
* to avoid creating new ones
*/
@UnsupportedAppUsage
final RecycleBin mRecycler = new RecycleBin();
/**
* The selection's left padding
*/
int mSelectionLeftPadding = 0;
/**
* The selection's top padding
*/
@UnsupportedAppUsage
int mSelectionTopPadding = 0;
/**
* The selection's right padding
*/
int mSelectionRightPadding = 0;
/**
* The selection's bottom padding
*/
@UnsupportedAppUsage
int mSelectionBottomPadding = 0;
/**
* This view's padding
*/
Rect mListPadding = new Rect();
/**
* Subclasses must retain their measure spec from onMeasure() into this member
*/
int mWidthMeasureSpec = 0;
/**
* The top scroll indicator
*/
View mScrollUp;
/**
* The down scroll indicator
*/
View mScrollDown;
/**
* When the view is scrolling, this flag is set to true to indicate subclasses that
* the drawing cache was enabled on the children
*/
boolean mCachingStarted;
boolean mCachingActive;
/**
* The position of the view that received the down motion event
*/
@UnsupportedAppUsage
int mMotionPosition;
/**
* The offset to the top of the mMotionPosition view when the down motion event was received
*/
int mMotionViewOriginalTop;
/**
* The desired offset to the top of the mMotionPosition view after a scroll
*/
int mMotionViewNewTop;
/**
* The X value associated with the the down motion event
*/
int mMotionX;
/**
* The Y value associated with the the down motion event
*/
@UnsupportedAppUsage
int mMotionY;
/**
* One of TOUCH_MODE_REST, TOUCH_MODE_DOWN, TOUCH_MODE_TAP, TOUCH_MODE_SCROLL, or
* TOUCH_MODE_DONE_WAITING
*/
@UnsupportedAppUsage
int mTouchMode = TOUCH_MODE_REST;
/**
* Y value from on the previous motion event (if any)
*/
int mLastY;
/**
* How far the finger moved before we started scrolling
*/
int mMotionCorrection;
/**
* Determines speed during touch scrolling
*/
@UnsupportedAppUsage
private VelocityTracker mVelocityTracker;
/**
* Handles one frame of a fling
*/
@UnsupportedAppUsage
private FlingRunnable mFlingRunnable;
/**
* Handles scrolling between positions within the list.
*/
@UnsupportedAppUsage
AbsPositionScroller mPositionScroller;
/**
* The offset in pixels form the top of the AdapterView to the top
* of the currently selected view. Used to save and restore state.
*/
int mSelectedTop = 0;
/**
* Indicates whether the list is stacked from the bottom edge or
* the top edge.
*/
boolean mStackFromBottom;
/**
* When set to true, the list automatically discards the children's
* bitmap cache after scrolling.
*/
boolean mScrollingCacheEnabled;
/**
* Whether or not to enable the fast scroll feature on this list
*/
boolean mFastScrollEnabled;
/**
* Whether or not to always show the fast scroll feature on this list
*/
boolean mFastScrollAlwaysVisible;
/**
* Optional callback to notify client when scroll position has changed
*/
@UnsupportedAppUsage
private OnScrollListener mOnScrollListener;
/**
* Keeps track of our accessory window
*/
@UnsupportedAppUsage
PopupWindow mPopup;
/**
* Used with type filter window
*/
EditText mTextFilter;
/**
* Indicates whether to use pixels-based or position-based scrollbar
* properties.
*/
private boolean mSmoothScrollbarEnabled = true;
/**
* Indicates that this view supports filtering
*/
private boolean mTextFilterEnabled;
/**
* Indicates that this view is currently displaying a filtered view of the data
*/
private boolean mFiltered;
/**
* Rectangle used for hit testing children
*/
private Rect mTouchFrame;
/**
* The position to resurrect the selected position to.
*/
int mResurrectToPosition = INVALID_POSITION;
@UnsupportedAppUsage
private ContextMenuInfo mContextMenuInfo = null;
/**
* Maximum distance to record overscroll
*/
int mOverscrollMax;
/**
* Content height divided by this is the overscroll limit.
*/
static final int OVERSCROLL_LIMIT_DIVISOR = 3;
/**
* How many positions in either direction we will search to try to
* find a checked item with a stable ID that moved position across
* a data set change. If the item isn't found it will be unselected.
*/
private static final int CHECK_POSITION_SEARCH_DISTANCE = 20;
/**
* Used to request a layout when we changed touch mode
*/
private static final int TOUCH_MODE_UNKNOWN = -1;
private static final int TOUCH_MODE_ON = 0;
private static final int TOUCH_MODE_OFF = 1;
private int mLastTouchMode = TOUCH_MODE_UNKNOWN;
private static final boolean PROFILE_SCROLLING = false;
private boolean mScrollProfilingStarted = false;
private static final boolean PROFILE_FLINGING = false;
private boolean mFlingProfilingStarted = false;
/**
* The StrictMode "critical time span" objects to catch animation
* stutters. Non-null when a time-sensitive animation is
* in-flight. Must call finish() on them when done animating.
* These are no-ops on user builds.
*/
private StrictMode.Span mScrollStrictSpan = null;
private StrictMode.Span mFlingStrictSpan = null;
/**
* The last CheckForLongPress runnable we posted, if any
*/
@UnsupportedAppUsage
private CheckForLongPress mPendingCheckForLongPress;
/**
* The last CheckForTap runnable we posted, if any
*/
@UnsupportedAppUsage
private CheckForTap mPendingCheckForTap;
/**
* The last CheckForKeyLongPress runnable we posted, if any
*/
private CheckForKeyLongPress mPendingCheckForKeyLongPress;
/**
* Acts upon click
*/
private AbsListView.PerformClick mPerformClick;
/**
* Delayed action for touch mode.
*/
private Runnable mTouchModeReset;
/**
* Whether the most recent touch event stream resulted in a successful
* long-press action. This is reset on TOUCH_DOWN.
*/
private boolean mHasPerformedLongPress;
/**
* This view is in transcript mode -- it shows the bottom of the list when the data
* changes
*/
private int mTranscriptMode;
/**
* Indicates that this list is always drawn on top of a solid, single-color, opaque
* background
*/
private int mCacheColorHint;
/**
* The select child's view (from the adapter's getView) is enabled.
*/
@UnsupportedAppUsage
private boolean mIsChildViewEnabled;
/**
* The cached drawable state for the selector. Accounts for child enabled
* state, but otherwise identical to the view's own drawable state.
*/
private int[] mSelectorState;
/**
* The last scroll state reported to clients through {@link OnScrollListener}.
*/
private int mLastScrollState = OnScrollListener.SCROLL_STATE_IDLE;
/**
* Helper object that renders and controls the fast scroll thumb.
*/
@UnsupportedAppUsage
private FastScroller mFastScroll;
/**
* Temporary holder for fast scroller style until a FastScroller object
* is created.
*/
private int mFastScrollStyle;
private boolean mGlobalLayoutListenerAddedFilter;
@UnsupportedAppUsage
private int mTouchSlop;
private float mDensityScale;
private float mVerticalScrollFactor;
private InputConnection mDefInputConnection;
private InputConnectionWrapper mPublicInputConnection;
private Runnable mClearScrollingCache;
Runnable mPositionScrollAfterLayout;
private int mMinimumVelocity;
@UnsupportedAppUsage
private int mMaximumVelocity;
private float mVelocityScale = 1.0f;
final boolean[] mIsScrap = new boolean[1];
private final int[] mScrollOffset = new int[2];
private final int[] mScrollConsumed = new int[2];
private final float[] mTmpPoint = new float[2];
// Used for offsetting MotionEvents that we feed to the VelocityTracker.
// In the future it would be nice to be able to give this to the VelocityTracker
// directly, or alternatively put a VT into absolute-positioning mode that only
// reads the raw screen-coordinate x/y values.
private int mNestedYOffset = 0;
// True when the popup should be hidden because of a call to
// dispatchDisplayHint()
private boolean mPopupHidden;
/**
* ID of the active pointer. This is used to retain consistency during
* drags/flings if multiple pointers are used.
*/
@UnsupportedAppUsage
private int mActivePointerId = INVALID_POINTER;
/**
* Sentinel value for no current active pointer.
* Used by {@link #mActivePointerId}.
*/
private static final int INVALID_POINTER = -1;
/**
* Maximum distance to overscroll by during edge effects
*/
@UnsupportedAppUsage
int mOverscrollDistance;
/**
* Maximum distance to overfling during edge effects
*/
@UnsupportedAppUsage
int mOverflingDistance;
// These two EdgeGlows are always set and used together.
// Checking one for null is as good as checking both.
/**
* Tracks the state of the top edge glow.
*/
@UnsupportedAppUsage
private EdgeEffect mEdgeGlowTop;
/**
* Tracks the state of the bottom edge glow.
*/
@UnsupportedAppUsage
private EdgeEffect mEdgeGlowBottom;
/**
* An estimate of how many pixels are between the top of the list and
* the top of the first position in the adapter, based on the last time
* we saw it. Used to hint where to draw edge glows.
*/
private int mFirstPositionDistanceGuess;
/**
* An estimate of how many pixels are between the bottom of the list and
* the bottom of the last position in the adapter, based on the last time
* we saw it. Used to hint where to draw edge glows.
*/
private int mLastPositionDistanceGuess;
/**
* Used for determining when to cancel out of overscroll.
*/
private int mDirection = 0;
/**
* Tracked on measurement in transcript mode. Makes sure that we can still pin to
* the bottom correctly on resizes.
*/
private boolean mForceTranscriptScroll;
/**
* Used for interacting with list items from an accessibility service.
*/
private ListItemAccessibilityDelegate mAccessibilityDelegate;
private int mLastAccessibilityScrollEventFromIndex;
private int mLastAccessibilityScrollEventToIndex;
/**
* Track the item count from the last time we handled a data change.
*/
private int mLastHandledItemCount;
/**
* Used for smooth scrolling at a consistent rate
*/
static final Interpolator sLinearInterpolator = new LinearInterpolator();
/**
* The saved state that we will be restoring from when we next sync.
* Kept here so that if we happen to be asked to save our state before
* the sync happens, we can return this existing data rather than losing
* it.
*/
private SavedState mPendingSync;
/**
* Whether the view is in the process of detaching from its window.
*/
private boolean mIsDetaching;
/**
* Interface definition for a callback to be invoked when the list or grid
* has been scrolled.
*/
public interface OnScrollListener {
/**
* The view is not scrolling. Note navigating the list using the trackball counts as
* being in the idle state since these transitions are not animated.
*/
public static int SCROLL_STATE_IDLE = 0;
/**
* The user is scrolling using touch, and their finger is still on the screen
*/
public static int SCROLL_STATE_TOUCH_SCROLL = 1;
/**
* The user had previously been scrolling using touch and had performed a fling. The
* animation is now coasting to a stop
*/
public static int SCROLL_STATE_FLING = 2;
/**
* Callback method to be invoked while the list view or grid view is being scrolled. If the
* view is being scrolled, this method will be called before the next frame of the scroll is
* rendered. In particular, it will be called before any calls to
* {@link Adapter#getView(int, View, ViewGroup)}.
*
* @param view The view whose scroll state is being reported
*
* @param scrollState The current scroll state. One of
* {@link #SCROLL_STATE_TOUCH_SCROLL} or {@link #SCROLL_STATE_IDLE}.
*/
public void onScrollStateChanged(AbsListView view, int scrollState);
/**
* Callback method to be invoked when the list or grid has been scrolled. This will be
* called after the scroll has completed
* @param view The view whose scroll state is being reported
* @param firstVisibleItem the index of the first visible cell (ignore if
* visibleItemCount == 0)
* @param visibleItemCount the number of visible cells
* @param totalItemCount the number of items in the list adaptor
*/
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount,
int totalItemCount);
}
/**
* The top-level view of a list item can implement this interface to allow
* itself to modify the bounds of the selection shown for that item.
*/
public interface SelectionBoundsAdjuster {
/**
* Called to allow the list item to adjust the bounds shown for
* its selection.
*
* @param bounds On call, this contains the bounds the list has
* selected for the item (that is the bounds of the entire view). The
* values can be modified as desired.
*/
public void adjustListItemSelectionBounds(Rect bounds);
}
public AbsListView(Context context) {
super(context);
initAbsListView();
mOwnerThread = Thread.currentThread();
setVerticalScrollBarEnabled(true);
TypedArray a = context.obtainStyledAttributes(R.styleable.View);
initializeScrollbarsInternal(a);
a.recycle();
}
public AbsListView(Context context, AttributeSet attrs) {
this(context, attrs, com.android.internal.R.attr.absListViewStyle);
}
public AbsListView(Context context, AttributeSet attrs, int defStyleAttr) {
this(context, attrs, defStyleAttr, 0);
}
public AbsListView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
initAbsListView();
mOwnerThread = Thread.currentThread();
final TypedArray a = context.obtainStyledAttributes(
attrs, R.styleable.AbsListView, defStyleAttr, defStyleRes);
final Drawable selector = a.getDrawable(R.styleable.AbsListView_listSelector);
if (selector != null) {
setSelector(selector);
}
mDrawSelectorOnTop = a.getBoolean(R.styleable.AbsListView_drawSelectorOnTop, false);
setStackFromBottom(a.getBoolean(
R.styleable.AbsListView_stackFromBottom, false));
setScrollingCacheEnabled(a.getBoolean(
R.styleable.AbsListView_scrollingCache, true));
setTextFilterEnabled(a.getBoolean(
R.styleable.AbsListView_textFilterEnabled, false));
setTranscriptMode(a.getInt(
R.styleable.AbsListView_transcriptMode, TRANSCRIPT_MODE_DISABLED));
setCacheColorHint(a.getColor(
R.styleable.AbsListView_cacheColorHint, 0));
setSmoothScrollbarEnabled(a.getBoolean(
R.styleable.AbsListView_smoothScrollbar, true));
setChoiceMode(a.getInt(
R.styleable.AbsListView_choiceMode, CHOICE_MODE_NONE));
setFastScrollEnabled(a.getBoolean(
R.styleable.AbsListView_fastScrollEnabled, false));
setFastScrollStyle(a.getResourceId(
R.styleable.AbsListView_fastScrollStyle, 0));
setFastScrollAlwaysVisible(a.getBoolean(
R.styleable.AbsListView_fastScrollAlwaysVisible, false));
a.recycle();
if (context.getResources().getConfiguration().uiMode == Configuration.UI_MODE_TYPE_WATCH) {
setRevealOnFocusHint(false);
}
}
private void initAbsListView() {
// Setting focusable in touch mode will set the focusable property to true
setClickable(true);
setFocusableInTouchMode(true);
setWillNotDraw(false);
setAlwaysDrawnWithCacheEnabled(false);
setScrollingCacheEnabled(true);
final ViewConfiguration configuration = ViewConfiguration.get(mContext);
mTouchSlop = configuration.getScaledTouchSlop();
mVerticalScrollFactor = configuration.getScaledVerticalScrollFactor();
mMinimumVelocity = configuration.getScaledMinimumFlingVelocity();
mMaximumVelocity = configuration.getScaledMaximumFlingVelocity();
mOverscrollDistance = configuration.getScaledOverscrollDistance();
mOverflingDistance = configuration.getScaledOverflingDistance();
mDensityScale = getContext().getResources().getDisplayMetrics().density;
}
@Override
public void setOverScrollMode(int mode) {
if (mode != OVER_SCROLL_NEVER) {
if (mEdgeGlowTop == null) {
Context context = getContext();
mEdgeGlowTop = new EdgeEffect(context);
mEdgeGlowBottom = new EdgeEffect(context);
}
} else {
mEdgeGlowTop = null;
mEdgeGlowBottom = null;
}
super.setOverScrollMode(mode);
}
/**
* {@inheritDoc}
*/
@Override
public void setAdapter(ListAdapter adapter) {
if (adapter != null) {
mAdapterHasStableIds = mAdapter.hasStableIds();
if (mChoiceMode != CHOICE_MODE_NONE && mAdapterHasStableIds &&
mCheckedIdStates == null) {
mCheckedIdStates = new LongSparseArray<Integer>();
}
}
clearChoices();
}
/**
* Returns the number of items currently selected. This will only be valid
* if the choice mode is not {@link #CHOICE_MODE_NONE} (default).
*
* <p>To determine the specific items that are currently selected, use one of
* the <code>getChecked*</code> methods.
*
* @return The number of items currently selected
*
* @see #getCheckedItemPosition()
* @see #getCheckedItemPositions()
* @see #getCheckedItemIds()
*/
public int getCheckedItemCount() {
return mCheckedItemCount;
}
/**
* Returns the checked state of the specified position. The result is only
* valid if the choice mode has been set to {@link #CHOICE_MODE_SINGLE}
* or {@link #CHOICE_MODE_MULTIPLE}.
*
* @param position The item whose checked state to return
* @return The item's checked state or <code>false</code> if choice mode
* is invalid
*
* @see #setChoiceMode(int)
*/
public boolean isItemChecked(int position) {
if (mChoiceMode != CHOICE_MODE_NONE && mCheckStates != null) {
return mCheckStates.get(position);
}
return false;
}
/**
* Returns the currently checked item. The result is only valid if the choice
* mode has been set to {@link #CHOICE_MODE_SINGLE}.
*
* @return The position of the currently checked item or
* {@link #INVALID_POSITION} if nothing is selected
*
* @see #setChoiceMode(int)
*/
public int getCheckedItemPosition() {
if (mChoiceMode == CHOICE_MODE_SINGLE && mCheckStates != null && mCheckStates.size() == 1) {
return mCheckStates.keyAt(0);
}
return INVALID_POSITION;
}
/**
* Returns the set of checked items in the list. The result is only valid if
* the choice mode has not been set to {@link #CHOICE_MODE_NONE}.
*
* @return A SparseBooleanArray which will return true for each call to
* get(int position) where position is a checked position in the
* list and false otherwise, or <code>null</code> if the choice
* mode is set to {@link #CHOICE_MODE_NONE}.
*/
public SparseBooleanArray getCheckedItemPositions() {
if (mChoiceMode != CHOICE_MODE_NONE) {
return mCheckStates;
}
return null;
}
/**
* Returns the set of checked items ids. The result is only valid if the
* choice mode has not been set to {@link #CHOICE_MODE_NONE} and the adapter
* has stable IDs. ({@link ListAdapter#hasStableIds()} == {@code true})
*
* @return A new array which contains the id of each checked item in the
* list.
*/
public long[] getCheckedItemIds() {
if (mChoiceMode == CHOICE_MODE_NONE || mCheckedIdStates == null || mAdapter == null) {
return new long[0];
}
final LongSparseArray<Integer> idStates = mCheckedIdStates;
final int count = idStates.size();
final long[] ids = new long[count];
for (int i = 0; i < count; i++) {
ids[i] = idStates.keyAt(i);
}
return ids;
}
/**
* Clear any choices previously set
*/
public void clearChoices() {
if (mCheckStates != null) {
mCheckStates.clear();
}
if (mCheckedIdStates != null) {
mCheckedIdStates.clear();
}
mCheckedItemCount = 0;
}
/**
* Sets the checked state of the specified position. The is only valid if
* the choice mode has been set to {@link #CHOICE_MODE_SINGLE} or
* {@link #CHOICE_MODE_MULTIPLE}.
*
* @param position The item whose checked state is to be checked
* @param value The new checked state for the item
*/
public void setItemChecked(int position, boolean value) {
if (mChoiceMode == CHOICE_MODE_NONE) {
return;
}
// Start selection mode if needed. We don't need to if we're unchecking something.
if (value && mChoiceMode == CHOICE_MODE_MULTIPLE_MODAL && mChoiceActionMode == null) {
if (mMultiChoiceModeCallback == null ||
!mMultiChoiceModeCallback.hasWrappedCallback()) {
throw new IllegalStateException("AbsListView: attempted to start selection mode " +
"for CHOICE_MODE_MULTIPLE_MODAL but no choice mode callback was " +
"supplied. Call setMultiChoiceModeListener to set a callback.");
}
mChoiceActionMode = startActionMode(mMultiChoiceModeCallback);
}
final boolean itemCheckChanged;
if (mChoiceMode == CHOICE_MODE_MULTIPLE || mChoiceMode == CHOICE_MODE_MULTIPLE_MODAL) {
boolean oldValue = mCheckStates.get(position);
mCheckStates.put(position, value);
if (mCheckedIdStates != null && mAdapter.hasStableIds()) {
if (value) {
mCheckedIdStates.put(mAdapter.getItemId(position), position);
} else {
mCheckedIdStates.delete(mAdapter.getItemId(position));
}
}
itemCheckChanged = oldValue != value;
if (itemCheckChanged) {
if (value) {
mCheckedItemCount++;
} else {
mCheckedItemCount--;
}
}
if (mChoiceActionMode != null) {
final long id = mAdapter.getItemId(position);
mMultiChoiceModeCallback.onItemCheckedStateChanged(mChoiceActionMode,
position, id, value);
}
} else {
boolean updateIds = mCheckedIdStates != null && mAdapter.hasStableIds();
// Clear all values if we're checking something, or unchecking the currently
// selected item
itemCheckChanged = isItemChecked(position) != value;
if (value || isItemChecked(position)) {
mCheckStates.clear();
if (updateIds) {
mCheckedIdStates.clear();
}
}
// this may end up selecting the value we just cleared but this way
// we ensure length of mCheckStates is 1, a fact getCheckedItemPosition relies on
if (value) {
mCheckStates.put(position, true);
if (updateIds) {
mCheckedIdStates.put(mAdapter.getItemId(position), position);
}
mCheckedItemCount = 1;
} else if (mCheckStates.size() == 0 || !mCheckStates.valueAt(0)) {
mCheckedItemCount = 0;
}
}
// Do not generate a data change while we are in the layout phase or data has not changed
if (!mInLayout && !mBlockLayoutRequests && itemCheckChanged) {
mDataChanged = true;
rememberSyncState();
requestLayout();
}
}
@Override
public boolean performItemClick(View view, int position, long id) {
boolean handled = false;
boolean dispatchItemClick = true;
if (mChoiceMode != CHOICE_MODE_NONE) {
handled = true;
boolean checkedStateChanged = false;
if (mChoiceMode == CHOICE_MODE_MULTIPLE ||
(mChoiceMode == CHOICE_MODE_MULTIPLE_MODAL && mChoiceActionMode != null)) {
boolean checked = !mCheckStates.get(position, false);
mCheckStates.put(position, checked);
if (mCheckedIdStates != null && mAdapter.hasStableIds()) {
if (checked) {
mCheckedIdStates.put(mAdapter.getItemId(position), position);
} else {
mCheckedIdStates.delete(mAdapter.getItemId(position));
}
}
if (checked) {
mCheckedItemCount++;
} else {
mCheckedItemCount--;
}
if (mChoiceActionMode != null) {
mMultiChoiceModeCallback.onItemCheckedStateChanged(mChoiceActionMode,
position, id, checked);
dispatchItemClick = false;
}
checkedStateChanged = true;
} else if (mChoiceMode == CHOICE_MODE_SINGLE) {
boolean checked = !mCheckStates.get(position, false);
if (checked) {
mCheckStates.clear();
mCheckStates.put(position, true);
if (mCheckedIdStates != null && mAdapter.hasStableIds()) {
mCheckedIdStates.clear();
mCheckedIdStates.put(mAdapter.getItemId(position), position);
}
mCheckedItemCount = 1;
} else if (mCheckStates.size() == 0 || !mCheckStates.valueAt(0)) {
mCheckedItemCount = 0;
}
checkedStateChanged = true;
}
if (checkedStateChanged) {
updateOnScreenCheckedViews();
}
}
if (dispatchItemClick) {
handled |= super.performItemClick(view, position, id);
}
return handled;
}
/**
* Perform a quick, in-place update of the checked or activated state
* on all visible item views. This should only be called when a valid
* choice mode is active.
*/
private void updateOnScreenCheckedViews() {
final int firstPos = mFirstPosition;
final int count = getChildCount();
final boolean useActivated = getContext().getApplicationInfo().targetSdkVersion
>= android.os.Build.VERSION_CODES.HONEYCOMB;
for (int i = 0; i < count; i++) {
final View child = getChildAt(i);
final int position = firstPos + i;
if (child instanceof Checkable) {
((Checkable) child).setChecked(mCheckStates.get(position));
} else if (useActivated) {
child.setActivated(mCheckStates.get(position));
}
}
}
/**
* @see #setChoiceMode(int)
*
* @return The current choice mode
*/
public int getChoiceMode() {
return mChoiceMode;
}
/**
* Defines the choice behavior for the List. By default, Lists do not have any choice behavior
* ({@link #CHOICE_MODE_NONE}). By setting the choiceMode to {@link #CHOICE_MODE_SINGLE}, the
* List allows up to one item to be in a chosen state. By setting the choiceMode to
* {@link #CHOICE_MODE_MULTIPLE}, the list allows any number of items to be chosen.
*
* @param choiceMode One of {@link #CHOICE_MODE_NONE}, {@link #CHOICE_MODE_SINGLE}, or
* {@link #CHOICE_MODE_MULTIPLE}
*/
public void setChoiceMode(int choiceMode) {
mChoiceMode = choiceMode;
if (mChoiceActionMode != null) {
mChoiceActionMode.finish();
mChoiceActionMode = null;
}
if (mChoiceMode != CHOICE_MODE_NONE) {
if (mCheckStates == null) {
mCheckStates = new SparseBooleanArray(0);
}
if (mCheckedIdStates == null && mAdapter != null && mAdapter.hasStableIds()) {
mCheckedIdStates = new LongSparseArray<Integer>(0);
}
// Modal multi-choice mode only has choices when the mode is active. Clear them.
if (mChoiceMode == CHOICE_MODE_MULTIPLE_MODAL) {
clearChoices();
setLongClickable(true);
}
}
}
/**
* Set a {@link MultiChoiceModeListener} that will manage the lifecycle of the
* selection {@link ActionMode}. Only used when the choice mode is set to
* {@link #CHOICE_MODE_MULTIPLE_MODAL}.
*
* @param listener Listener that will manage the selection mode
*
* @see #setChoiceMode(int)
*/
public void setMultiChoiceModeListener(MultiChoiceModeListener listener) {
if (mMultiChoiceModeCallback == null) {
mMultiChoiceModeCallback = new MultiChoiceModeWrapper();
}
mMultiChoiceModeCallback.setWrapped(listener);
}
/**
* @return true if all list content currently fits within the view boundaries
*/
private boolean contentFits() {
final int childCount = getChildCount();
if (childCount == 0) return true;
if (childCount != mItemCount) return false;
return getChildAt(0).getTop() >= mListPadding.top &&
getChildAt(childCount - 1).getBottom() <= getHeight() - mListPadding.bottom;
}
/**
* Specifies whether fast scrolling is enabled or disabled.
* <p>
* When fast scrolling is enabled, the user can quickly scroll through lists
* by dragging the fast scroll thumb.
* <p>
* If the adapter backing this list implements {@link SectionIndexer}, the
* fast scroller will display section header previews as the user scrolls.
* Additionally, the user will be able to quickly jump between sections by
* tapping along the length of the scroll bar.
*
* @see SectionIndexer
* @see #isFastScrollEnabled()
* @param enabled true to enable fast scrolling, false otherwise
*/
public void setFastScrollEnabled(final boolean enabled) {
if (mFastScrollEnabled != enabled) {
mFastScrollEnabled = enabled;
if (isOwnerThread()) {
setFastScrollerEnabledUiThread(enabled);
} else {
post(new Runnable() {
@Override
public void run() {
setFastScrollerEnabledUiThread(enabled);
}
});
}
}
}
private void setFastScrollerEnabledUiThread(boolean enabled) {
if (mFastScroll != null) {
mFastScroll.setEnabled(enabled);
} else if (enabled) {
mFastScroll = new FastScroller(this, mFastScrollStyle);
mFastScroll.setEnabled(true);
}
resolvePadding();
if (mFastScroll != null) {
mFastScroll.updateLayout();
}
}
/**
* Specifies the style of the fast scroller decorations.
*
* @param styleResId style resource containing fast scroller properties
* @see android.R.styleable#FastScroll
*/
public void setFastScrollStyle(int styleResId) {
if (mFastScroll == null) {
mFastScrollStyle = styleResId;
} else {
mFastScroll.setStyle(styleResId);
}
}
/**
* Set whether or not the fast scroller should always be shown in place of
* the standard scroll bars. This will enable fast scrolling if it is not
* already enabled.
* <p>
* Fast scrollers shown in this way will not fade out and will be a
* permanent fixture within the list. This is best combined with an inset
* scroll bar style to ensure the scroll bar does not overlap content.
*
* @param alwaysShow true if the fast scroller should always be displayed,
* false otherwise
* @see #setScrollBarStyle(int)
* @see #setFastScrollEnabled(boolean)
*/
public void setFastScrollAlwaysVisible(final boolean alwaysShow) {
if (mFastScrollAlwaysVisible != alwaysShow) {
if (alwaysShow && !mFastScrollEnabled) {
setFastScrollEnabled(true);
}
mFastScrollAlwaysVisible = alwaysShow;
if (isOwnerThread()) {
setFastScrollerAlwaysVisibleUiThread(alwaysShow);
} else {
post(new Runnable() {
@Override
public void run() {
setFastScrollerAlwaysVisibleUiThread(alwaysShow);
}
});
}
}
}
private void setFastScrollerAlwaysVisibleUiThread(boolean alwaysShow) {
if (mFastScroll != null) {
mFastScroll.setAlwaysShow(alwaysShow);
}
}
/**
* @return whether the current thread is the one that created the view
*/
private boolean isOwnerThread() {
return mOwnerThread == Thread.currentThread();
}
/**
* Returns true if the fast scroller is set to always show on this view.
*
* @return true if the fast scroller will always show
* @see #setFastScrollAlwaysVisible(boolean)
*/
public boolean isFastScrollAlwaysVisible() {
if (mFastScroll == null) {
return mFastScrollEnabled && mFastScrollAlwaysVisible;
} else {
return mFastScroll.isEnabled() && mFastScroll.isAlwaysShowEnabled();
}
}
@Override
public int getVerticalScrollbarWidth() {
if (mFastScroll != null && mFastScroll.isEnabled()) {
return Math.max(super.getVerticalScrollbarWidth(), mFastScroll.getWidth());
}
return super.getVerticalScrollbarWidth();
}
/**
* Returns true if the fast scroller is enabled.
*
* @see #setFastScrollEnabled(boolean)
* @return true if fast scroll is enabled, false otherwise
*/
@ViewDebug.ExportedProperty
public boolean isFastScrollEnabled() {
if (mFastScroll == null) {
return mFastScrollEnabled;
} else {
return mFastScroll.isEnabled();
}
}
@Override
public void setVerticalScrollbarPosition(int position) {
super.setVerticalScrollbarPosition(position);
if (mFastScroll != null) {
mFastScroll.setScrollbarPosition(position);
}
}
@Override
public void setScrollBarStyle(int style) {
super.setScrollBarStyle(style);
if (mFastScroll != null) {
mFastScroll.setScrollBarStyle(style);
}
}
/**
* If fast scroll is enabled, then don't draw the vertical scrollbar.
* @hide
*/
@Override
@UnsupportedAppUsage
protected boolean isVerticalScrollBarHidden() {
return isFastScrollEnabled();
}
/**
* When smooth scrollbar is enabled, the position and size of the scrollbar thumb
* is computed based on the number of visible pixels in the visible items. This
* however assumes that all list items have the same height. If you use a list in
* which items have different heights, the scrollbar will change appearance as the
* user scrolls through the list. To avoid this issue, you need to disable this
* property.
*
* When smooth scrollbar is disabled, the position and size of the scrollbar thumb
* is based solely on the number of items in the adapter and the position of the
* visible items inside the adapter. This provides a stable scrollbar as the user
* navigates through a list of items with varying heights.
*
* @param enabled Whether or not to enable smooth scrollbar.
*
* @see #setSmoothScrollbarEnabled(boolean)
* @attr ref android.R.styleable#AbsListView_smoothScrollbar
*/
public void setSmoothScrollbarEnabled(boolean enabled) {
mSmoothScrollbarEnabled = enabled;
}
/**
* Returns the current state of the fast scroll feature.
*
* @return True if smooth scrollbar is enabled is enabled, false otherwise.
*
* @see #setSmoothScrollbarEnabled(boolean)
*/
@ViewDebug.ExportedProperty
public boolean isSmoothScrollbarEnabled() {
return mSmoothScrollbarEnabled;
}
/**
* Set the listener that will receive notifications every time the list scrolls.
*
* @param l the scroll listener
*/
public void setOnScrollListener(OnScrollListener l) {
mOnScrollListener = l;
invokeOnItemScrollListener();
}
/**
* Notify our scroll listener (if there is one) of a change in scroll state
*/
@UnsupportedAppUsage
void invokeOnItemScrollListener() {
if (mFastScroll != null) {
mFastScroll.onScroll(mFirstPosition, getChildCount(), mItemCount);
}
if (mOnScrollListener != null) {
mOnScrollListener.onScroll(this, mFirstPosition, getChildCount(), mItemCount);
}
onScrollChanged(0, 0, 0, 0); // dummy values, View's implementation does not use these.
}
/** @hide */
@Override
public void sendAccessibilityEventUnchecked(AccessibilityEvent event) {
// Since this class calls onScrollChanged even if the mFirstPosition and the
// child count have not changed we will avoid sending duplicate accessibility
// events.
if (event.getEventType() == AccessibilityEvent.TYPE_VIEW_SCROLLED) {
final int firstVisiblePosition = getFirstVisiblePosition();
final int lastVisiblePosition = getLastVisiblePosition();
if (mLastAccessibilityScrollEventFromIndex == firstVisiblePosition
&& mLastAccessibilityScrollEventToIndex == lastVisiblePosition) {
return;
} else {
mLastAccessibilityScrollEventFromIndex = firstVisiblePosition;
mLastAccessibilityScrollEventToIndex = lastVisiblePosition;
}
}
super.sendAccessibilityEventUnchecked(event);
}
@Override
public CharSequence getAccessibilityClassName() {
return AbsListView.class.getName();
}
/** @hide */
@Override
public void onInitializeAccessibilityNodeInfoInternal(AccessibilityNodeInfo info) {
super.onInitializeAccessibilityNodeInfoInternal(info);
if (isEnabled()) {
if (canScrollUp()) {
info.addAction(AccessibilityAction.ACTION_SCROLL_BACKWARD);
info.addAction(AccessibilityAction.ACTION_SCROLL_UP);
info.setScrollable(true);
}
if (canScrollDown()) {
info.addAction(AccessibilityAction.ACTION_SCROLL_FORWARD);
info.addAction(AccessibilityAction.ACTION_SCROLL_DOWN);
info.setScrollable(true);
}
}
info.removeAction(AccessibilityAction.ACTION_CLICK);
info.setClickable(false);
}
int getSelectionModeForAccessibility() {
final int choiceMode = getChoiceMode();
switch (choiceMode) {
case CHOICE_MODE_NONE:
return CollectionInfo.SELECTION_MODE_NONE;
case CHOICE_MODE_SINGLE:
return CollectionInfo.SELECTION_MODE_SINGLE;
case CHOICE_MODE_MULTIPLE:
case CHOICE_MODE_MULTIPLE_MODAL:
return CollectionInfo.SELECTION_MODE_MULTIPLE;
default:
return CollectionInfo.SELECTION_MODE_NONE;
}
}
/** @hide */
@Override
public boolean performAccessibilityActionInternal(int action, Bundle arguments) {
if (super.performAccessibilityActionInternal(action, arguments)) {
return true;
}
switch (action) {
case AccessibilityNodeInfo.ACTION_SCROLL_FORWARD:
case R.id.accessibilityActionScrollDown: {
if (isEnabled() && canScrollDown()) {
final int viewportHeight = getHeight() - mListPadding.top - mListPadding.bottom;
smoothScrollBy(viewportHeight, PositionScroller.SCROLL_DURATION);
return true;
}
} return false;
case AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD:
case R.id.accessibilityActionScrollUp: {
if (isEnabled() && canScrollUp()) {
final int viewportHeight = getHeight() - mListPadding.top - mListPadding.bottom;
smoothScrollBy(-viewportHeight, PositionScroller.SCROLL_DURATION);
return true;
}
} return false;
}
return false;
}
/** @hide */
@Override
public View findViewByAccessibilityIdTraversal(int accessibilityId) {
if (accessibilityId == getAccessibilityViewId()) {
return this;
}
return super.findViewByAccessibilityIdTraversal(accessibilityId);
}
/**
* Indicates whether the children's drawing cache is used during a scroll.
* By default, the drawing cache is enabled but this will consume more memory.
*
* @return true if the scrolling cache is enabled, false otherwise
*
* @see #setScrollingCacheEnabled(boolean)
* @see View#setDrawingCacheEnabled(boolean)
*/
@ViewDebug.ExportedProperty
public boolean isScrollingCacheEnabled() {
return mScrollingCacheEnabled;
}
/**
* Enables or disables the children's drawing cache during a scroll.
* By default, the drawing cache is enabled but this will use more memory.
*
* When the scrolling cache is enabled, the caches are kept after the
* first scrolling. You can manually clear the cache by calling
* {@link android.view.ViewGroup#setChildrenDrawingCacheEnabled(boolean)}.
*
* @param enabled true to enable the scroll cache, false otherwise
*
* @see #isScrollingCacheEnabled()
* @see View#setDrawingCacheEnabled(boolean)
*/
public void setScrollingCacheEnabled(boolean enabled) {
if (mScrollingCacheEnabled && !enabled) {
clearScrollingCache();
}
mScrollingCacheEnabled = enabled;
}
/**
* Enables or disables the type filter window. If enabled, typing when
* this view has focus will filter the children to match the users input.
* Note that the {@link Adapter} used by this view must implement the
* {@link Filterable} interface.
*
* @param textFilterEnabled true to enable type filtering, false otherwise
*
* @see Filterable
*/
public void setTextFilterEnabled(boolean textFilterEnabled) {
mTextFilterEnabled = textFilterEnabled;
}
/**
* Indicates whether type filtering is enabled for this view
*
* @return true if type filtering is enabled, false otherwise
*
* @see #setTextFilterEnabled(boolean)
* @see Filterable
*/
@ViewDebug.ExportedProperty
public boolean isTextFilterEnabled() {
return mTextFilterEnabled;
}
@Override
public void getFocusedRect(Rect r) {
View view = getSelectedView();
if (view != null && view.getParent() == this) {
// the focused rectangle of the selected view offset into the
// coordinate space of this view.
view.getFocusedRect(r);
offsetDescendantRectToMyCoords(view, r);
} else {
// otherwise, just the norm
super.getFocusedRect(r);
}
}
private void useDefaultSelector() {
setSelector(getContext().getDrawable(
com.android.internal.R.drawable.list_selector_background));
}
/**
* Indicates whether the content of this view is pinned to, or stacked from,
* the bottom edge.
*
* @return true if the content is stacked from the bottom edge, false otherwise
*/
@ViewDebug.ExportedProperty
public boolean isStackFromBottom() {
return mStackFromBottom;
}
/**
* When stack from bottom is set to true, the list fills its content starting from
* the bottom of the view.
*
* @param stackFromBottom true to pin the view's content to the bottom edge,
* false to pin the view's content to the top edge
*/
public void setStackFromBottom(boolean stackFromBottom) {
if (mStackFromBottom != stackFromBottom) {
mStackFromBottom = stackFromBottom;
requestLayoutIfNecessary();
}
}
void requestLayoutIfNecessary() {
if (getChildCount() > 0) {
resetList();
requestLayout();
invalidate();
}
}
static class SavedState extends BaseSavedState {
long selectedId;
@UnsupportedAppUsage
long firstId;
@UnsupportedAppUsage
int viewTop;
int position;
int height;
String filter;
boolean inActionMode;
int checkedItemCount;
SparseBooleanArray checkState;
LongSparseArray<Integer> checkIdState;
/**
* Constructor called from {@link AbsListView#onSaveInstanceState()}
*/
SavedState(Parcelable superState) {
super(superState);
}
/**
* Constructor called from {@link #CREATOR}
*/
private SavedState(Parcel in) {
super(in);
selectedId = in.readLong();
firstId = in.readLong();
viewTop = in.readInt();
position = in.readInt();
height = in.readInt();
filter = in.readString();
inActionMode = in.readByte() != 0;
checkedItemCount = in.readInt();
checkState = in.readSparseBooleanArray();
final int N = in.readInt();
if (N > 0) {
checkIdState = new LongSparseArray<Integer>();
for (int i=0; i<N; i++) {
final long key = in.readLong();
final int value = in.readInt();
checkIdState.put(key, value);
}
}
}
@Override
public void writeToParcel(Parcel out, int flags) {
super.writeToParcel(out, flags);
out.writeLong(selectedId);
out.writeLong(firstId);
out.writeInt(viewTop);
out.writeInt(position);
out.writeInt(height);
out.writeString(filter);
out.writeByte((byte) (inActionMode ? 1 : 0));
out.writeInt(checkedItemCount);
out.writeSparseBooleanArray(checkState);
final int N = checkIdState != null ? checkIdState.size() : 0;
out.writeInt(N);
for (int i=0; i<N; i++) {
out.writeLong(checkIdState.keyAt(i));
out.writeInt(checkIdState.valueAt(i));
}
}
@Override
public String toString() {
return "AbsListView.SavedState{"
+ Integer.toHexString(System.identityHashCode(this))
+ " selectedId=" + selectedId
+ " firstId=" + firstId
+ " viewTop=" + viewTop
+ " position=" + position
+ " height=" + height
+ " filter=" + filter
+ " checkState=" + checkState + "}";
}
public static final Parcelable.Creator<SavedState> CREATOR
= new Parcelable.Creator<SavedState>() {
@Override
public SavedState createFromParcel(Parcel in) {
return new SavedState(in);
}
@Override
public SavedState[] newArray(int size) {
return new SavedState[size];
}
};
}
@Override
public Parcelable onSaveInstanceState() {
/*
* This doesn't really make sense as the place to dismiss the
* popups, but there don't seem to be any other useful hooks
* that happen early enough to keep from getting complaints
* about having leaked the window.
*/
dismissPopup();
Parcelable superState = super.onSaveInstanceState();
SavedState ss = new SavedState(superState);
if (mPendingSync != null) {
// Just keep what we last restored.
ss.selectedId = mPendingSync.selectedId;
ss.firstId = mPendingSync.firstId;
ss.viewTop = mPendingSync.viewTop;
ss.position = mPendingSync.position;
ss.height = mPendingSync.height;
ss.filter = mPendingSync.filter;
ss.inActionMode = mPendingSync.inActionMode;
ss.checkedItemCount = mPendingSync.checkedItemCount;
ss.checkState = mPendingSync.checkState;
ss.checkIdState = mPendingSync.checkIdState;
return ss;
}
boolean haveChildren = getChildCount() > 0 && mItemCount > 0;
long selectedId = getSelectedItemId();
ss.selectedId = selectedId;
ss.height = getHeight();
if (selectedId >= 0) {
// Remember the selection
ss.viewTop = mSelectedTop;
ss.position = getSelectedItemPosition();
ss.firstId = INVALID_POSITION;
} else {
if (haveChildren && mFirstPosition > 0) {
// Remember the position of the first child.
// We only do this if we are not currently at the top of
// the list, for two reasons:
// (1) The list may be in the process of becoming empty, in
// which case mItemCount may not be 0, but if we try to
// ask for any information about position 0 we will crash.
// (2) Being "at the top" seems like a special case, anyway,
// and the user wouldn't expect to end up somewhere else when
// they revisit the list even if its content has changed.
View v = getChildAt(0);
ss.viewTop = v.getTop();
int firstPos = mFirstPosition;
if (firstPos >= mItemCount) {
firstPos = mItemCount - 1;
}
ss.position = firstPos;
ss.firstId = mAdapter.getItemId(firstPos);
} else {
ss.viewTop = 0;
ss.firstId = INVALID_POSITION;
ss.position = 0;
}
}
ss.filter = null;
if (mFiltered) {
final EditText textFilter = mTextFilter;
if (textFilter != null) {
Editable filterText = textFilter.getText();
if (filterText != null) {
ss.filter = filterText.toString();
}
}
}
ss.inActionMode = mChoiceMode == CHOICE_MODE_MULTIPLE_MODAL && mChoiceActionMode != null;
if (mCheckStates != null) {
ss.checkState = mCheckStates.clone();
}
if (mCheckedIdStates != null) {
final LongSparseArray<Integer> idState = new LongSparseArray<Integer>();
final int count = mCheckedIdStates.size();
for (int i = 0; i < count; i++) {
idState.put(mCheckedIdStates.keyAt(i), mCheckedIdStates.valueAt(i));
}
ss.checkIdState = idState;
}
ss.checkedItemCount = mCheckedItemCount;
if (mRemoteAdapter != null) {
mRemoteAdapter.saveRemoteViewsCache();
}
return ss;
}
@Override
public void onRestoreInstanceState(Parcelable state) {
SavedState ss = (SavedState) state;
super.onRestoreInstanceState(ss.getSuperState());
mDataChanged = true;
mSyncHeight = ss.height;
if (ss.selectedId >= 0) {
mNeedSync = true;
mPendingSync = ss;
mSyncRowId = ss.selectedId;
mSyncPosition = ss.position;
mSpecificTop = ss.viewTop;
mSyncMode = SYNC_SELECTED_POSITION;
} else if (ss.firstId >= 0) {
setSelectedPositionInt(INVALID_POSITION);
// Do this before setting mNeedSync since setNextSelectedPosition looks at mNeedSync
setNextSelectedPositionInt(INVALID_POSITION);
mSelectorPosition = INVALID_POSITION;
mNeedSync = true;
mPendingSync = ss;
mSyncRowId = ss.firstId;
mSyncPosition = ss.position;
mSpecificTop = ss.viewTop;
mSyncMode = SYNC_FIRST_POSITION;
}
setFilterText(ss.filter);
if (ss.checkState != null) {
mCheckStates = ss.checkState;
}
if (ss.checkIdState != null) {
mCheckedIdStates = ss.checkIdState;
}
mCheckedItemCount = ss.checkedItemCount;
if (ss.inActionMode && mChoiceMode == CHOICE_MODE_MULTIPLE_MODAL &&
mMultiChoiceModeCallback != null) {
mChoiceActionMode = startActionMode(mMultiChoiceModeCallback);
}
requestLayout();
}
private boolean acceptFilter() {
return mTextFilterEnabled && getAdapter() instanceof Filterable &&
((Filterable) getAdapter()).getFilter() != null;
}
/**
* Sets the initial value for the text filter.
* @param filterText The text to use for the filter.
*
* @see #setTextFilterEnabled
*/
public void setFilterText(String filterText) {
// TODO: Should we check for acceptFilter()?
if (mTextFilterEnabled && !TextUtils.isEmpty(filterText)) {
createTextFilter(false);
// This is going to call our listener onTextChanged, but we might not
// be ready to bring up a window yet
mTextFilter.setText(filterText);
mTextFilter.setSelection(filterText.length());
if (mAdapter instanceof Filterable) {
// if mPopup is non-null, then onTextChanged will do the filtering
if (mPopup == null) {
Filter f = ((Filterable) mAdapter).getFilter();
f.filter(filterText);
}
// Set filtered to true so we will display the filter window when our main
// window is ready
mFiltered = true;
mDataSetObserver.clearSavedState();
}
}
}
/**
* Returns the list's text filter, if available.
* @return the list's text filter or null if filtering isn't enabled
*/
public CharSequence getTextFilter() {
if (mTextFilterEnabled && mTextFilter != null) {
return mTextFilter.getText();
}
return null;
}
@Override
protected void onFocusChanged(boolean gainFocus, int direction, Rect previouslyFocusedRect) {
super.onFocusChanged(gainFocus, direction, previouslyFocusedRect);
if (gainFocus && mSelectedPosition < 0 && !isInTouchMode()) {
if (!isAttachedToWindow() && mAdapter != null) {
// Data may have changed while we were detached and it's valid
// to change focus while detached. Refresh so we don't die.
mDataChanged = true;
mOldItemCount = mItemCount;
mItemCount = mAdapter.getCount();
}
resurrectSelection();
}
}
@Override
public void requestLayout() {
if (!mBlockLayoutRequests && !mInLayout) {
super.requestLayout();
}
}
/**
* The list is empty. Clear everything out.
*/
void resetList() {
removeAllViewsInLayout();
mFirstPosition = 0;
mDataChanged = false;
mPositionScrollAfterLayout = null;
mNeedSync = false;
mPendingSync = null;
mOldSelectedPosition = INVALID_POSITION;
mOldSelectedRowId = INVALID_ROW_ID;
setSelectedPositionInt(INVALID_POSITION);
setNextSelectedPositionInt(INVALID_POSITION);
mSelectedTop = 0;
mSelectorPosition = INVALID_POSITION;
mSelectorRect.setEmpty();
invalidate();
}
@Override
protected int computeVerticalScrollExtent() {
final int count = getChildCount();
if (count > 0) {
if (mSmoothScrollbarEnabled) {
int extent = count * 100;
View view = getChildAt(0);
final int top = view.getTop();
int height = view.getHeight();
if (height > 0) {
extent += (top * 100) / height;
}
view = getChildAt(count - 1);
final int bottom = view.getBottom();
height = view.getHeight();
if (height > 0) {
extent -= ((bottom - getHeight()) * 100) / height;
}
return extent;
} else {
return 1;
}
}
return 0;
}
@Override
protected int computeVerticalScrollOffset() {
final int firstPosition = mFirstPosition;
final int childCount = getChildCount();
if (firstPosition >= 0 && childCount > 0) {
if (mSmoothScrollbarEnabled) {
final View view = getChildAt(0);
final int top = view.getTop();
int height = view.getHeight();
if (height > 0) {
return Math.max(firstPosition * 100 - (top * 100) / height +
(int)((float)mScrollY / getHeight() * mItemCount * 100), 0);
}
} else {
int index;
final int count = mItemCount;
if (firstPosition == 0) {
index = 0;
} else if (firstPosition + childCount == count) {
index = count;
} else {
index = firstPosition + childCount / 2;
}
return (int) (firstPosition + childCount * (index / (float) count));
}
}
return 0;
}
@Override
protected int computeVerticalScrollRange() {
int result;
if (mSmoothScrollbarEnabled) {
result = Math.max(mItemCount * 100, 0);
if (mScrollY != 0) {
// Compensate for overscroll
result += Math.abs((int) ((float) mScrollY / getHeight() * mItemCount * 100));
}
} else {
result = mItemCount;
}
return result;
}
@Override
protected float getTopFadingEdgeStrength() {
final int count = getChildCount();
final float fadeEdge = super.getTopFadingEdgeStrength();
if (count == 0) {
return fadeEdge;
} else {
if (mFirstPosition > 0) {
return 1.0f;
}
final int top = getChildAt(0).getTop();
final float fadeLength = getVerticalFadingEdgeLength();
return top < mPaddingTop ? -(top - mPaddingTop) / fadeLength : fadeEdge;
}
}
@Override
protected float getBottomFadingEdgeStrength() {
final int count = getChildCount();
final float fadeEdge = super.getBottomFadingEdgeStrength();
if (count == 0) {
return fadeEdge;
} else {
if (mFirstPosition + count - 1 < mItemCount - 1) {
return 1.0f;
}
final int bottom = getChildAt(count - 1).getBottom();
final int height = getHeight();
final float fadeLength = getVerticalFadingEdgeLength();
return bottom > height - mPaddingBottom ?
(bottom - height + mPaddingBottom) / fadeLength : fadeEdge;
}
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
if (mSelector == null) {
useDefaultSelector();
}
final Rect listPadding = mListPadding;
listPadding.left = mSelectionLeftPadding + mPaddingLeft;
listPadding.top = mSelectionTopPadding + mPaddingTop;
listPadding.right = mSelectionRightPadding + mPaddingRight;
listPadding.bottom = mSelectionBottomPadding + mPaddingBottom;
// Check if our previous measured size was at a point where we should scroll later.
if (mTranscriptMode == TRANSCRIPT_MODE_NORMAL) {
final int childCount = getChildCount();
final int listBottom = getHeight() - getPaddingBottom();
final View lastChild = getChildAt(childCount - 1);
final int lastBottom = lastChild != null ? lastChild.getBottom() : listBottom;
mForceTranscriptScroll = mFirstPosition + childCount >= mLastHandledItemCount &&
lastBottom <= listBottom;
}
}
/**
* Subclasses should NOT override this method but
* {@link #layoutChildren()} instead.
*/
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
super.onLayout(changed, l, t, r, b);
mInLayout = true;
final int childCount = getChildCount();
if (changed) {
for (int i = 0; i < childCount; i++) {
getChildAt(i).forceLayout();
}
mRecycler.markChildrenDirty();
}
layoutChildren();
mOverscrollMax = (b - t) / OVERSCROLL_LIMIT_DIVISOR;
// TODO: Move somewhere sane. This doesn't belong in onLayout().
if (mFastScroll != null) {
mFastScroll.onItemCountChanged(getChildCount(), mItemCount);
}
mInLayout = false;
}
/**
* @hide
*/
@Override
protected boolean setFrame(int left, int top, int right, int bottom) {
final boolean changed = super.setFrame(left, top, right, bottom);
if (changed) {
// Reposition the popup when the frame has changed. This includes
// translating the widget, not just changing its dimension. The
// filter popup needs to follow the widget.
final boolean visible = getWindowVisibility() == View.VISIBLE;
if (mFiltered && visible && mPopup != null && mPopup.isShowing()) {
positionPopup();
}
}
return changed;
}
/**
* Subclasses must override this method to layout their children.
*/
protected void layoutChildren() {
}
/**
* @param focusedView view that holds accessibility focus
* @return direct child that contains accessibility focus, or null if no
* child contains accessibility focus
*/
View getAccessibilityFocusedChild(View focusedView) {
ViewParent viewParent = focusedView.getParent();
while ((viewParent instanceof View) && (viewParent != this)) {
focusedView = (View) viewParent;
viewParent = viewParent.getParent();
}
if (!(viewParent instanceof View)) {
return null;
}
return focusedView;
}
void updateScrollIndicators() {
if (mScrollUp != null) {
mScrollUp.setVisibility(canScrollUp() ? View.VISIBLE : View.INVISIBLE);
}
if (mScrollDown != null) {
mScrollDown.setVisibility(canScrollDown() ? View.VISIBLE : View.INVISIBLE);
}
}
@UnsupportedAppUsage
private boolean canScrollUp() {
boolean canScrollUp;
// 0th element is not visible
canScrollUp = mFirstPosition > 0;
// ... Or top of 0th element is not visible
if (!canScrollUp) {
if (getChildCount() > 0) {
View child = getChildAt(0);
canScrollUp = child.getTop() < mListPadding.top;
}
}
return canScrollUp;
}
@UnsupportedAppUsage
private boolean canScrollDown() {
boolean canScrollDown;
int count = getChildCount();
// Last item is not visible
canScrollDown = (mFirstPosition + count) < mItemCount;
// ... Or bottom of the last element is not visible
if (!canScrollDown && count > 0) {
View child = getChildAt(count - 1);
canScrollDown = child.getBottom() > mBottom - mListPadding.bottom;
}
return canScrollDown;
}
@Override
@ViewDebug.ExportedProperty
public View getSelectedView() {
if (mItemCount > 0 && mSelectedPosition >= 0) {
return getChildAt(mSelectedPosition - mFirstPosition);
} else {
return null;
}
}
/**
* List padding is the maximum of the normal view's padding and the padding of the selector.
*
* @see android.view.View#getPaddingTop()
* @see #getSelector()
*
* @return The top list padding.
*/
public int getListPaddingTop() {
return mListPadding.top;
}
/**
* List padding is the maximum of the normal view's padding and the padding of the selector.
*
* @see android.view.View#getPaddingBottom()
* @see #getSelector()
*
* @return The bottom list padding.
*/
public int getListPaddingBottom() {
return mListPadding.bottom;
}
/**
* List padding is the maximum of the normal view's padding and the padding of the selector.
*
* @see android.view.View#getPaddingLeft()
* @see #getSelector()
*
* @return The left list padding.
*/
public int getListPaddingLeft() {
return mListPadding.left;
}
/**
* List padding is the maximum of the normal view's padding and the padding of the selector.
*
* @see android.view.View#getPaddingRight()
* @see #getSelector()
*
* @return The right list padding.
*/
public int getListPaddingRight() {
return mListPadding.right;
}
/**
* Gets a view and have it show the data associated with the specified
* position. This is called when we have already discovered that the view
* is not available for reuse in the recycle bin. The only choices left are
* converting an old view or making a new one.
*
* @param position the position to display
* @param outMetadata an array of at least 1 boolean where the first entry
* will be set {@code true} if the view is currently
* attached to the window, {@code false} otherwise (e.g.
* newly-inflated or remained scrap for multiple layout
* passes)
*
* @return A view displaying the data associated with the specified position
*/
View obtainView(int position, boolean[] outMetadata) {
Trace.traceBegin(Trace.TRACE_TAG_VIEW, "obtainView");
outMetadata[0] = false;
// Check whether we have a transient state view. Attempt to re-bind the
// data and discard the view if we fail.
final View transientView = mRecycler.getTransientStateView(position);
if (transientView != null) {
final LayoutParams params = (LayoutParams) transientView.getLayoutParams();
// If the view type hasn't changed, attempt to re-bind the data.
if (params.viewType == mAdapter.getItemViewType(position)) {
final View updatedView = mAdapter.getView(position, transientView, this);
// If we failed to re-bind the data, scrap the obtained view.
if (updatedView != transientView) {
setItemViewLayoutParams(updatedView, position);
mRecycler.addScrapView(updatedView, position);
}
}
outMetadata[0] = true;
// Finish the temporary detach started in addScrapView().
transientView.dispatchFinishTemporaryDetach();
return transientView;
}
final View scrapView = mRecycler.getScrapView(position);
final View child = mAdapter.getView(position, scrapView, this);
if (scrapView != null) {
if (child != scrapView) {
// Failed to re-bind the data, return scrap to the heap.
mRecycler.addScrapView(scrapView, position);
} else if (child.isTemporarilyDetached()) {
outMetadata[0] = true;
// Finish the temporary detach started in addScrapView().
child.dispatchFinishTemporaryDetach();
}
}
if (mCacheColorHint != 0) {
child.setDrawingCacheBackgroundColor(mCacheColorHint);
}
if (child.getImportantForAccessibility() == IMPORTANT_FOR_ACCESSIBILITY_AUTO) {
child.setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_YES);
}
setItemViewLayoutParams(child, position);
if (AccessibilityManager.getInstance(mContext).isEnabled()) {
if (mAccessibilityDelegate == null) {
mAccessibilityDelegate = new ListItemAccessibilityDelegate();
}
if (child.getAccessibilityDelegate() == null) {
child.setAccessibilityDelegate(mAccessibilityDelegate);
}
}
Trace.traceEnd(Trace.TRACE_TAG_VIEW);
return child;
}
private void setItemViewLayoutParams(View child, int position) {
final ViewGroup.LayoutParams vlp = child.getLayoutParams();
LayoutParams lp;
if (vlp == null) {
lp = (LayoutParams) generateDefaultLayoutParams();
} else if (!checkLayoutParams(vlp)) {
lp = (LayoutParams) generateLayoutParams(vlp);
} else {
lp = (LayoutParams) vlp;
}
if (mAdapterHasStableIds) {
lp.itemId = mAdapter.getItemId(position);
}
lp.viewType = mAdapter.getItemViewType(position);
lp.isEnabled = mAdapter.isEnabled(position);
if (lp != vlp) {
child.setLayoutParams(lp);
}
}
class ListItemAccessibilityDelegate extends AccessibilityDelegate {
@Override
public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfo info) {
super.onInitializeAccessibilityNodeInfo(host, info);
final int position = getPositionForView(host);
onInitializeAccessibilityNodeInfoForItem(host, position, info);
}
@Override
public boolean performAccessibilityAction(View host, int action, Bundle arguments) {
if (super.performAccessibilityAction(host, action, arguments)) {
return true;
}
final int position = getPositionForView(host);
if (position == INVALID_POSITION || mAdapter == null) {
// Cannot perform actions on invalid items.
return false;
}
if (position >= mAdapter.getCount()) {
// The position is no longer valid, likely due to a data set
// change. We could fail here for all data set changes, since
// there is a chance that the data bound to the view may no
// longer exist at the same position within the adapter, but
// it's more consistent with the standard touch interaction to
// click at whatever may have moved into that position.
return false;
}
final boolean isItemEnabled;
final ViewGroup.LayoutParams lp = host.getLayoutParams();
if (lp instanceof AbsListView.LayoutParams) {
isItemEnabled = ((AbsListView.LayoutParams) lp).isEnabled;
} else {
isItemEnabled = false;
}
if (!isEnabled() || !isItemEnabled) {
// Cannot perform actions on disabled items.
return false;
}
switch (action) {
case AccessibilityNodeInfo.ACTION_CLEAR_SELECTION: {
if (getSelectedItemPosition() == position) {
setSelection(INVALID_POSITION);
return true;
}
} return false;
case AccessibilityNodeInfo.ACTION_SELECT: {
if (getSelectedItemPosition() != position) {
setSelection(position);
return true;
}
} return false;
case AccessibilityNodeInfo.ACTION_CLICK: {
if (isItemClickable(host)) {
final long id = getItemIdAtPosition(position);
return performItemClick(host, position, id);
}
} return false;
case AccessibilityNodeInfo.ACTION_LONG_CLICK: {
if (isLongClickable()) {
final long id = getItemIdAtPosition(position);
return performLongPress(host, position, id);
}
} return false;
}
return false;
}
}
/**
* Initializes an {@link AccessibilityNodeInfo} with information about a
* particular item in the list.
*
* @param view View representing the list item.
* @param position Position of the list item within the adapter.
* @param info Node info to populate.
*/
public void onInitializeAccessibilityNodeInfoForItem(
View view, int position, AccessibilityNodeInfo info) {
if (position == INVALID_POSITION) {
// The item doesn't exist, so there's not much we can do here.
return;
}
final boolean isItemEnabled;
final ViewGroup.LayoutParams lp = view.getLayoutParams();
if (lp instanceof AbsListView.LayoutParams) {
isItemEnabled = ((AbsListView.LayoutParams) lp).isEnabled;
} else {
isItemEnabled = false;
}
if (!isEnabled() || !isItemEnabled) {
info.setEnabled(false);
return;
}
if (position == getSelectedItemPosition()) {
info.setSelected(true);
info.addAction(AccessibilityAction.ACTION_CLEAR_SELECTION);
} else {
info.addAction(AccessibilityAction.ACTION_SELECT);
}
if (isItemClickable(view)) {
info.addAction(AccessibilityAction.ACTION_CLICK);
info.setClickable(true);
}
if (isLongClickable()) {
info.addAction(AccessibilityAction.ACTION_LONG_CLICK);
info.setLongClickable(true);
}
}
private boolean isItemClickable(View view) {
return !view.hasExplicitFocusable();
}
/**
* Positions the selector in a way that mimics touch.
*/
void positionSelectorLikeTouch(int position, View sel, float x, float y) {
positionSelector(position, sel, true, x, y);
}
/**
* Positions the selector in a way that mimics keyboard focus.
*/
void positionSelectorLikeFocus(int position, View sel) {
if (mSelector != null && mSelectorPosition != position && position != INVALID_POSITION) {
final Rect bounds = mSelectorRect;
final float x = bounds.exactCenterX();
final float y = bounds.exactCenterY();
positionSelector(position, sel, true, x, y);
} else {
positionSelector(position, sel);
}
}
void positionSelector(int position, View sel) {
positionSelector(position, sel, false, -1, -1);
}
@UnsupportedAppUsage
private void positionSelector(int position, View sel, boolean manageHotspot, float x, float y) {
final boolean positionChanged = position != mSelectorPosition;
if (position != INVALID_POSITION) {
mSelectorPosition = position;
}
final Rect selectorRect = mSelectorRect;
selectorRect.set(sel.getLeft(), sel.getTop(), sel.getRight(), sel.getBottom());
if (sel instanceof SelectionBoundsAdjuster) {
((SelectionBoundsAdjuster)sel).adjustListItemSelectionBounds(selectorRect);
}
// Adjust for selection padding.
selectorRect.left -= mSelectionLeftPadding;
selectorRect.top -= mSelectionTopPadding;
selectorRect.right += mSelectionRightPadding;
selectorRect.bottom += mSelectionBottomPadding;
// Update the child enabled state prior to updating the selector.
final boolean isChildViewEnabled = sel.isEnabled();
if (mIsChildViewEnabled != isChildViewEnabled) {
mIsChildViewEnabled = isChildViewEnabled;
}
// Update the selector drawable's state and position.
final Drawable selector = mSelector;
if (selector != null) {
if (positionChanged) {
// Wipe out the current selector state so that we can start
// over in the new position with a fresh state.
selector.setVisible(false, false);
selector.setState(StateSet.NOTHING);
}
selector.setBounds(selectorRect);
if (positionChanged) {
if (getVisibility() == VISIBLE) {
selector.setVisible(true, false);
}
updateSelectorState();
}
if (manageHotspot) {
selector.setHotspot(x, y);
}
}
}
@Override
protected void dispatchDraw(Canvas canvas) {
int saveCount = 0;
final boolean clipToPadding = (mGroupFlags & CLIP_TO_PADDING_MASK) == CLIP_TO_PADDING_MASK;
if (clipToPadding) {
saveCount = canvas.save();
final int scrollX = mScrollX;
final int scrollY = mScrollY;
canvas.clipRect(scrollX + mPaddingLeft, scrollY + mPaddingTop,
scrollX + mRight - mLeft - mPaddingRight,
scrollY + mBottom - mTop - mPaddingBottom);
mGroupFlags &= ~CLIP_TO_PADDING_MASK;
}
final boolean drawSelectorOnTop = mDrawSelectorOnTop;
if (!drawSelectorOnTop) {
drawSelector(canvas);
}
super.dispatchDraw(canvas);
if (drawSelectorOnTop) {
drawSelector(canvas);
}
if (clipToPadding) {
canvas.restoreToCount(saveCount);
mGroupFlags |= CLIP_TO_PADDING_MASK;
}
}
@Override
protected boolean isPaddingOffsetRequired() {
return (mGroupFlags & CLIP_TO_PADDING_MASK) != CLIP_TO_PADDING_MASK;
}
@Override
protected int getLeftPaddingOffset() {
return (mGroupFlags & CLIP_TO_PADDING_MASK) == CLIP_TO_PADDING_MASK ? 0 : -mPaddingLeft;
}
@Override
protected int getTopPaddingOffset() {
return (mGroupFlags & CLIP_TO_PADDING_MASK) == CLIP_TO_PADDING_MASK ? 0 : -mPaddingTop;
}
@Override
protected int getRightPaddingOffset() {
return (mGroupFlags & CLIP_TO_PADDING_MASK) == CLIP_TO_PADDING_MASK ? 0 : mPaddingRight;
}
@Override
protected int getBottomPaddingOffset() {
return (mGroupFlags & CLIP_TO_PADDING_MASK) == CLIP_TO_PADDING_MASK ? 0 : mPaddingBottom;
}
/**
* @hide
*/
@Override
protected void internalSetPadding(int left, int top, int right, int bottom) {
super.internalSetPadding(left, top, right, bottom);
if (isLayoutRequested()) {
handleBoundsChange();
}
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
handleBoundsChange();
if (mFastScroll != null) {
mFastScroll.onSizeChanged(w, h, oldw, oldh);
}
}
/**
* Called when bounds of the AbsListView are changed. AbsListView marks data set as changed
* and force layouts all children that don't have exact measure specs.
* <p>
* This invalidation is necessary, otherwise, AbsListView may think the children are valid and
* fail to relayout them properly to accommodate for new bounds.
*/
void handleBoundsChange() {
if (mInLayout) {
return;
}
final int childCount = getChildCount();
if (childCount > 0) {
mDataChanged = true;
rememberSyncState();
for (int i = 0; i < childCount; i++) {
final View child = getChildAt(i);
final ViewGroup.LayoutParams lp = child.getLayoutParams();
// force layout child unless it has exact specs
if (lp == null || lp.width < 1 || lp.height < 1) {
child.forceLayout();
}
}
}
}
/**
* @return True if the current touch mode requires that we draw the selector in the pressed
* state.
*/
boolean touchModeDrawsInPressedState() {
// FIXME use isPressed for this
switch (mTouchMode) {
case TOUCH_MODE_TAP:
case TOUCH_MODE_DONE_WAITING:
return true;
default:
return false;
}
}
/**
* Indicates whether this view is in a state where the selector should be drawn. This will
* happen if we have focus but are not in touch mode, or we are in the middle of displaying
* the pressed state for an item.
*
* @return True if the selector should be shown
*/
boolean shouldShowSelector() {
return (isFocused() && !isInTouchMode()) || (touchModeDrawsInPressedState() && isPressed());
}
private void drawSelector(Canvas canvas) {
if (shouldDrawSelector()) {
final Drawable selector = mSelector;
selector.setBounds(mSelectorRect);
selector.draw(canvas);
}
}
/**
* @hide
*/
@TestApi
public final boolean shouldDrawSelector() {
return !mSelectorRect.isEmpty();
}
/**
* Controls whether the selection highlight drawable should be drawn on top of the item or
* behind it.
*
* @param onTop If true, the selector will be drawn on the item it is highlighting. The default
* is false.
*
* @attr ref android.R.styleable#AbsListView_drawSelectorOnTop
*/
public void setDrawSelectorOnTop(boolean onTop) {
mDrawSelectorOnTop = onTop;
}
/**
* Set a Drawable that should be used to highlight the currently selected item.
*
* @param resID A Drawable resource to use as the selection highlight.
*
* @attr ref android.R.styleable#AbsListView_listSelector
*/
public void setSelector(@DrawableRes int resID) {
setSelector(getContext().getDrawable(resID));
}
public void setSelector(Drawable sel) {
if (mSelector != null) {
mSelector.setCallback(null);
unscheduleDrawable(mSelector);
}
mSelector = sel;
Rect padding = new Rect();
sel.getPadding(padding);
mSelectionLeftPadding = padding.left;
mSelectionTopPadding = padding.top;
mSelectionRightPadding = padding.right;
mSelectionBottomPadding = padding.bottom;
sel.setCallback(this);
updateSelectorState();
}
/**
* Returns the selector {@link android.graphics.drawable.Drawable} that is used to draw the
* selection in the list.
*
* @return the drawable used to display the selector
*/
public Drawable getSelector() {