diff --git a/libs/ActionBarSherlock/AndroidManifest.xml b/libs/ActionBarSherlock/AndroidManifest.xml
index 40d50e2..e4de549 100644
--- a/libs/ActionBarSherlock/AndroidManifest.xml
+++ b/libs/ActionBarSherlock/AndroidManifest.xml
@@ -1,13 +1,6 @@
-
-
* - * @param keyCode The value in event.getKeyCode(). * @param event Description of the key event. * @return {@code true} if the event was handled. */ - public boolean dispatchKeyUp(int keyCode, KeyEvent event) { - if (DEBUG) Log.d(TAG, "[dispatchKeyUp] keyCode: " + keyCode + ", event: " + event); - - if (isReservingOverflow() && (keyCode == KeyEvent.KEYCODE_MENU)) { - if (mActionBarView.isOverflowMenuShowing()) { - mActionBarView.hideOverflowMenu(); - } else { - mActionBarView.showOverflowMenu(); - } - return true; - } + public boolean dispatchKeyEvent(KeyEvent event) { return false; } /** - * Internal method to trigger the menu creation process. + * Notify the action bar that the Activity has triggered a menu creation + * which should happen on the conclusion of {@link Activity#onCreate}. This + * will be used to gain a reference to the native menu for native and + * overflow binding as well as to indicate when compatibility create should + * occur for the first time. * - * @return {@code true} if menu creation should proceed. + * @param menu Activity native menu. + * @return {@code true} since we always want to say that we have a native */ - private boolean dispatchCreateOptionsMenu() { - if (DEBUG) Log.d(TAG, "[dispatchCreateOptionsMenu]"); - - mLastCreateResult = false; - if (mActivity instanceof OnCreatePanelMenuListener) { - OnCreatePanelMenuListener listener = (OnCreatePanelMenuListener)mActivity; - mLastCreateResult = listener.onCreatePanelMenu(Window.FEATURE_OPTIONS_PANEL, mMenu); - } - return mLastCreateResult; - } - - /** - * Internal method to trigger the menu preparation process. - * - * @return {@code true} if menu preparation should proceed. - */ - private boolean dispatchPrepareOptionsMenu() { - if (DEBUG) Log.d(TAG, "[dispatchPrepareOptionsMenu]"); - - mLastPrepareResult = false; - if (mActivity instanceof OnPreparePanelListener) { - OnPreparePanelListener listener = (OnPreparePanelListener)mActivity; - mLastPrepareResult = listener.onPreparePanel(Window.FEATURE_OPTIONS_PANEL, null, mMenu); - } - return mLastPrepareResult; - } + public abstract boolean dispatchCreateOptionsMenu(android.view.Menu menu); /** * Notify the action bar that the Activity has triggered a menu preparation @@ -581,45 +462,26 @@ public final class ActionBarSherlock { * } * * - * @param menu Activity native menu + * @param menu Activity native menu. * @return {@code true} if menu display should proceed. */ - public boolean dispatchPrepareOptionsMenu(android.view.Menu menu) { - if (DEBUG) Log.d(TAG, "[dispatchPrepareOptionsMenu] android.view.Menu: " + menu); - - if (isReservingOverflow()) { - return false; - } - - if (!dispatchPrepareOptionsMenu()) { - return false; - } - - if (mNativeItemMap == null) { - mNativeItemMap = new HashMap- * @Override - * public boolean onKeyUp(int keyCode, KeyEvent event) { - * if (mSherlock.dispatchKeyUp(keyCode, event)) { - * return true; - * } - * return super.onKeyDown(keyCode, event); - * } + * @Override + * public boolean dispatchKeyEvent(KeyEvent event) { + * if (mSherlock.dispatchKeyEvent(event)) { + * return true; + * } + * return super.dispatchKeyEvent(event); + * } *
+ * + * @param item Options menu item. + * @return @{code true} if the selection was handled. */ - private boolean dispatchOptionsItemSelected(MenuItem item) { - if (DEBUG) Log.d(TAG, "[dispatchOptionsItemSelected] item: " + item); - - if (mActivity instanceof OnMenuItemSelectedListener) { - OnMenuItemSelectedListener listener = (OnMenuItemSelectedListener)mActivity; - return listener.onMenuItemSelected(Window.FEATURE_OPTIONS_PANEL, item); - } - return false; - } + public abstract boolean dispatchOptionsItemSelected(android.view.MenuItem item); /** * Notify the action bar that the overflow menu has been opened. The @@ -642,15 +504,6 @@ public final class ActionBarSherlock { * @return {@code true} if the event was handled by this method. */ public boolean dispatchMenuOpened(int featureId, android.view.Menu menu) { - if (DEBUG) Log.d(TAG, "[dispatchMenuOpened] featureId: " + featureId + ", menu: " + menu); - - if (featureId == Window.FEATURE_ACTION_BAR || featureId == Window.FEATURE_OPTIONS_PANEL) { - if (mActionBar != null) { - mActionBar.dispatchMenuVisibilityChanged(true); - } - return true; - } - return false; } @@ -669,45 +522,90 @@ public final class ActionBarSherlock { * @param featureId * @param menu */ - public void dispatchPanelClosed(int featureId, android.view.Menu menu){ - if (DEBUG) Log.d(TAG, "[dispatchPanelClosed] featureId: " + featureId + ", menu: " + menu); + public void dispatchPanelClosed(int featureId, android.view.Menu menu) {} - if (featureId == Window.FEATURE_ACTION_BAR || featureId == Window.FEATURE_OPTIONS_PANEL) { - if (mActionBar != null) { - mActionBar.dispatchMenuVisibilityChanged(false); - } - } - } /////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////// /** - * Return the feature bits that are enabled. This is the set of features - * that were given to requestFeature(), and are being handled by this - * Window itself or its container. That is, it is the set of requested - * features that you can actually use. + * Internal method to trigger the menu creation process. * - * @return The feature bits. + * @return {@code true} if menu creation should proceed. */ - public int getFeatures() { - if (DEBUG) Log.d(TAG, "[getFeatures]"); + protected final boolean callbackCreateOptionsMenu(Menu menu) { + if (DEBUG) Log.d(TAG, "[callbackCreateOptionsMenu] menu: " + menu); - return mFeatures; + boolean result = true; + if (mActivity instanceof OnCreatePanelMenuListener) { + OnCreatePanelMenuListener listener = (OnCreatePanelMenuListener)mActivity; + result = listener.onCreatePanelMenu(Window.FEATURE_OPTIONS_PANEL, menu); + } else if (mActivity instanceof OnCreateOptionsMenuListener) { + OnCreateOptionsMenuListener listener = (OnCreateOptionsMenuListener)mActivity; + result = listener.onCreateOptionsMenu(menu); + } + + if (DEBUG) Log.d(TAG, "[callbackCreateOptionsMenu] returning " + result); + return result; } + /** + * Internal method to trigger the menu preparation process. + * + * @return {@code true} if menu preparation should proceed. + */ + protected final boolean callbackPrepareOptionsMenu(Menu menu) { + if (DEBUG) Log.d(TAG, "[callbackPrepareOptionsMenu] menu: " + menu); + + boolean result = true; + if (mActivity instanceof OnPreparePanelListener) { + OnPreparePanelListener listener = (OnPreparePanelListener)mActivity; + result = listener.onPreparePanel(Window.FEATURE_OPTIONS_PANEL, null, menu); + } else if (mActivity instanceof OnPrepareOptionsMenuListener) { + OnPrepareOptionsMenuListener listener = (OnPrepareOptionsMenuListener)mActivity; + result = listener.onPrepareOptionsMenu(menu); + } + + if (DEBUG) Log.d(TAG, "[callbackPrepareOptionsMenu] returning " + result); + return result; + } + + /** + * Internal method for dispatching options menu selection to the owning + * activity callback. + * + * @param item Selected options menu item. + * @return {@code true} if the item selection was handled in the callback. + */ + protected final boolean callbackOptionsItemSelected(MenuItem item) { + if (DEBUG) Log.d(TAG, "[callbackOptionsItemSelected] item: " + item.getTitleCondensed()); + + boolean result = false; + if (mActivity instanceof OnMenuItemSelectedListener) { + OnMenuItemSelectedListener listener = (OnMenuItemSelectedListener)mActivity; + result = listener.onMenuItemSelected(Window.FEATURE_OPTIONS_PANEL, item); + } else if (mActivity instanceof OnOptionsItemSelectedListener) { + OnOptionsItemSelectedListener listener = (OnOptionsItemSelectedListener)mActivity; + result = listener.onOptionsItemSelected(item); + } + + if (DEBUG) Log.d(TAG, "[callbackOptionsItemSelected] returning " + result); + return result; + } + + + /////////////////////////////////////////////////////////////////////////// + /////////////////////////////////////////////////////////////////////////// + + /** * Query for the availability of a certain feature. * * @param featureId The feature ID to check. * @return {@code true} if feature is enabled, {@code false} otherwise. */ - public boolean hasFeature(int featureId) { - if (DEBUG) Log.d(TAG, "[hasFeature] featureId: " + featureId); - - return (mFeatures & (1 << featureId)) != 0; - } + public abstract boolean hasFeature(int featureId); /** * Enable extended screen features. This must be called before @@ -720,38 +618,14 @@ public final class ActionBarSherlock { * @return Returns true if the requested feature is supported and now * enabled. */ - public boolean requestFeature(int featureId) { - if (DEBUG) Log.d(TAG, "[requestFeature] featureId: " + featureId); - - if (mContentParent != null) { - throw new AndroidRuntimeException("requestFeature() must be called before adding content"); - } - - switch (featureId) { - case Window.FEATURE_ACTION_BAR: - case Window.FEATURE_ACTION_BAR_OVERLAY: - case Window.FEATURE_ACTION_MODE_OVERLAY: - case Window.FEATURE_INDETERMINATE_PROGRESS: - case Window.FEATURE_NO_TITLE: - case Window.FEATURE_PROGRESS: - mFeatures |= (1 << featureId); - return true; - - default: - return false; - } - } + public abstract boolean requestFeature(int featureId); /** * Set extra options that will influence the UI for this window. * * @param uiOptions Flags specifying extra options for this window. */ - public void setUiOptions(int uiOptions) { - if (DEBUG) Log.d(TAG, "[setUiOptions] uiOptions: " + uiOptions); - - mUiOptions = uiOptions; - } + public abstract void setUiOptions(int uiOptions); /** * Set extra options that will influence the UI for this window. Only the @@ -761,34 +635,14 @@ public final class ActionBarSherlock { * @param mask Flags specifying which options should be modified. Others * will remain unchanged. */ - public void setUiOptions(int uiOptions, int mask) { - if (DEBUG) Log.d(TAG, "[setUiOptions] uiOptions: " + uiOptions + ", mask: " + mask); - - mUiOptions = (mUiOptions & ~mask) | (uiOptions & mask); - } + public abstract void setUiOptions(int uiOptions, int mask); /** * Set the content of the activity inside the action bar. * * @param layoutResId Layout resource ID. */ - public void setContentView(int layoutResId) { - if (DEBUG) Log.d(TAG, "[setContentView] layoutResId: " + layoutResId); - - if (mContentParent == null) { - installDecor(); - } else { - mContentParent.removeAllViews(); - } - mActivity.getLayoutInflater().inflate(layoutResId, mContentParent); - - android.view.Window.Callback callback = mActivity.getWindow().getCallback(); - if (callback != null) { - callback.onContentChanged(); - } - - initActionBar(); - } + public abstract void setContentView(int layoutResId); /** * Set the content of the activity inside the action bar. @@ -807,23 +661,7 @@ public final class ActionBarSherlock { * @param view The desired content to display. * @param params Layout parameters to apply to the view. */ - public void setContentView(View view, ViewGroup.LayoutParams params) { - if (DEBUG) Log.d(TAG, "[setContentView] view: " + view + ", params: " + params); - - if (mContentParent == null) { - installDecor(); - } else { - mContentParent.removeAllViews(); - } - mContentParent.addView(view, params); - - android.view.Window.Callback callback = mActivity.getWindow().getCallback(); - if (callback != null) { - callback.onContentChanged(); - } - - initActionBar(); - } + public abstract void setContentView(View view, ViewGroup.LayoutParams params); /** * Variation on {@link #setContentView(android.view.View, android.view.ViewGroup.LayoutParams)} @@ -833,221 +671,12 @@ public final class ActionBarSherlock { * @param view The desired content to display. * @param params Layout parameters for the view. */ - public void addContentView(View view, ViewGroup.LayoutParams params) { - if (DEBUG) Log.d(TAG, "[addContentView] view: " + view + ", params: " + params); - - if (mContentParent == null) { - installDecor(); - } - mContentParent.addView(view, params); - - initActionBar(); - } - - private void installDecor() { - if (DEBUG) Log.d(TAG, "[installDecor]"); - - if (mDecor == null) { - mDecor = (ViewGroup)mActivity.getWindow().getDecorView().findViewById(android.R.id.content); - } - if (mContentParent == null) { - mContentParent = generateLayout(); - mActionBarView = (ActionBarView)mDecor.findViewById(R.id.abs__action_bar); - if (mActionBarView != null) { - mActionBarView.setWindowCallback(mWindowCallback); - if (mActionBarView.getTitle() == null) { - mActionBarView.setWindowTitle(mActivity.getTitle()); - } - if (hasFeature(Window.FEATURE_PROGRESS)) { - mActionBarView.initProgress(); - } - if (hasFeature(Window.FEATURE_INDETERMINATE_PROGRESS)) { - mActionBarView.initIndeterminateProgress(); - } - - //Since we don't require onCreate dispatching, parse for uiOptions here - mUiOptions = loadUiOptionsFromManifest(mActivity); - - boolean splitActionBar = false; - final boolean splitWhenNarrow = (mUiOptions & ActivityInfo.UIOPTION_SPLIT_ACTION_BAR_WHEN_NARROW) != 0; - if (splitWhenNarrow) { - splitActionBar = mActivity.getResources().getBoolean(R.bool.abs__split_action_bar_is_narrow); - } else { - splitActionBar = mActivity.getTheme() - .obtainStyledAttributes(R.styleable.SherlockTheme) - .getBoolean(R.styleable.SherlockTheme_windowSplitActionBar, false); - } - final ActionBarContainer splitView = (ActionBarContainer)mDecor.findViewById(R.id.abs__split_action_bar); - if (splitView != null) { - mActionBarView.setSplitView(splitView); - mActionBarView.setSplitActionBar(splitActionBar); - mActionBarView.setSplitWhenNarrow(splitWhenNarrow); - - mActionModeView = (ActionBarContextView)mDecor.findViewById(R.id.abs__action_context_bar); - mActionModeView.setSplitView(splitView); - mActionModeView.setSplitActionBar(splitActionBar); - mActionModeView.setSplitWhenNarrow(splitWhenNarrow); - } else if (splitActionBar) { - Log.e(TAG, "Requested split action bar with incompatible window decor! Ignoring request."); - } - - // Post the panel invalidate for later; avoid application onCreateOptionsMenu - // being called in the middle of onCreate or similar. - mDecor.post(new Runnable() { - @Override - public void run() { - //Invalidate if the panel menu hasn't been created before this. - if (mMenu == null) { - dispatchInvalidateOptionsMenu(); - } - } - }); - } - } - } - - private static int loadUiOptionsFromManifest(Activity activity) { - int uiOptions = 0; - try { - final String thisPackage = activity.getClass().getName(); - if (DEBUG) Log.i(TAG, "Parsing AndroidManifest.xml for " + thisPackage); - - final String packageName = activity.getApplicationInfo().packageName; - final AssetManager am = activity.createPackageContext(packageName, 0).getAssets(); - final XmlResourceParser xml = am.openXmlResourceParser("AndroidManifest.xml"); - - int eventType = xml.getEventType(); - while (eventType != XmlPullParser.END_DOCUMENT) { - if (eventType == XmlPullParser.START_TAG) { - String name = xml.getName(); - - if ("application".equals(name)) { - //Check if the+ * @Override + * public final boolean onOptionsItemSelected(android.view.MenuItem item) { + * return mSherlock.dispatchOptionsItemSelected(item); + * } + *
Note that canceling a AnimatorSet
also cancels all of the animations that it
* is responsible for.
+ * See {@link ListView}, {@link GridView}, {@link Spinner} and + * {@link Gallery} for commonly used subclasses of AdapterView. + * + *
For more information about using AdapterView, read the + * Binding to Data with AdapterView + * developer guide.
Callback method to be invoked when an item in this view has been + * selected. This callback is invoked only when the newly selected + * position is different from the previously selected position or if + * there was no selected item.
+ * + * Impelmenters can call getItemAtPosition(position) if they need to access the + * data associated with the selected item. + * + * @param parent The AdapterView where the selection happened + * @param view The view within the AdapterView that was clicked + * @param position The position of the view in the adapter + * @param id The row id of the item that is selected + */ + void onItemSelected(IcsAdapterView> parent, View view, int position, long id); + + /** + * Callback method to be invoked when the selection disappears from this + * view. The selection can disappear for instance when touch is activated + * or when the adapter becomes empty. + * + * @param parent The AdapterView that now contains no selected item. + */ + void onNothingSelected(IcsAdapterView> parent); + } + + + /** + * Register a callback to be invoked when an item in this AdapterView has + * been selected. + * + * @param listener The callback that will run + */ + public void setOnItemSelectedListener(OnItemSelectedListener listener) { + mOnItemSelectedListener = listener; + } + + public final OnItemSelectedListener getOnItemSelectedListener() { + return mOnItemSelectedListener; + } + + /** + * Extra menu information provided to the + * {@link android.view.View.OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo) } + * callback when a context menu is brought up for this AdapterView. + * + */ + public static class AdapterContextMenuInfo implements ContextMenu.ContextMenuInfo { + + public AdapterContextMenuInfo(View targetView, int position, long id) { + this.targetView = targetView; + this.position = position; + this.id = id; + } + + /** + * The child view for which the context menu is being displayed. This + * will be one of the children of this AdapterView. + */ + public View targetView; + + /** + * The position in the adapter for which the context menu is being + * displayed. + */ + public int position; + + /** + * The row id of the item for which the context menu is being displayed. + */ + public long id; + } + + /** + * Returns the adapter currently associated with this widget. + * + * @return The adapter used to provide this view's content. + */ + public abstract T getAdapter(); + + /** + * Sets the adapter that provides the data and the views to represent the data + * in this widget. + * + * @param adapter The adapter to use to create this view's content. + */ + public abstract void setAdapter(T adapter); + + /** + * This method is not supported and throws an UnsupportedOperationException when called. + * + * @param child Ignored. + * + * @throws UnsupportedOperationException Every time this method is invoked. + */ + @Override + public void addView(View child) { + throw new UnsupportedOperationException("addView(View) is not supported in AdapterView"); + } + + /** + * This method is not supported and throws an UnsupportedOperationException when called. + * + * @param child Ignored. + * @param index Ignored. + * + * @throws UnsupportedOperationException Every time this method is invoked. + */ + @Override + public void addView(View child, int index) { + throw new UnsupportedOperationException("addView(View, int) is not supported in AdapterView"); + } + + /** + * This method is not supported and throws an UnsupportedOperationException when called. + * + * @param child Ignored. + * @param params Ignored. + * + * @throws UnsupportedOperationException Every time this method is invoked. + */ + @Override + public void addView(View child, LayoutParams params) { + throw new UnsupportedOperationException("addView(View, LayoutParams) " + + "is not supported in AdapterView"); + } + + /** + * This method is not supported and throws an UnsupportedOperationException when called. + * + * @param child Ignored. + * @param index Ignored. + * @param params Ignored. + * + * @throws UnsupportedOperationException Every time this method is invoked. + */ + @Override + public void addView(View child, int index, LayoutParams params) { + throw new UnsupportedOperationException("addView(View, int, LayoutParams) " + + "is not supported in AdapterView"); + } + + /** + * This method is not supported and throws an UnsupportedOperationException when called. + * + * @param child Ignored. + * + * @throws UnsupportedOperationException Every time this method is invoked. + */ + @Override + public void removeView(View child) { + throw new UnsupportedOperationException("removeView(View) is not supported in AdapterView"); + } + + /** + * This method is not supported and throws an UnsupportedOperationException when called. + * + * @param index Ignored. + * + * @throws UnsupportedOperationException Every time this method is invoked. + */ + @Override + public void removeViewAt(int index) { + throw new UnsupportedOperationException("removeViewAt(int) is not supported in AdapterView"); + } + + /** + * This method is not supported and throws an UnsupportedOperationException when called. + * + * @throws UnsupportedOperationException Every time this method is invoked. + */ + @Override + public void removeAllViews() { + throw new UnsupportedOperationException("removeAllViews() is not supported in AdapterView"); + } + + @Override + protected void onLayout(boolean changed, int left, int top, int right, int bottom) { + mLayoutHeight = getHeight(); + } + + /** + * Return the position of the currently selected item within the adapter's data set + * + * @return int Position (starting at 0), or {@link #INVALID_POSITION} if there is nothing selected. + */ + @ViewDebug.CapturedViewProperty + public int getSelectedItemPosition() { + return mNextSelectedPosition; + } + + /** + * @return The id corresponding to the currently selected item, or {@link #INVALID_ROW_ID} + * if nothing is selected. + */ + @ViewDebug.CapturedViewProperty + public long getSelectedItemId() { + return mNextSelectedRowId; + } + + /** + * @return The view corresponding to the currently selected item, or null + * if nothing is selected + */ + public abstract View getSelectedView(); + + /** + * @return The data corresponding to the currently selected item, or + * null if there is nothing selected. + */ + public Object getSelectedItem() { + T adapter = getAdapter(); + int selection = getSelectedItemPosition(); + if (adapter != null && adapter.getCount() > 0 && selection >= 0) { + return adapter.getItem(selection); + } else { + return null; + } + } + + /** + * @return The number of items owned by the Adapter associated with this + * AdapterView. (This is the number of data items, which may be + * larger than the number of visible views.) + */ + @ViewDebug.CapturedViewProperty + public int getCount() { + return mItemCount; + } + + /** + * Get the position within the adapter's data set for the view, where view is a an adapter item + * or a descendant of an adapter item. + * + * @param view an adapter item, or a descendant of an adapter item. This must be visible in this + * AdapterView at the time of the call. + * @return the position within the adapter's data set of the view, or {@link #INVALID_POSITION} + * if the view does not correspond to a list item (or it is not currently visible). + */ + public int getPositionForView(View view) { + View listItem = view; + try { + View v; + while (!(v = (View) listItem.getParent()).equals(this)) { + listItem = v; + } + } catch (ClassCastException e) { + // We made it up to the window without find this list view + return INVALID_POSITION; + } + + // Search the children for the list item + final int childCount = getChildCount(); + for (int i = 0; i < childCount; i++) { + if (getChildAt(i).equals(listItem)) { + return mFirstPosition + i; + } + } + + // Child not found! + return INVALID_POSITION; + } + + /** + * Returns the position within the adapter's data set for the first item + * displayed on screen. + * + * @return The position within the adapter's data set + */ + public int getFirstVisiblePosition() { + return mFirstPosition; + } + + /** + * Returns the position within the adapter's data set for the last item + * displayed on screen. + * + * @return The position within the adapter's data set + */ + public int getLastVisiblePosition() { + return mFirstPosition + getChildCount() - 1; + } + + /** + * Sets the currently selected item. To support accessibility subclasses that + * override this method must invoke the overriden super method first. + * + * @param position Index (starting at 0) of the data item to be selected. + */ + public abstract void setSelection(int position); + + /** + * Sets the view to show if the adapter is empty + */ + public void setEmptyView(View emptyView) { + mEmptyView = emptyView; + + final T adapter = getAdapter(); + final boolean empty = ((adapter == null) || adapter.isEmpty()); + updateEmptyStatus(empty); + } + + /** + * When the current adapter is empty, the AdapterView can display a special view + * call the empty view. The empty view is used to provide feedback to the user + * that no data is available in this AdapterView. + * + * @return The view to show if the adapter is empty. + */ + public View getEmptyView() { + return mEmptyView; + } + + /** + * Indicates whether this view is in filter mode. Filter mode can for instance + * be enabled by a user when typing on the keyboard. + * + * @return True if the view is in filter mode, false otherwise. + */ + boolean isInFilterMode() { + return false; + } + + @Override + public void setFocusable(boolean focusable) { + final T adapter = getAdapter(); + final boolean empty = adapter == null || adapter.getCount() == 0; + + mDesiredFocusableState = focusable; + if (!focusable) { + mDesiredFocusableInTouchModeState = false; + } + + super.setFocusable(focusable && (!empty || isInFilterMode())); + } + + @Override + public void setFocusableInTouchMode(boolean focusable) { + final T adapter = getAdapter(); + final boolean empty = adapter == null || adapter.getCount() == 0; + + mDesiredFocusableInTouchModeState = focusable; + if (focusable) { + mDesiredFocusableState = true; + } + + super.setFocusableInTouchMode(focusable && (!empty || isInFilterMode())); + } + + void checkFocus() { + final T adapter = getAdapter(); + final boolean empty = adapter == null || adapter.getCount() == 0; + final boolean focusable = !empty || isInFilterMode(); + // The order in which we set focusable in touch mode/focusable may matter + // for the client, see View.setFocusableInTouchMode() comments for more + // details + super.setFocusableInTouchMode(focusable && mDesiredFocusableInTouchModeState); + super.setFocusable(focusable && mDesiredFocusableState); + if (mEmptyView != null) { + updateEmptyStatus((adapter == null) || adapter.isEmpty()); + } + } + + /** + * Update the status of the list based on the empty parameter. If empty is true and + * we have an empty view, display it. In all the other cases, make sure that the listview + * is VISIBLE and that the empty view is GONE (if it's not null). + */ + private void updateEmptyStatus(boolean empty) { + if (isInFilterMode()) { + empty = false; + } + + if (empty) { + if (mEmptyView != null) { + mEmptyView.setVisibility(View.VISIBLE); + setVisibility(View.GONE); + } else { + // If the caller just removed our empty view, make sure the list view is visible + setVisibility(View.VISIBLE); + } + + // We are now GONE, so pending layouts will not be dispatched. + // Force one here to make sure that the state of the list matches + // the state of the adapter. + if (mDataChanged) { + this.onLayout(false, getLeft(), getTop(), getRight(), getBottom()); + } + } else { + if (mEmptyView != null) mEmptyView.setVisibility(View.GONE); + setVisibility(View.VISIBLE); + } + } + + /** + * Gets the data associated with the specified position in the list. + * + * @param position Which data to get + * @return The data associated with the specified position in the list + */ + public Object getItemAtPosition(int position) { + T adapter = getAdapter(); + return (adapter == null || position < 0) ? null : adapter.getItem(position); + } + + public long getItemIdAtPosition(int position) { + T adapter = getAdapter(); + return (adapter == null || position < 0) ? INVALID_ROW_ID : adapter.getItemId(position); + } + + @Override + public void setOnClickListener(OnClickListener l) { + throw new RuntimeException("Don't call setOnClickListener for an AdapterView. " + + "You probably want setOnItemClickListener instead"); + } + + /** + * Override to prevent freezing of any views created by the adapter. + */ + @Override + protected void dispatchSaveInstanceState(SparseArrayDefines whether widgets contained in this layout are - * baseline-aligned or not.
- * - * @param baselineAligned true to align widgets on their baseline, - * false otherwise - * - * @attr ref android.R.styleable#LinearLayout_baselineAligned - */ - public void setBaselineAligned(boolean baselineAligned) { - mBaselineAligned = baselineAligned; - } - - @Override - public int getBaseline() { - if (mBaselineAlignedChildIndex < 0) { - return super.getBaseline(); - } - - if (getChildCount() <= mBaselineAlignedChildIndex) { - throw new RuntimeException("mBaselineAlignedChildIndex of LinearLayout " - + "set to an index that is out of bounds."); - } - - final View child = getChildAt(mBaselineAlignedChildIndex); - final int childBaseline = child.getBaseline(); - - if (childBaseline == -1) { - if (mBaselineAlignedChildIndex == 0) { - // this is just the default case, safe to return -1 - return -1; - } - // the user picked an index that points to something that doesn't - // know how to calculate its baseline. - throw new RuntimeException("mBaselineAlignedChildIndex of LinearLayout " - + "points to a View that doesn't know how to get its baseline."); - } - - // TODO: This should try to take into account the virtual offsets - // (See getNextLocationOffset and getLocationOffset) - // We should add to childTop: - // sum([getNextLocationOffset(getChildAt(i)) / i < mBaselineAlignedChildIndex]) - // and also add: - // getLocationOffset(child) - int childTop = mBaselineChildTop; - - IcsLinearLayout.LayoutParams lp = (IcsLinearLayout.LayoutParams) child.getLayoutParams(); - return childTop + lp.topMargin + childBaseline; - } - - /** - *Returns the view at the specified index. This method can be overriden - * to take into account virtual children. Refer to - * {@link android.widget.TableLayout} and {@link android.widget.TableRow} - * for an example.
- * - * @param index the child's index - * @return the child at the specified index - */ - View getVirtualChildAt(int index) { - return getChildAt(index); - } - - /** - *Returns the virtual number of children. This number might be different - * than the actual number of children if the layout can hold virtual - * children. Refer to - * {@link android.widget.TableLayout} and {@link android.widget.TableRow} - * for an example.
- * - * @return the virtual number of children - */ - int getVirtualChildCount() { - return getChildCount(); - } - /** * Determines where to position dividers between children. * @@ -324,707 +245,4 @@ public class IcsLinearLayout extends NineViewGroup { } return false; } - - @Override - protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { - mTotalLength = 0; - int maxHeight = 0; - int childState = 0; - int alternativeMaxHeight = 0; - int weightedMaxHeight = 0; - boolean allFillParent = true; - float totalWeight = 0; - - final int count = getVirtualChildCount(); - - final int widthMode = MeasureSpec.getMode(widthMeasureSpec); - final int heightMode = MeasureSpec.getMode(heightMeasureSpec); - - boolean matchHeight = false; - - if (mMaxAscent == null || mMaxDescent == null) { - mMaxAscent = new int[VERTICAL_GRAVITY_COUNT]; - mMaxDescent = new int[VERTICAL_GRAVITY_COUNT]; - } - - final int[] maxAscent = mMaxAscent; - final int[] maxDescent = mMaxDescent; - - maxAscent[0] = maxAscent[1] = maxAscent[2] = maxAscent[3] = -1; - maxDescent[0] = maxDescent[1] = maxDescent[2] = maxDescent[3] = -1; - - final boolean baselineAligned = mBaselineAligned; - final boolean useLargestChild = mUseLargestChild; - - final boolean isExactly = widthMode == MeasureSpec.EXACTLY; - - int largestChildWidth = Integer.MIN_VALUE; - - // See how wide everyone is. Also remember max height. - for (int i = 0; i < count; ++i) { - final View child = getVirtualChildAt(i); - - if (child == null) { - mTotalLength += measureNullChild(i); - continue; - } - - if (child.getVisibility() == GONE) { - i += getChildrenSkipCount(child, i); - continue; - } - - if (hasDividerBeforeChildAt(i)) { - mTotalLength += mDividerWidth; - } - - final IcsLinearLayout.LayoutParams lp = (IcsLinearLayout.LayoutParams) - child.getLayoutParams(); - - totalWeight += lp.weight; - - if (widthMode == MeasureSpec.EXACTLY && lp.width == 0 && lp.weight > 0) { - // Optimization: don't bother measuring children who are going to use - // leftover space. These views will get measured again down below if - // there is any leftover space. - if (isExactly) { - mTotalLength += lp.leftMargin + lp.rightMargin; - } else { - final int totalLength = mTotalLength; - mTotalLength = Math.max(totalLength, totalLength + - lp.leftMargin + lp.rightMargin); - } - - // Baseline alignment requires to measure widgets to obtain the - // baseline offset (in particular for TextViews). The following - // defeats the optimization mentioned above. Allow the child to - // use as much space as it wants because we can shrink things - // later (and re-measure). - if (baselineAligned) { - final int freeSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED); - child.measure(freeSpec, freeSpec); - } - } else { - int oldWidth = Integer.MIN_VALUE; - - if (lp.width == 0 && lp.weight > 0) { - // widthMode is either UNSPECIFIED or AT_MOST, and this - // child - // wanted to stretch to fill available space. Translate that to - // WRAP_CONTENT so that it does not end up with a width of 0 - oldWidth = 0; - lp.width = LayoutParams.WRAP_CONTENT; - } - - // Determine how big this child would like to be. If this or - // previous children have given a weight, then we allow it to - // use all available space (and we will shrink things later - // if needed). - measureChildBeforeLayout(child, i, widthMeasureSpec, - totalWeight == 0 ? mTotalLength : 0, - heightMeasureSpec, 0); - - if (oldWidth != Integer.MIN_VALUE) { - lp.width = oldWidth; - } - - final int childWidth = child.getMeasuredWidth(); - if (isExactly) { - mTotalLength += childWidth + lp.leftMargin + lp.rightMargin + - getNextLocationOffset(child); - } else { - final int totalLength = mTotalLength; - mTotalLength = Math.max(totalLength, totalLength + childWidth + lp.leftMargin + - lp.rightMargin + getNextLocationOffset(child)); - } - - if (useLargestChild) { - largestChildWidth = Math.max(childWidth, largestChildWidth); - } - } - - boolean matchHeightLocally = false; - if (heightMode != MeasureSpec.EXACTLY && lp.height == LayoutParams.MATCH_PARENT) { - // The height of the linear layout will scale, and at least one - // child said it wanted to match our height. Set a flag indicating that - // we need to remeasure at least that view when we know our height. - matchHeight = true; - matchHeightLocally = true; - } - - final int margin = lp.topMargin + lp.bottomMargin; - final int childHeight = child.getMeasuredHeight() + margin; - childState = combineMeasuredStatesInt(childState, IcsView.getMeasuredStateInt(child)); - - if (baselineAligned) { - final int childBaseline = child.getBaseline(); - if (childBaseline != -1) { - // Translates the child's vertical gravity into an index - // in the range 0..VERTICAL_GRAVITY_COUNT - final int gravity = (lp.gravity < 0 ? mGravity : lp.gravity) - & Gravity.VERTICAL_GRAVITY_MASK; - final int index = ((gravity >> Gravity.AXIS_Y_SHIFT) - & ~Gravity.AXIS_SPECIFIED) >> 1; - - maxAscent[index] = Math.max(maxAscent[index], childBaseline); - maxDescent[index] = Math.max(maxDescent[index], childHeight - childBaseline); - } - } - - maxHeight = Math.max(maxHeight, childHeight); - - allFillParent = allFillParent && lp.height == LayoutParams.MATCH_PARENT; - if (lp.weight > 0) { - /* - * Heights of weighted Views are bogus if we end up - * remeasuring, so keep them separate. - */ - weightedMaxHeight = Math.max(weightedMaxHeight, - matchHeightLocally ? margin : childHeight); - } else { - alternativeMaxHeight = Math.max(alternativeMaxHeight, - matchHeightLocally ? margin : childHeight); - } - - i += getChildrenSkipCount(child, i); - } - - if (mTotalLength > 0 && hasDividerBeforeChildAt(count)) { - mTotalLength += mDividerWidth; - } - - // Check mMaxAscent[INDEX_TOP] first because it maps to Gravity.TOP, - // the most common case - if (maxAscent[INDEX_TOP] != -1 || - maxAscent[INDEX_CENTER_VERTICAL] != -1 || - maxAscent[INDEX_BOTTOM] != -1 || - maxAscent[INDEX_FILL] != -1) { - final int ascent = Math.max(maxAscent[INDEX_FILL], - Math.max(maxAscent[INDEX_CENTER_VERTICAL], - Math.max(maxAscent[INDEX_TOP], maxAscent[INDEX_BOTTOM]))); - final int descent = Math.max(maxDescent[INDEX_FILL], - Math.max(maxDescent[INDEX_CENTER_VERTICAL], - Math.max(maxDescent[INDEX_TOP], maxDescent[INDEX_BOTTOM]))); - maxHeight = Math.max(maxHeight, ascent + descent); - } - - if (useLargestChild && - (widthMode == MeasureSpec.AT_MOST || widthMode == MeasureSpec.UNSPECIFIED)) { - mTotalLength = 0; - - for (int i = 0; i < count; ++i) { - final View child = getVirtualChildAt(i); - - if (child == null) { - mTotalLength += measureNullChild(i); - continue; - } - - if (child.getVisibility() == GONE) { - i += getChildrenSkipCount(child, i); - continue; - } - - final IcsLinearLayout.LayoutParams lp = (IcsLinearLayout.LayoutParams) - child.getLayoutParams(); - if (isExactly) { - mTotalLength += largestChildWidth + lp.leftMargin + lp.rightMargin + - getNextLocationOffset(child); - } else { - final int totalLength = mTotalLength; - mTotalLength = Math.max(totalLength, totalLength + largestChildWidth + - lp.leftMargin + lp.rightMargin + getNextLocationOffset(child)); - } - } - } - - // Add in our padding - mTotalLength += getPaddingLeft() + getPaddingRight(); - - int widthSize = mTotalLength; - - // Check against our minimum width - widthSize = Math.max(widthSize, getSuggestedMinimumWidth()); - - // Reconcile our calculated size with the widthMeasureSpec - int widthSizeAndState = IcsView.resolveSizeAndState(widthSize, widthMeasureSpec, 0); - widthSize = widthSizeAndState & MEASURED_SIZE_MASK; - - // Either expand children with weight to take up available space or - // shrink them if they extend beyond our current bounds - int delta = widthSize - mTotalLength; - if (delta != 0 && totalWeight > 0.0f) { - float weightSum = mWeightSum > 0.0f ? mWeightSum : totalWeight; - - maxAscent[0] = maxAscent[1] = maxAscent[2] = maxAscent[3] = -1; - maxDescent[0] = maxDescent[1] = maxDescent[2] = maxDescent[3] = -1; - maxHeight = -1; - - mTotalLength = 0; - - for (int i = 0; i < count; ++i) { - final View child = getVirtualChildAt(i); - - if (child == null || child.getVisibility() == View.GONE) { - continue; - } - - final IcsLinearLayout.LayoutParams lp = - (IcsLinearLayout.LayoutParams) child.getLayoutParams(); - - float childExtra = lp.weight; - if (childExtra > 0) { - // Child said it could absorb extra space -- give him his share - int share = (int) (childExtra * delta / weightSum); - weightSum -= childExtra; - delta -= share; - - final int childHeightMeasureSpec = getChildMeasureSpec( - heightMeasureSpec, - getPaddingTop() + getPaddingBottom() + lp.topMargin + lp.bottomMargin, - lp.height); - - // TODO: Use a field like lp.isMeasured to figure out if this - // child has been previously measured - if ((lp.width != 0) || (widthMode != MeasureSpec.EXACTLY)) { - // child was measured once already above ... base new measurement - // on stored values - int childWidth = child.getMeasuredWidth() + share; - if (childWidth < 0) { - childWidth = 0; - } - - child.measure( - MeasureSpec.makeMeasureSpec(childWidth, MeasureSpec.EXACTLY), - childHeightMeasureSpec); - } else { - // child was skipped in the loop above. Measure for this first time here - child.measure(MeasureSpec.makeMeasureSpec( - share > 0 ? share : 0, MeasureSpec.EXACTLY), - childHeightMeasureSpec); - } - - // Child may now not fit in horizontal dimension. - childState = combineMeasuredStatesInt(childState, - IcsView.getMeasuredStateInt(child) & MEASURED_STATE_MASK); - } - - if (isExactly) { - mTotalLength += child.getMeasuredWidth() + lp.leftMargin + lp.rightMargin + - getNextLocationOffset(child); - } else { - final int totalLength = mTotalLength; - mTotalLength = Math.max(totalLength, totalLength + child.getMeasuredWidth() + - lp.leftMargin + lp.rightMargin + getNextLocationOffset(child)); - } - - boolean matchHeightLocally = heightMode != MeasureSpec.EXACTLY && - lp.height == LayoutParams.MATCH_PARENT; - - final int margin = lp.topMargin + lp .bottomMargin; - int childHeight = child.getMeasuredHeight() + margin; - maxHeight = Math.max(maxHeight, childHeight); - alternativeMaxHeight = Math.max(alternativeMaxHeight, - matchHeightLocally ? margin : childHeight); - - allFillParent = allFillParent && lp.height == LayoutParams.MATCH_PARENT; - - if (baselineAligned) { - final int childBaseline = child.getBaseline(); - if (childBaseline != -1) { - // Translates the child's vertical gravity into an index in the range 0..2 - final int gravity = (lp.gravity < 0 ? mGravity : lp.gravity) - & Gravity.VERTICAL_GRAVITY_MASK; - final int index = ((gravity >> Gravity.AXIS_Y_SHIFT) - & ~Gravity.AXIS_SPECIFIED) >> 1; - - maxAscent[index] = Math.max(maxAscent[index], childBaseline); - maxDescent[index] = Math.max(maxDescent[index], - childHeight - childBaseline); - } - } - } - - // Add in our padding - mTotalLength += getPaddingLeft() + getPaddingRight(); - // TODO: Should we update widthSize with the new total length? - - // Check mMaxAscent[INDEX_TOP] first because it maps to Gravity.TOP, - // the most common case - if (maxAscent[INDEX_TOP] != -1 || - maxAscent[INDEX_CENTER_VERTICAL] != -1 || - maxAscent[INDEX_BOTTOM] != -1 || - maxAscent[INDEX_FILL] != -1) { - final int ascent = Math.max(maxAscent[INDEX_FILL], - Math.max(maxAscent[INDEX_CENTER_VERTICAL], - Math.max(maxAscent[INDEX_TOP], maxAscent[INDEX_BOTTOM]))); - final int descent = Math.max(maxDescent[INDEX_FILL], - Math.max(maxDescent[INDEX_CENTER_VERTICAL], - Math.max(maxDescent[INDEX_TOP], maxDescent[INDEX_BOTTOM]))); - maxHeight = Math.max(maxHeight, ascent + descent); - } - } else { - alternativeMaxHeight = Math.max(alternativeMaxHeight, weightedMaxHeight); - - // We have no limit, so make all weighted views as wide as the largest child. - // Children will have already been measured once. - if (useLargestChild && widthMode == MeasureSpec.UNSPECIFIED) { - for (int i = 0; i < count; i++) { - final View child = getVirtualChildAt(i); - - if (child == null || child.getVisibility() == View.GONE) { - continue; - } - - final IcsLinearLayout.LayoutParams lp = - (IcsLinearLayout.LayoutParams) child.getLayoutParams(); - - float childExtra = lp.weight; - if (childExtra > 0) { - child.measure( - MeasureSpec.makeMeasureSpec(largestChildWidth, MeasureSpec.EXACTLY), - MeasureSpec.makeMeasureSpec(child.getMeasuredHeight(), - MeasureSpec.EXACTLY)); - } - } - } - } - - if (!allFillParent && heightMode != MeasureSpec.EXACTLY) { - maxHeight = alternativeMaxHeight; - } - - maxHeight += getPaddingTop() + getPaddingBottom(); - - // Check against our minimum height - maxHeight = Math.max(maxHeight, getSuggestedMinimumHeight()); - - setMeasuredDimension(widthSizeAndState | (childState&MEASURED_STATE_MASK), - IcsView.resolveSizeAndState(maxHeight, heightMeasureSpec, - (childState<Returns the size (width or height) that should be occupied by a null - * child.
- * - * @param childIndex the index of the null child - * @return the width or height of the child depending on the orientation - */ - int measureNullChild(int childIndex) { - return 0; - } - - /** - *Measure the child according to the parent's measure specs. This - * method should be overriden by subclasses to force the sizing of - * children. This method is called by {@link #measureVertical(int, int)} and - * {@link #measureHorizontal(int, int)}.
- * - * @param child the child to measure - * @param childIndex the index of the child in this view - * @param widthMeasureSpec horizontal space requirements as imposed by the parent - * @param totalWidth extra space that has been used up by the parent horizontally - * @param heightMeasureSpec vertical space requirements as imposed by the parent - * @param totalHeight extra space that has been used up by the parent vertically - */ - void measureChildBeforeLayout(View child, int childIndex, - int widthMeasureSpec, int totalWidth, int heightMeasureSpec, - int totalHeight) { - measureChildWithMargins(child, widthMeasureSpec, totalWidth, - heightMeasureSpec, totalHeight); - } - - /** - *Return the location offset of the specified child. This can be used - * by subclasses to change the location of a given widget.
- * - * @param child the child for which to obtain the location offset - * @return the location offset in pixels - */ - int getLocationOffset(View child) { - return 0; - } - - /** - *Return the size offset of the next sibling of the specified child.
- * This can be used by subclasses to change the location of the widget
- * following child
.
See the Spinner + * tutorial.
+ * + * @attr ref android.R.styleable#Spinner_prompt + */ +public class IcsSpinner extends IcsAbsSpinner implements OnClickListener { + //private static final String TAG = "Spinner"; + + // Only measure this many items to get a decent max width. + private static final int MAX_ITEMS_MEASURED = 15; + + /** + * Use a dialog window for selecting spinner options. + */ + //public static final int MODE_DIALOG = 0; + + /** + * Use a dropdown anchored to the Spinner for selecting spinner options. + */ + public static final int MODE_DROPDOWN = 1; + + /** + * Use the theme-supplied value to select the dropdown mode. + */ + //private static final int MODE_THEME = -1; + + private SpinnerPopup mPopup; + private DropDownAdapter mTempAdapter; + int mDropDownWidth; + + private int mGravity; + private boolean mDisableChildrenWhenDisabled; + + private Rect mTempRect = new Rect(); + + /** + * Construct a new spinner with the given context's theme, the supplied attribute set, + * and default style. + * + * @param context The Context the view is running in, through which it can + * access the current theme, resources, etc. + * @param attrs The attributes of the XML tag that is inflating the view. + * @param defStyle The default style to apply to this view. If 0, no style + * will be applied (beyond what is included in the theme). This may + * either be an attribute resource, whose value will be retrieved + * from the current theme, or an explicit style resource. + */ + public IcsSpinner(Context context, AttributeSet attrs, int defStyle) { + super(context, attrs, defStyle); + + TypedArray a = context.obtainStyledAttributes(attrs, + R.styleable.SherlockSpinner, defStyle, 0); + + + DropdownPopup popup = new DropdownPopup(context, attrs, defStyle); + + mDropDownWidth = a.getLayoutDimension( + R.styleable.SherlockSpinner_android_dropDownWidth, + ViewGroup.LayoutParams.WRAP_CONTENT); + popup.setBackgroundDrawable(a.getDrawable( + R.styleable.SherlockSpinner_android_popupBackground)); + final int verticalOffset = a.getDimensionPixelOffset( + R.styleable.SherlockSpinner_android_dropDownVerticalOffset, 0); + if (verticalOffset != 0) { + popup.setVerticalOffset(verticalOffset); + } + + final int horizontalOffset = a.getDimensionPixelOffset( + R.styleable.SherlockSpinner_android_dropDownHorizontalOffset, 0); + if (horizontalOffset != 0) { + popup.setHorizontalOffset(horizontalOffset); + } + + mPopup = popup; + + mGravity = a.getInt(R.styleable.SherlockSpinner_android_gravity, Gravity.CENTER); + + mPopup.setPromptText(a.getString(R.styleable.SherlockSpinner_android_prompt)); + + mDisableChildrenWhenDisabled = true; + + a.recycle(); + + // Base constructor can call setAdapter before we initialize mPopup. + // Finish setting things up if this happened. + if (mTempAdapter != null) { + mPopup.setAdapter(mTempAdapter); + mTempAdapter = null; + } + } + + @Override + public void setEnabled(boolean enabled) { + super.setEnabled(enabled); + if (mDisableChildrenWhenDisabled) { + final int count = getChildCount(); + for (int i = 0; i < count; i++) { + getChildAt(i).setEnabled(enabled); + } + } + } + + /** + * Describes how the selected item view is positioned. Currently only the horizontal component + * is used. The default is determined by the current theme. + * + * @param gravity See {@link android.view.Gravity} + * + * @attr ref android.R.styleable#Spinner_gravity + */ + public void setGravity(int gravity) { + if (mGravity != gravity) { + if ((gravity & Gravity.HORIZONTAL_GRAVITY_MASK) == 0) { + gravity |= Gravity.LEFT; + } + mGravity = gravity; + requestLayout(); + } + } + + @Override + public void setAdapter(SpinnerAdapter adapter) { + super.setAdapter(adapter); + + if (mPopup != null) { + mPopup.setAdapter(new DropDownAdapter(adapter)); + } else { + mTempAdapter = new DropDownAdapter(adapter); + } + } + + @Override + public int getBaseline() { + View child = null; + + if (getChildCount() > 0) { + child = getChildAt(0); + } else if (mAdapter != null && mAdapter.getCount() > 0) { + child = makeAndAddView(0); + mRecycler.put(0, child); + removeAllViewsInLayout(); + } + + if (child != null) { + final int childBaseline = child.getBaseline(); + return childBaseline >= 0 ? child.getTop() + childBaseline : -1; + } else { + return -1; + } + } + + @Override + protected void onDetachedFromWindow() { + super.onDetachedFromWindow(); + + if (mPopup != null && mPopup.isShowing()) { + mPopup.dismiss(); + } + } + + /** + *A spinner does not support item click events. Calling this method + * will raise an exception.
+ * + * @param l this listener will be ignored + */ + @Override + public void setOnItemClickListener(OnItemClickListener l) { + throw new RuntimeException("setOnItemClickListener cannot be used with a spinner."); + } + + @Override + protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { + super.onMeasure(widthMeasureSpec, heightMeasureSpec); + if (mPopup != null && MeasureSpec.getMode(widthMeasureSpec) == MeasureSpec.AT_MOST) { + final int measuredWidth = getMeasuredWidth(); + setMeasuredDimension(Math.min(Math.max(measuredWidth, + measureContentWidth(getAdapter(), getBackground())), + MeasureSpec.getSize(widthMeasureSpec)), + getMeasuredHeight()); + } + } + + /** + * @see android.view.View#onLayout(boolean,int,int,int,int) + * + * Creates and positions all views + * + */ + @Override + protected void onLayout(boolean changed, int l, int t, int r, int b) { + super.onLayout(changed, l, t, r, b); + mInLayout = true; + layout(0, false); + mInLayout = false; + } + + /** + * Creates and positions all views for this Spinner. + * + * @param delta Change in the selected position. +1 moves selection is moving to the right, + * so views are scrolling to the left. -1 means selection is moving to the left. + */ + @Override + void layout(int delta, boolean animate) { + int childrenLeft = mSpinnerPadding.left; + int childrenWidth = getRight() - getLeft() - mSpinnerPadding.left - mSpinnerPadding.right; + + if (mDataChanged) { + handleDataChanged(); + } + + // Handle the empty set by removing all views + if (mItemCount == 0) { + resetList(); + return; + } + + if (mNextSelectedPosition >= 0) { + setSelectedPositionInt(mNextSelectedPosition); + } + + recycleAllViews(); + + // Clear out old views + removeAllViewsInLayout(); + + // Make selected view and position it + mFirstPosition = mSelectedPosition; + View sel = makeAndAddView(mSelectedPosition); + int width = sel.getMeasuredWidth(); + int selectedOffset = childrenLeft; + switch (mGravity & Gravity.HORIZONTAL_GRAVITY_MASK) { + case Gravity.CENTER_HORIZONTAL: + selectedOffset = childrenLeft + (childrenWidth / 2) - (width / 2); + break; + case Gravity.RIGHT: + selectedOffset = childrenLeft + childrenWidth - width; + break; + } + sel.offsetLeftAndRight(selectedOffset); + + // Flush any cached views that did not get reused above + mRecycler.clear(); + + invalidate(); + + checkSelectionChanged(); + + mDataChanged = false; + mNeedSync = false; + setNextSelectedPositionInt(mSelectedPosition); + } + + /** + * Obtain a view, either by pulling an existing view from the recycler or + * by getting a new one from the adapter. If we are animating, make sure + * there is enough information in the view's layout parameters to animate + * from the old to new positions. + * + * @param position Position in the spinner for the view to obtain + * @return A view that has been added to the spinner + */ + private View makeAndAddView(int position) { + + View child; + + if (!mDataChanged) { + child = mRecycler.get(position); + if (child != null) { + // Position the view + setUpChild(child); + + return child; + } + } + + // Nothing found in the recycler -- ask the adapter for a view + child = mAdapter.getView(position, null, this); + + // Position the view + setUpChild(child); + + return child; + } + + /** + * Helper for makeAndAddView to set the position of a view + * and fill out its layout paramters. + * + * @param child The view to position + */ + private void setUpChild(View child) { + + // Respect layout params that are already in the view. Otherwise + // make some up... + ViewGroup.LayoutParams lp = child.getLayoutParams(); + if (lp == null) { + lp = generateDefaultLayoutParams(); + } + + addViewInLayout(child, 0, lp); + + child.setSelected(hasFocus()); + if (mDisableChildrenWhenDisabled) { + child.setEnabled(isEnabled()); + } + + // Get measure specs + int childHeightSpec = ViewGroup.getChildMeasureSpec(mHeightMeasureSpec, + mSpinnerPadding.top + mSpinnerPadding.bottom, lp.height); + int childWidthSpec = ViewGroup.getChildMeasureSpec(mWidthMeasureSpec, + mSpinnerPadding.left + mSpinnerPadding.right, lp.width); + + // Measure child + child.measure(childWidthSpec, childHeightSpec); + + int childLeft; + int childRight; + + // Position vertically based on gravity setting + int childTop = mSpinnerPadding.top + + ((getMeasuredHeight() - mSpinnerPadding.bottom - + mSpinnerPadding.top - child.getMeasuredHeight()) / 2); + int childBottom = childTop + child.getMeasuredHeight(); + + int width = child.getMeasuredWidth(); + childLeft = 0; + childRight = childLeft + width; + + child.layout(childLeft, childTop, childRight, childBottom); + } + + @Override + public boolean performClick() { + boolean handled = super.performClick(); + + if (!handled) { + handled = true; + + if (!mPopup.isShowing()) { + mPopup.show(); + } + } + + return handled; + } + + public void onClick(DialogInterface dialog, int which) { + setSelection(which); + dialog.dismiss(); + } + + /** + * Sets the prompt to display when the dialog is shown. + * @param prompt the prompt to set + */ + public void setPrompt(CharSequence prompt) { + mPopup.setPromptText(prompt); + } + + /** + * Sets the prompt to display when the dialog is shown. + * @param promptId the resource ID of the prompt to display when the dialog is shown + */ + public void setPromptId(int promptId) { + setPrompt(getContext().getText(promptId)); + } + + /** + * @return The prompt to display when the dialog is shown + */ + public CharSequence getPrompt() { + return mPopup.getHintText(); + } + + int measureContentWidth(SpinnerAdapter adapter, Drawable background) { + if (adapter == null) { + return 0; + } + + int width = 0; + View itemView = null; + int itemType = 0; + final int widthMeasureSpec = + MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED); + final int heightMeasureSpec = + MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED); + + // Make sure the number of items we'll measure is capped. If it's a huge data set + // with wildly varying sizes, oh well. + int start = Math.max(0, getSelectedItemPosition()); + final int end = Math.min(adapter.getCount(), start + MAX_ITEMS_MEASURED); + final int count = end - start; + start = Math.max(0, start - (MAX_ITEMS_MEASURED - count)); + for (int i = start; i < end; i++) { + final int positionType = adapter.getItemViewType(i); + if (positionType != itemType) { + itemType = positionType; + itemView = null; + } + itemView = adapter.getView(i, itemView, this); + if (itemView.getLayoutParams() == null) { + itemView.setLayoutParams(new ViewGroup.LayoutParams( + ViewGroup.LayoutParams.WRAP_CONTENT, + ViewGroup.LayoutParams.WRAP_CONTENT)); + } + itemView.measure(widthMeasureSpec, heightMeasureSpec); + width = Math.max(width, itemView.getMeasuredWidth()); + } + + // Add background padding to measured width + if (background != null) { + background.getPadding(mTempRect); + width += mTempRect.left + mTempRect.right; + } + + return width; + } + + /** + *Wrapper class for an Adapter. Transforms the embedded Adapter instance + * into a ListAdapter.
+ */ + private static class DropDownAdapter implements ListAdapter, SpinnerAdapter { + private SpinnerAdapter mAdapter; + private ListAdapter mListAdapter; + + /** + *Creates a new ListAdapter wrapper for the specified adapter.
+ * + * @param adapter the Adapter to transform into a ListAdapter + */ + public DropDownAdapter(SpinnerAdapter adapter) { + this.mAdapter = adapter; + if (adapter instanceof ListAdapter) { + this.mListAdapter = (ListAdapter) adapter; + } + } + + public int getCount() { + return mAdapter == null ? 0 : mAdapter.getCount(); + } + + public Object getItem(int position) { + return mAdapter == null ? null : mAdapter.getItem(position); + } + + public long getItemId(int position) { + return mAdapter == null ? -1 : mAdapter.getItemId(position); + } + + public View getView(int position, View convertView, ViewGroup parent) { + return getDropDownView(position, convertView, parent); + } + + public View getDropDownView(int position, View convertView, ViewGroup parent) { + return mAdapter == null ? null : + mAdapter.getDropDownView(position, convertView, parent); + } + + public boolean hasStableIds() { + return mAdapter != null && mAdapter.hasStableIds(); + } + + public void registerDataSetObserver(DataSetObserver observer) { + if (mAdapter != null) { + mAdapter.registerDataSetObserver(observer); + } + } + + public void unregisterDataSetObserver(DataSetObserver observer) { + if (mAdapter != null) { + mAdapter.unregisterDataSetObserver(observer); + } + } + + /** + * If the wrapped SpinnerAdapter is also a ListAdapter, delegate this call. + * Otherwise, return true. + */ + public boolean areAllItemsEnabled() { + final ListAdapter adapter = mListAdapter; + if (adapter != null) { + return adapter.areAllItemsEnabled(); + } else { + return true; + } + } + + /** + * If the wrapped SpinnerAdapter is also a ListAdapter, delegate this call. + * Otherwise, return true. + */ + public boolean isEnabled(int position) { + final ListAdapter adapter = mListAdapter; + if (adapter != null) { + return adapter.isEnabled(position); + } else { + return true; + } + } + + public int getItemViewType(int position) { + return 0; + } + + public int getViewTypeCount() { + return 1; + } + + public boolean isEmpty() { + return getCount() == 0; + } + } + + /** + * Implements some sort of popup selection interface for selecting a spinner option. + * Allows for different spinner modes. + */ + private interface SpinnerPopup { + public void setAdapter(ListAdapter adapter); + + /** + * Show the popup + */ + public void show(); + + /** + * Dismiss the popup + */ + public void dismiss(); + + /** + * @return true if the popup is showing, false otherwise. + */ + public boolean isShowing(); + + /** + * Set hint text to be displayed to the user. This should provide + * a description of the choice being made. + * @param hintText Hint text to set. + */ + public void setPromptText(CharSequence hintText); + public CharSequence getHintText(); + } + + /* + private class DialogPopup implements SpinnerPopup, DialogInterface.OnClickListener { + private AlertDialog mPopup; + private ListAdapter mListAdapter; + private CharSequence mPrompt; + + public void dismiss() { + mPopup.dismiss(); + mPopup = null; + } + + public boolean isShowing() { + return mPopup != null ? mPopup.isShowing() : false; + } + + public void setAdapter(ListAdapter adapter) { + mListAdapter = adapter; + } + + public void setPromptText(CharSequence hintText) { + mPrompt = hintText; + } + + public CharSequence getHintText() { + return mPrompt; + } + + public void show() { + AlertDialog.Builder builder = new AlertDialog.Builder(getContext()); + if (mPrompt != null) { + builder.setTitle(mPrompt); + } + mPopup = builder.setSingleChoiceItems(mListAdapter, + getSelectedItemPosition(), this).show(); + } + + public void onClick(DialogInterface dialog, int which) { + setSelection(which); + dismiss(); + } + } + */ + + private class DropdownPopup extends IcsListPopupWindow implements SpinnerPopup { + private CharSequence mHintText; + private ListAdapter mAdapter; + + public DropdownPopup(Context context, AttributeSet attrs, int defStyleRes) { + super(context, attrs, 0, defStyleRes); + + setAnchorView(IcsSpinner.this); + setModal(true); + setPromptPosition(POSITION_PROMPT_ABOVE); + setOnItemClickListener(new OnItemClickListener() { + @SuppressWarnings("rawtypes") + public void onItemClick(AdapterView parent, View v, int position, long id) { + IcsSpinner.this.setSelection(position); + dismiss(); + } + }); + } + + @Override + public void setAdapter(ListAdapter adapter) { + super.setAdapter(adapter); + mAdapter = adapter; + } + + public CharSequence getHintText() { + return mHintText; + } + + public void setPromptText(CharSequence hintText) { + // Hint text is ignored for dropdowns, but maintain it here. + mHintText = hintText; + } + + @Override + public void show() { + final int spinnerPaddingLeft = IcsSpinner.this.getPaddingLeft(); + if (mDropDownWidth == WRAP_CONTENT) { + final int spinnerWidth = IcsSpinner.this.getWidth(); + final int spinnerPaddingRight = IcsSpinner.this.getPaddingRight(); + setContentWidth(Math.max( + measureContentWidth((SpinnerAdapter) mAdapter, getBackground()), + spinnerWidth - spinnerPaddingLeft - spinnerPaddingRight)); + } else if (mDropDownWidth == MATCH_PARENT) { + final int spinnerWidth = IcsSpinner.this.getWidth(); + final int spinnerPaddingRight = IcsSpinner.this.getPaddingRight(); + setContentWidth(spinnerWidth - spinnerPaddingLeft - spinnerPaddingRight); + } else { + setContentWidth(mDropDownWidth); + } + final Drawable background = getBackground(); + int bgOffset = 0; + if (background != null) { + background.getPadding(mTempRect); + bgOffset = -mTempRect.left; + } + setHorizontalOffset(bgOffset + spinnerPaddingLeft); + setInputMethodMode(PopupWindow.INPUT_METHOD_NOT_NEEDED); + super.show(); + getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE); + setSelection(IcsSpinner.this.getSelectedItemPosition()); + } + } +} diff --git a/libs/ActionBarSherlock/src/com/actionbarsherlock/internal/widget/IcsView.java b/libs/ActionBarSherlock/src/com/actionbarsherlock/internal/widget/IcsView.java index 4cd50e4..a7185d0 100644 --- a/libs/ActionBarSherlock/src/com/actionbarsherlock/internal/widget/IcsView.java +++ b/libs/ActionBarSherlock/src/com/actionbarsherlock/internal/widget/IcsView.java @@ -1,47 +1,11 @@ package com.actionbarsherlock.internal.widget; import android.view.View; -import android.view.View.MeasureSpec; final class IcsView { //No instances private IcsView() {} - /** - * Utility to reconcile a desired size and state, with constraints imposed - * by a MeasureSpec. Will take the desired size, unless a different size - * is imposed by the constraints. The returned value is a compound integer, - * with the resolved size in the {@link #MEASURED_SIZE_MASK} bits and - * optionally the bit {@link #MEASURED_STATE_TOO_SMALL} set if the resulting - * size is smaller than the size the view wants to be. - * - * @param size How big the view wants to be - * @param measureSpec Constraints imposed by the parent - * @return Size information bit mask as defined by - * {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}. - */ - public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) { - int result = size; - int specMode = MeasureSpec.getMode(measureSpec); - int specSize = MeasureSpec.getSize(measureSpec); - switch (specMode) { - case MeasureSpec.UNSPECIFIED: - result = size; - break; - case MeasureSpec.AT_MOST: - if (specSize < size) { - result = specSize | View.MEASURED_STATE_TOO_SMALL; - } else { - result = size; - } - break; - case MeasureSpec.EXACTLY: - result = specSize; - break; - } - return result | (childMeasuredState&View.MEASURED_STATE_MASK); - } - /** * Return only the state bits of {@link #getMeasuredWidthAndState()} * and {@link #getMeasuredHeightAndState()}, combined into one integer. diff --git a/libs/ActionBarSherlock/src/com/actionbarsherlock/internal/widget/ScrollingTabContainerView.java b/libs/ActionBarSherlock/src/com/actionbarsherlock/internal/widget/ScrollingTabContainerView.java index 562f44b..1a532e0 100644 --- a/libs/ActionBarSherlock/src/com/actionbarsherlock/internal/widget/ScrollingTabContainerView.java +++ b/libs/ActionBarSherlock/src/com/actionbarsherlock/internal/widget/ScrollingTabContainerView.java @@ -25,33 +25,31 @@ import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; +import android.view.ViewParent; import android.view.animation.DecelerateInterpolator; import android.view.animation.Interpolator; -import android.widget.AdapterView; import android.widget.BaseAdapter; -import android.widget.HorizontalScrollView; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ListView; -import android.widget.Spinner; -import android.widget.TextView; import com.actionbarsherlock.R; import com.actionbarsherlock.app.ActionBar; import com.actionbarsherlock.internal.nineoldandroids.animation.Animator; import com.actionbarsherlock.internal.nineoldandroids.animation.ObjectAnimator; +import com.actionbarsherlock.internal.nineoldandroids.widget.NineHorizontalScrollView; /** * This widget implements the dynamic action bar tab behavior that can change * across different configurations or circumstances. */ -public class ScrollingTabContainerView extends HorizontalScrollView - implements AdapterView.OnItemSelectedListener { +public class ScrollingTabContainerView extends NineHorizontalScrollView + implements IcsAdapterView.OnItemSelectedListener { //UNUSED private static final String TAG = "ScrollingTabContainerView"; Runnable mTabSelector; private TabClickListener mTabClickListener; private IcsLinearLayout mTabLayout; - private Spinner mTabSpinner; + private IcsSpinner mTabSpinner; private boolean mAllowCollapse; private LayoutInflater mInflater; @@ -80,7 +78,7 @@ public class ScrollingTabContainerView extends HorizontalScrollView mTabLayout = createTabLayout(); addView(mTabLayout, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, - ViewGroup.LayoutParams.FILL_PARENT)); + ViewGroup.LayoutParams.MATCH_PARENT)); } @Override @@ -148,7 +146,7 @@ public class ScrollingTabContainerView extends HorizontalScrollView } removeView(mTabLayout); addView(mTabSpinner, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, - ViewGroup.LayoutParams.FILL_PARENT)); + ViewGroup.LayoutParams.MATCH_PARENT)); if (mTabSpinner.getAdapter() == null) { mTabSpinner.setAdapter(new TabAdapter()); } @@ -164,7 +162,7 @@ public class ScrollingTabContainerView extends HorizontalScrollView removeView(mTabSpinner); addView(mTabLayout, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, - ViewGroup.LayoutParams.FILL_PARENT)); + ViewGroup.LayoutParams.MATCH_PARENT)); setTabSelected(mTabSpinner.getSelectedItemPosition()); return false; } @@ -188,17 +186,18 @@ public class ScrollingTabContainerView extends HorizontalScrollView } private IcsLinearLayout createTabLayout() { - final IcsLinearLayout tabLayout = new IcsLinearLayout(getContext(), null, R.attr.actionBarTabBarStyle); + final IcsLinearLayout tabLayout = (IcsLinearLayout) LayoutInflater.from(getContext()) + .inflate(R.layout.abs__action_bar_tab_bar_view, null); tabLayout.setLayoutParams(new LinearLayout.LayoutParams( LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.MATCH_PARENT)); return tabLayout; } - private Spinner createSpinner() { - final Spinner spinner = new Spinner(getContext(), null, + private IcsSpinner createSpinner() { + final IcsSpinner spinner = new IcsSpinner(getContext(), null, R.attr.actionDropDownStyle); spinner.setLayoutParams(new LinearLayout.LayoutParams( - LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.FILL_PARENT)); + LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.MATCH_PARENT)); spinner.setOnItemSelectedListener(this); return spinner; } @@ -278,7 +277,7 @@ public class ScrollingTabContainerView extends HorizontalScrollView if (forAdapter) { tabView.setBackgroundDrawable(null); - tabView.setLayoutParams(new ListView.LayoutParams(ListView.LayoutParams.FILL_PARENT, + tabView.setLayoutParams(new ListView.LayoutParams(ListView.LayoutParams.MATCH_PARENT, mContentHeight)); } else { tabView.setFocusable(true); @@ -294,7 +293,7 @@ public class ScrollingTabContainerView extends HorizontalScrollView public void addTab(ActionBar.Tab tab, boolean setSelected) { TabView tabView = createTabView(tab, false); mTabLayout.addView(tabView, new IcsLinearLayout.LayoutParams(0, - LayoutParams.FILL_PARENT, 1)); + LayoutParams.MATCH_PARENT, 1)); if (mTabSpinner != null) { ((TabAdapter) mTabSpinner.getAdapter()).notifyDataSetChanged(); } @@ -309,7 +308,7 @@ public class ScrollingTabContainerView extends HorizontalScrollView public void addTab(ActionBar.Tab tab, int position, boolean setSelected) { final TabView tabView = createTabView(tab, false); mTabLayout.addView(tabView, position, new IcsLinearLayout.LayoutParams( - 0, LayoutParams.FILL_PARENT, 1)); + 0, LayoutParams.MATCH_PARENT, 1)); if (mTabSpinner != null) { ((TabAdapter) mTabSpinner.getAdapter()).notifyDataSetChanged(); } @@ -352,19 +351,19 @@ public class ScrollingTabContainerView extends HorizontalScrollView } @Override - public void onItemSelected(AdapterView> parent, View view, int position, long id) { + public void onItemSelected(IcsAdapterView> parent, View view, int position, long id) { TabView tabView = (TabView) view; tabView.getTab().select(); } @Override - public void onNothingSelected(AdapterView> parent) { + public void onNothingSelected(IcsAdapterView> parent) { } public static class TabView extends LinearLayout { private ScrollingTabContainerView mParent; private ActionBar.Tab mTab; - private TextView mTextView; + private CapitalizingTextView mTextView; private ImageView mIconView; private View mCustomView; @@ -404,7 +403,11 @@ public class ScrollingTabContainerView extends HorizontalScrollView final ActionBar.Tab tab = mTab; final View custom = tab.getCustomView(); if (custom != null) { - addView(custom); + final ViewParent customParent = custom.getParent(); + if (customParent != this) { + if (customParent != null) ((ViewGroup) customParent).removeView(custom); + addView(custom); + } mCustomView = custom; if (mTextView != null) mTextView.setVisibility(GONE); if (mIconView != null) { @@ -439,7 +442,7 @@ public class ScrollingTabContainerView extends HorizontalScrollView if (text != null) { if (mTextView == null) { - TextView textView = new TextView(getContext(), null, + CapitalizingTextView textView = new CapitalizingTextView(getContext(), null, R.attr.actionBarTabTextStyle); textView.setEllipsize(TruncateAt.END); LayoutParams lp = new LayoutParams(LayoutParams.WRAP_CONTENT, @@ -449,7 +452,7 @@ public class ScrollingTabContainerView extends HorizontalScrollView addView(textView); mTextView = textView; } - mTextView.setText(text); + mTextView.setTextCompat(text); mTextView.setVisibility(VISIBLE); } else if (mTextView != null) { mTextView.setVisibility(GONE); diff --git a/libs/ActionBarSherlock/src/com/actionbarsherlock/view/MenuInflater.java b/libs/ActionBarSherlock/src/com/actionbarsherlock/view/MenuInflater.java index 0219a10..9694597 100644 --- a/libs/ActionBarSherlock/src/com/actionbarsherlock/view/MenuInflater.java +++ b/libs/ActionBarSherlock/src/com/actionbarsherlock/view/MenuInflater.java @@ -23,12 +23,16 @@ import java.lang.reflect.Method; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import android.content.Context; +import android.content.res.TypedArray; import android.content.res.XmlResourceParser; import android.util.AttributeSet; import android.util.Log; +import android.util.TypedValue; import android.util.Xml; import android.view.InflateException; import android.view.View; + +import com.actionbarsherlock.R; import com.actionbarsherlock.internal.view.menu.MenuItemImpl; /** @@ -43,9 +47,6 @@ import com.actionbarsherlock.internal.view.menu.MenuItemImpl; public class MenuInflater { private static final String LOG_TAG = "MenuInflater"; - /** Android XML namespace. */ - private static final String XML_NS = "http://schemas.android.com/apk/res/android"; - /** Menu tag name in XML. */ private static final String XML_MENU = "menu"; @@ -306,107 +307,59 @@ public class MenuInflater { * Called when the parser is pointing to a group tag. */ public void readGroup(AttributeSet attrs) { - //TypedArray a = mContext.obtainStyledAttributes(attrs, com.android.internal.R.styleable.MenuGroup); + TypedArray a = mContext.obtainStyledAttributes(attrs, + R.styleable.SherlockMenuGroup); - //groupId = a.getResourceId(com.android.internal.R.styleable.MenuGroup_id, defaultGroupId); - groupId = attrs.getAttributeResourceValue(XML_NS, "id", defaultGroupId); + groupId = a.getResourceId(R.styleable.SherlockMenuGroup_android_id, defaultGroupId); + groupCategory = a.getInt(R.styleable.SherlockMenuGroup_android_menuCategory, defaultItemCategory); + groupOrder = a.getInt(R.styleable.SherlockMenuGroup_android_orderInCategory, defaultItemOrder); + groupCheckable = a.getInt(R.styleable.SherlockMenuGroup_android_checkableBehavior, defaultItemCheckable); + groupVisible = a.getBoolean(R.styleable.SherlockMenuGroup_android_visible, defaultItemVisible); + groupEnabled = a.getBoolean(R.styleable.SherlockMenuGroup_android_enabled, defaultItemEnabled); - //groupCategory = a.getInt(com.android.internal.R.styleable.MenuGroup_menuCategory, defaultItemCategory); - groupCategory = attrs.getAttributeIntValue(XML_NS, "menuCategory", defaultItemCategory); - - //groupOrder = a.getInt(com.android.internal.R.styleable.MenuGroup_orderInCategory, defaultItemOrder); - groupOrder = attrs.getAttributeIntValue(XML_NS, "orderInCategory", defaultItemOrder); - - //groupCheckable = a.getInt(com.android.internal.R.styleable.MenuGroup_checkableBehavior, defaultItemCheckable); - groupCheckable = attrs.getAttributeIntValue(XML_NS, "checkableBehavior", defaultItemCheckable); - - //groupVisible = a.getBoolean(com.android.internal.R.styleable.MenuGroup_visible, defaultItemVisible); - groupVisible = attrs.getAttributeBooleanValue(XML_NS, "visible", defaultItemVisible); - - //groupEnabled = a.getBoolean(com.android.internal.R.styleable.MenuGroup_enabled, defaultItemEnabled); - groupEnabled = attrs.getAttributeBooleanValue(XML_NS, "enabled", defaultItemEnabled); - - //a.recycle(); + a.recycle(); } /** * Called when the parser is pointing to an item tag. */ public void readItem(AttributeSet attrs) { - //TypedArray a = mContext.obtainStyledAttributes(attrs, com.android.internal.R.styleable.MenuItem); + TypedArray a = mContext.obtainStyledAttributes(attrs, + R.styleable.SherlockMenuItem); // Inherit attributes from the group as default value - - //itemId = a.getResourceId(com.android.internal.R.styleable.MenuItem_id, defaultItemId); - itemId = attrs.getAttributeResourceValue(XML_NS, "id", defaultItemId); - - //final int category = a.getInt(com.android.internal.R.styleable.MenuItem_menuCategory, groupCategory); - final int category = attrs.getAttributeIntValue(XML_NS, "menuCategory", groupCategory); - - //final int order = a.getInt(com.android.internal.R.styleable.MenuItem_orderInCategory, groupOrder); - final int order = attrs.getAttributeIntValue(XML_NS, "orderInCategory", groupOrder); - + itemId = a.getResourceId(R.styleable.SherlockMenuItem_android_id, defaultItemId); + final int category = a.getInt(R.styleable.SherlockMenuItem_android_menuCategory, groupCategory); + final int order = a.getInt(R.styleable.SherlockMenuItem_android_orderInCategory, groupOrder); itemCategoryOrder = (category & Menu.CATEGORY_MASK) | (order & Menu.USER_MASK); - - //itemTitle = a.getString(com.android.internal.R.styleable.MenuItem_title); - final int itemTitleId = attrs.getAttributeResourceValue(XML_NS, "title", 0); - if (itemTitleId != 0) { - itemTitle = mContext.getString(itemTitleId); - } else { - itemTitle = attrs.getAttributeValue(XML_NS, "title"); - } - - //itemTitleCondensed = a.getString(com.android.internal.R.styleable.MenuItem_titleCondensed); - final int itemTitleCondensedId = attrs.getAttributeResourceValue(XML_NS, "titleCondensed", 0); - if (itemTitleCondensedId != 0) { - itemTitleCondensed = mContext.getString(itemTitleCondensedId); - } else { - itemTitleCondensed = attrs.getAttributeValue(XML_NS, "titleCondensed"); - } - - //itemIconResId = a.getResourceId(com.android.internal.R.styleable.MenuItem_icon, 0); - itemIconResId = attrs.getAttributeResourceValue(XML_NS, "icon", 0); - - //itemAlphabeticShortcut = getShortcut(a.getString(com.android.internal.R.styleable.MenuItem_alphabeticShortcut)); - itemAlphabeticShortcut = getShortcut(attrs.getAttributeValue(XML_NS, "alphabeticShortcut")); - - //itemNumericShortcut = getShortcut(a.getString(com.android.internal.R.styleable.MenuItem_numericShortcut)); - itemNumericShortcut = getShortcut(attrs.getAttributeValue(XML_NS, "numericShortcut")); - - //if (a.hasValue(com.android.internal.R.styleable.MenuItem_checkable)) { - if (attrs.getAttributeValue(XML_NS, "checkable") != null) { + itemTitle = a.getText(R.styleable.SherlockMenuItem_android_title); + itemTitleCondensed = a.getText(R.styleable.SherlockMenuItem_android_titleCondensed); + itemIconResId = a.getResourceId(R.styleable.SherlockMenuItem_android_icon, 0); + itemAlphabeticShortcut = + getShortcut(a.getString(R.styleable.SherlockMenuItem_android_alphabeticShortcut)); + itemNumericShortcut = + getShortcut(a.getString(R.styleable.SherlockMenuItem_android_numericShortcut)); + if (a.hasValue(R.styleable.SherlockMenuItem_android_checkable)) { // Item has attribute checkable, use it - //itemCheckable = a.getBoolean(com.android.internal.R.styleable.MenuItem_checkable, false) ? 1 : 0; - itemCheckable = attrs.getAttributeBooleanValue(XML_NS, "checkable", false) ? 1 : 0; + itemCheckable = a.getBoolean(R.styleable.SherlockMenuItem_android_checkable, false) ? 1 : 0; } else { // Item does not have attribute, use the group's (group can have one more state // for checkable that represents the exclusive checkable) itemCheckable = groupCheckable; } - //itemChecked = a.getBoolean(com.android.internal.R.styleable.MenuItem_checked, defaultItemChecked); - itemChecked = attrs.getAttributeBooleanValue(XML_NS, "checked", defaultItemChecked); + itemChecked = a.getBoolean(R.styleable.SherlockMenuItem_android_checked, defaultItemChecked); + itemVisible = a.getBoolean(R.styleable.SherlockMenuItem_android_visible, groupVisible); + itemEnabled = a.getBoolean(R.styleable.SherlockMenuItem_android_enabled, groupEnabled); - //itemVisible = a.getBoolean(com.android.internal.R.styleable.MenuItem_visible, groupVisible); - itemVisible = attrs.getAttributeBooleanValue(XML_NS, "visible", groupVisible); + TypedValue value = new TypedValue(); + a.getValue(R.styleable.SherlockMenuItem_android_showAsAction, value); + itemShowAsAction = value.type == TypedValue.TYPE_INT_HEX ? value.data : -1; - //itemEnabled = a.getBoolean(com.android.internal.R.styleable.MenuItem_enabled, groupEnabled); - itemEnabled = attrs.getAttributeBooleanValue(XML_NS, "enabled", groupEnabled); - - //itemShowAsAction = a.getInt(com.android.internal.R.styleable.MenuItem_showAsAction, -1); - itemShowAsAction = attrs.getAttributeIntValue(XML_NS, "showAsAction", -1); - - //itemListenerMethodName = a.getString(com.android.internal.R.styleable.MenuItem_onClick); - itemListenerMethodName = attrs.getAttributeValue(XML_NS, "onClick"); - - //itemActionViewLayout = a.getResourceId(com.android.internal.R.styleable.MenuItem_actionLayout, 0); - itemActionViewLayout = attrs.getAttributeResourceValue(XML_NS, "actionLayout", 0); - - //itemActionViewClassName = a.getString(com.android.internal.R.styleable.MenuItem_actionViewClass); - itemActionViewClassName = attrs.getAttributeValue(XML_NS, "actionViewClass"); - - //itemActionProviderClassName = a.getString(com.android.internal.R.styleable.MenuItem_actionProviderClass); - itemActionProviderClassName = attrs.getAttributeValue(XML_NS, "actionProviderClass"); + itemListenerMethodName = a.getString(R.styleable.SherlockMenuItem_android_onClick); + itemActionViewLayout = a.getResourceId(R.styleable.SherlockMenuItem_android_actionLayout, 0); + itemActionViewClassName = a.getString(R.styleable.SherlockMenuItem_android_actionViewClass); + itemActionProviderClassName = a.getString(R.styleable.SherlockMenuItem_android_actionProviderClass); final boolean hasActionProvider = itemActionProviderClassName != null; if (hasActionProvider && itemActionViewLayout == 0 && itemActionViewClassName == null) { @@ -421,7 +374,7 @@ public class MenuInflater { itemActionProvider = null; } - //a.recycle(); + a.recycle(); itemAdded = false; } @@ -457,10 +410,12 @@ public class MenuInflater { new InflatedOnMenuItemClickListener(mContext, itemListenerMethodName)); } - if (item instanceof MenuItemImpl) { - MenuItemImpl impl = (MenuItemImpl) item; - if (itemCheckable >= 2) { + if (itemCheckable >= 2) { + if (item instanceof MenuItemImpl) { + MenuItemImpl impl = (MenuItemImpl) item; impl.setExclusiveCheckable(true); + } else { + menu.setGroupCheckable(groupId, true, true); } } diff --git a/libs/ActionBarSherlock/src/com/actionbarsherlock/view/MenuItem.java b/libs/ActionBarSherlock/src/com/actionbarsherlock/view/MenuItem.java index 406c4c2..7fc3aa4 100644 --- a/libs/ActionBarSherlock/src/com/actionbarsherlock/view/MenuItem.java +++ b/libs/ActionBarSherlock/src/com/actionbarsherlock/view/MenuItem.java @@ -40,29 +40,29 @@ public interface MenuItem { * These should be kept in sync with attrs.xml enum constants for showAsAction */ /** Never show this item as a button in an Action Bar. */ - public static final int SHOW_AS_ACTION_NEVER = 0; + public static final int SHOW_AS_ACTION_NEVER = android.view.MenuItem.SHOW_AS_ACTION_NEVER; /** Show this item as a button in an Action Bar if the system decides there is room for it. */ - public static final int SHOW_AS_ACTION_IF_ROOM = 1; + public static final int SHOW_AS_ACTION_IF_ROOM = android.view.MenuItem.SHOW_AS_ACTION_IF_ROOM; /** * Always show this item as a button in an Action Bar. * Use sparingly! If too many items are set to always show in the Action Bar it can * crowd the Action Bar and degrade the user experience on devices with smaller screens. * A good rule of thumb is to have no more than 2 items set to always show at a time. */ - public static final int SHOW_AS_ACTION_ALWAYS = 2; + public static final int SHOW_AS_ACTION_ALWAYS = android.view.MenuItem.SHOW_AS_ACTION_ALWAYS; /** * When this item is in the action bar, always show it with a text label even if * it also has an icon specified. */ - public static final int SHOW_AS_ACTION_WITH_TEXT = 4; + public static final int SHOW_AS_ACTION_WITH_TEXT = android.view.MenuItem.SHOW_AS_ACTION_WITH_TEXT; /** * This item's action view collapses to a normal menu item. * When expanded, the action view temporarily takes over * a larger segment of its container. */ - public static final int SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW = 8; + public static final int SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW = android.view.MenuItem.SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW; /** * Interface definition for a callback to be invoked when a menu item is diff --git a/libs/ActionBarSherlock/src/com/actionbarsherlock/widget/ActivityChooserModel.java b/libs/ActionBarSherlock/src/com/actionbarsherlock/widget/ActivityChooserModel.java new file mode 100644 index 0000000..3792074 --- /dev/null +++ b/libs/ActionBarSherlock/src/com/actionbarsherlock/widget/ActivityChooserModel.java @@ -0,0 +1,1131 @@ +/* + * Copyright (C) 2011 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 com.actionbarsherlock.widget; + +import android.content.ComponentName; +import android.content.Context; +import android.content.Intent; +import android.content.pm.ResolveInfo; +import android.database.DataSetObservable; +import android.os.Handler; +import android.text.TextUtils; +import android.util.Log; +import android.util.Xml; + +import org.xmlpull.v1.XmlPullParser; +import org.xmlpull.v1.XmlPullParserException; +import org.xmlpull.v1.XmlSerializer; + +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.IOException; +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.LinkedHashSet; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.Executor; + +/** + *+ * This class represents a data model for choosing a component for handing a + * given {@link Intent}. The model is responsible for querying the system for + * activities that can handle the given intent and order found activities + * based on historical data of previous choices. The historical data is stored + * in an application private file. If a client does not want to have persistent + * choice history the file can be omitted, thus the activities will be ordered + * based on historical usage for the current session. + *
+ *
+ * For each backing history file there is a singleton instance of this class. Thus, + * several clients that specify the same history file will share the same model. Note + * that if multiple clients are sharing the same model they should implement semantically + * equivalent functionality since setting the model intent will change the found + * activities and they may be inconsistent with the functionality of some of the clients. + * For example, choosing a share activity can be implemented by a single backing + * model and two different views for performing the selection. If however, one of the + * views is used for sharing but the other for importing, for example, then each + * view should be backed by a separate model. + * + *+ * The way clients interact with this class is as follows: + *
+ *+ *
+ *
+ * // Get a model and set it to a couple of clients with semantically similar function.
+ * ActivityChooserModel dataModel =
+ * ActivityChooserModel.get(context, "task_specific_history_file_name.xml");
+ *
+ * ActivityChooserModelClient modelClient1 = getActivityChooserModelClient1();
+ * modelClient1.setActivityChooserModel(dataModel);
+ *
+ * ActivityChooserModelClient modelClient2 = getActivityChooserModelClient2();
+ * modelClient2.setActivityChooserModel(dataModel);
+ *
+ * // Set an intent to choose a an activity for.
+ * dataModel.setIntent(intent);
+ *
+ *
+ *
+ *
+ * Note: This class is thread safe.
+ *
+ *
+ * @hide
+ */
+class ActivityChooserModel extends DataSetObservable {
+
+ /**
+ * Client that utilizes an {@link ActivityChooserModel}.
+ */
+ public interface ActivityChooserModelClient {
+
+ /**
+ * Sets the {@link ActivityChooserModel}.
+ *
+ * @param dataModel The model.
+ */
+ public void setActivityChooserModel(ActivityChooserModel dataModel);
+ }
+
+ /**
+ * Defines a sorter that is responsible for sorting the activities
+ * based on the provided historical choices and an intent.
+ */
+ public interface ActivitySorter {
+
+ /**
+ * Sorts the activities
in descending order of relevance
+ * based on previous history and an intent.
+ *
+ * @param intent The {@link Intent}.
+ * @param activities Activities to be sorted.
+ * @param historicalRecords Historical records.
+ */
+ // This cannot be done by a simple comparator since an Activity weight
+ // is computed from history. Note that Activity implements Comparable.
+ public void sort(Intent intent, List activities,
+ List historicalRecords);
+ }
+
+ /**
+ * Listener for choosing an activity.
+ */
+ public interface OnChooseActivityListener {
+
+ /**
+ * Called when an activity has been chosen. The client can decide whether
+ * an activity can be chosen and if so the caller of
+ * {@link ActivityChooserModel#chooseActivity(int)} will receive and {@link Intent}
+ * for launching it.
+ *
+ * Note: Modifying the intent is not permitted and
+ * any changes to the latter will be ignored.
+ *
+ *
+ * @param host The listener's host model.
+ * @param intent The intent for launching the chosen activity.
+ * @return Whether the intent is handled and should not be delivered to clients.
+ *
+ * @see ActivityChooserModel#chooseActivity(int)
+ */
+ public boolean onChooseActivity(ActivityChooserModel host, Intent intent);
+ }
+
+ /**
+ * Flag for selecting debug mode.
+ */
+ private static final boolean DEBUG = false;
+
+ /**
+ * Tag used for logging.
+ */
+ private static final String LOG_TAG = ActivityChooserModel.class.getSimpleName();
+
+ /**
+ * The root tag in the history file.
+ */
+ private static final String TAG_HISTORICAL_RECORDS = "historical-records";
+
+ /**
+ * The tag for a record in the history file.
+ */
+ private static final String TAG_HISTORICAL_RECORD = "historical-record";
+
+ /**
+ * Attribute for the activity.
+ */
+ private static final String ATTRIBUTE_ACTIVITY = "activity";
+
+ /**
+ * Attribute for the choice time.
+ */
+ private static final String ATTRIBUTE_TIME = "time";
+
+ /**
+ * Attribute for the choice weight.
+ */
+ private static final String ATTRIBUTE_WEIGHT = "weight";
+
+ /**
+ * The default name of the choice history file.
+ */
+ public static final String DEFAULT_HISTORY_FILE_NAME =
+ "activity_choser_model_history.xml";
+
+ /**
+ * The default maximal length of the choice history.
+ */
+ public static final int DEFAULT_HISTORY_MAX_LENGTH = 50;
+
+ /**
+ * The amount with which to inflate a chosen activity when set as default.
+ */
+ private static final int DEFAULT_ACTIVITY_INFLATION = 5;
+
+ /**
+ * Default weight for a choice record.
+ */
+ private static final float DEFAULT_HISTORICAL_RECORD_WEIGHT = 1.0f;
+
+ /**
+ * The extension of the history file.
+ */
+ private static final String HISTORY_FILE_EXTENSION = ".xml";
+
+ /**
+ * An invalid item index.
+ */
+ private static final int INVALID_INDEX = -1;
+
+ /**
+ * Lock to guard the model registry.
+ */
+ private static final Object sRegistryLock = new Object();
+
+ /**
+ * This the registry for data models.
+ */
+ private static final Map sDataModelRegistry =
+ new HashMap();
+
+ /**
+ * Lock for synchronizing on this instance.
+ */
+ private final Object mInstanceLock = new Object();
+
+ /**
+ * List of activities that can handle the current intent.
+ */
+ private final List mActivites = new ArrayList();
+
+ /**
+ * List with historical choice records.
+ */
+ private final List mHistoricalRecords = new ArrayList();
+
+ /**
+ * Context for accessing resources.
+ */
+ private final Context mContext;
+
+ /**
+ * The name of the history file that backs this model.
+ */
+ private final String mHistoryFileName;
+
+ /**
+ * The intent for which a activity is being chosen.
+ */
+ private Intent mIntent;
+
+ /**
+ * The sorter for ordering activities based on intent and past choices.
+ */
+ private ActivitySorter mActivitySorter = new DefaultSorter();
+
+ /**
+ * The maximal length of the choice history.
+ */
+ private int mHistoryMaxSize = DEFAULT_HISTORY_MAX_LENGTH;
+
+ /**
+ * Flag whether choice history can be read. In general many clients can
+ * share the same data model and {@link #readHistoricalData()} may be called
+ * by arbitrary of them any number of times. Therefore, this class guarantees
+ * that the very first read succeeds and subsequent reads can be performed
+ * only after a call to {@link #persistHistoricalData()} followed by change
+ * of the share records.
+ */
+ private boolean mCanReadHistoricalData = true;
+
+ /**
+ * Flag whether the choice history was read. This is used to enforce that
+ * before calling {@link #persistHistoricalData()} a call to
+ * {@link #persistHistoricalData()} has been made. This aims to avoid a
+ * scenario in which a choice history file exits, it is not read yet and
+ * it is overwritten. Note that always all historical records are read in
+ * full and the file is rewritten. This is necessary since we need to
+ * purge old records that are outside of the sliding window of past choices.
+ */
+ private boolean mReadShareHistoryCalled = false;
+
+ /**
+ * Flag whether the choice records have changed. In general many clients can
+ * share the same data model and {@link #persistHistoricalData()} may be called
+ * by arbitrary of them any number of times. Therefore, this class guarantees
+ * that choice history will be persisted only if it has changed.
+ */
+ private boolean mHistoricalRecordsChanged = true;
+
+ /**
+ * Hander for scheduling work on client tread.
+ */
+ private final Handler mHandler = new Handler();
+
+ /**
+ * Policy for controlling how the model handles chosen activities.
+ */
+ private OnChooseActivityListener mActivityChoserModelPolicy;
+
+ /**
+ * Gets the data model backed by the contents of the provided file with historical data.
+ * Note that only one data model is backed by a given file, thus multiple calls with
+ * the same file name will return the same model instance. If no such instance is present
+ * it is created.
+ *
+ * Note: To use the default historical data file clients should explicitly
+ * pass as file name {@link #DEFAULT_HISTORY_FILE_NAME}. If no persistence of the choice
+ * history is desired clients should pass null
for the file name. In such
+ * case a new model is returned for each invocation.
+ *
+ *
+ *
+ * Always use difference historical data files for semantically different actions.
+ * For example, sharing is different from importing.
+ *
+ *
+ * @param context Context for loading resources.
+ * @param historyFileName File name with choice history, null
+ * if the model should not be backed by a file. In this case the activities
+ * will be ordered only by data from the current session.
+ *
+ * @return The model.
+ */
+ public static ActivityChooserModel get(Context context, String historyFileName) {
+ synchronized (sRegistryLock) {
+ ActivityChooserModel dataModel = sDataModelRegistry.get(historyFileName);
+ if (dataModel == null) {
+ dataModel = new ActivityChooserModel(context, historyFileName);
+ sDataModelRegistry.put(historyFileName, dataModel);
+ }
+ dataModel.readHistoricalData();
+ return dataModel;
+ }
+ }
+
+ /**
+ * Creates a new instance.
+ *
+ * @param context Context for loading resources.
+ * @param historyFileName The history XML file.
+ */
+ private ActivityChooserModel(Context context, String historyFileName) {
+ mContext = context.getApplicationContext();
+ if (!TextUtils.isEmpty(historyFileName)
+ && !historyFileName.endsWith(HISTORY_FILE_EXTENSION)) {
+ mHistoryFileName = historyFileName + HISTORY_FILE_EXTENSION;
+ } else {
+ mHistoryFileName = historyFileName;
+ }
+ }
+
+ /**
+ * Sets an intent for which to choose a activity.
+ *
+ * Note: Clients must set only semantically similar
+ * intents for each data model.
+ *
+ *
+ * @param intent The intent.
+ */
+ public void setIntent(Intent intent) {
+ synchronized (mInstanceLock) {
+ if (mIntent == intent) {
+ return;
+ }
+ mIntent = intent;
+ loadActivitiesLocked();
+ }
+ }
+
+ /**
+ * Gets the intent for which a activity is being chosen.
+ *
+ * @return The intent.
+ */
+ public Intent getIntent() {
+ synchronized (mInstanceLock) {
+ return mIntent;
+ }
+ }
+
+ /**
+ * Gets the number of activities that can handle the intent.
+ *
+ * @return The activity count.
+ *
+ * @see #setIntent(Intent)
+ */
+ public int getActivityCount() {
+ synchronized (mInstanceLock) {
+ return mActivites.size();
+ }
+ }
+
+ /**
+ * Gets an activity at a given index.
+ *
+ * @return The activity.
+ *
+ * @see ActivityResolveInfo
+ * @see #setIntent(Intent)
+ */
+ public ResolveInfo getActivity(int index) {
+ synchronized (mInstanceLock) {
+ return mActivites.get(index).resolveInfo;
+ }
+ }
+
+ /**
+ * Gets the index of a the given activity.
+ *
+ * @param activity The activity index.
+ *
+ * @return The index if found, -1 otherwise.
+ */
+ public int getActivityIndex(ResolveInfo activity) {
+ List activities = mActivites;
+ final int activityCount = activities.size();
+ for (int i = 0; i < activityCount; i++) {
+ ActivityResolveInfo currentActivity = activities.get(i);
+ if (currentActivity.resolveInfo == activity) {
+ return i;
+ }
+ }
+ return INVALID_INDEX;
+ }
+
+ /**
+ * Chooses a activity to handle the current intent. This will result in
+ * adding a historical record for that action and construct intent with
+ * its component name set such that it can be immediately started by the
+ * client.
+ *
+ * Note: By calling this method the client guarantees
+ * that the returned intent will be started. This intent is returned to
+ * the client solely to let additional customization before the start.
+ *
+ *
+ * @return An {@link Intent} for launching the activity or null if the
+ * policy has consumed the intent.
+ *
+ * @see HistoricalRecord
+ * @see OnChooseActivityListener
+ */
+ public Intent chooseActivity(int index) {
+ ActivityResolveInfo chosenActivity = mActivites.get(index);
+
+ ComponentName chosenName = new ComponentName(
+ chosenActivity.resolveInfo.activityInfo.packageName,
+ chosenActivity.resolveInfo.activityInfo.name);
+
+ Intent choiceIntent = new Intent(mIntent);
+ choiceIntent.setComponent(chosenName);
+
+ if (mActivityChoserModelPolicy != null) {
+ // Do not allow the policy to change the intent.
+ Intent choiceIntentCopy = new Intent(choiceIntent);
+ final boolean handled = mActivityChoserModelPolicy.onChooseActivity(this,
+ choiceIntentCopy);
+ if (handled) {
+ return null;
+ }
+ }
+
+ HistoricalRecord historicalRecord = new HistoricalRecord(chosenName,
+ System.currentTimeMillis(), DEFAULT_HISTORICAL_RECORD_WEIGHT);
+ addHisoricalRecord(historicalRecord);
+
+ return choiceIntent;
+ }
+
+ /**
+ * Sets the listener for choosing an activity.
+ *
+ * @param listener The listener.
+ */
+ public void setOnChooseActivityListener(OnChooseActivityListener listener) {
+ mActivityChoserModelPolicy = listener;
+ }
+
+ /**
+ * Gets the default activity, The default activity is defined as the one
+ * with highest rank i.e. the first one in the list of activities that can
+ * handle the intent.
+ *
+ * @return The default activity, null
id not activities.
+ *
+ * @see #getActivity(int)
+ */
+ public ResolveInfo getDefaultActivity() {
+ synchronized (mInstanceLock) {
+ if (!mActivites.isEmpty()) {
+ return mActivites.get(0).resolveInfo;
+ }
+ }
+ return null;
+ }
+
+ /**
+ * Sets the default activity. The default activity is set by adding a
+ * historical record with weight high enough that this activity will
+ * become the highest ranked. Such a strategy guarantees that the default
+ * will eventually change if not used. Also the weight of the record for
+ * setting a default is inflated with a constant amount to guarantee that
+ * it will stay as default for awhile.
+ *
+ * @param index The index of the activity to set as default.
+ */
+ public void setDefaultActivity(int index) {
+ ActivityResolveInfo newDefaultActivity = mActivites.get(index);
+ ActivityResolveInfo oldDefaultActivity = mActivites.get(0);
+
+ final float weight;
+ if (oldDefaultActivity != null) {
+ // Add a record with weight enough to boost the chosen at the top.
+ weight = oldDefaultActivity.weight - newDefaultActivity.weight
+ + DEFAULT_ACTIVITY_INFLATION;
+ } else {
+ weight = DEFAULT_HISTORICAL_RECORD_WEIGHT;
+ }
+
+ ComponentName defaultName = new ComponentName(
+ newDefaultActivity.resolveInfo.activityInfo.packageName,
+ newDefaultActivity.resolveInfo.activityInfo.name);
+ HistoricalRecord historicalRecord = new HistoricalRecord(defaultName,
+ System.currentTimeMillis(), weight);
+ addHisoricalRecord(historicalRecord);
+ }
+
+ /**
+ * Reads the history data from the backing file if the latter
+ * was provided. Calling this method more than once before a call
+ * to {@link #persistHistoricalData()} has been made has no effect.
+ *
+ * Note: Historical data is read asynchronously and
+ * as soon as the reading is completed any registered
+ * {@link DataSetObserver}s will be notified. Also no historical
+ * data is read until this method is invoked.
+ *
+ */
+ private void readHistoricalData() {
+ synchronized (mInstanceLock) {
+ if (!mCanReadHistoricalData || !mHistoricalRecordsChanged) {
+ return;
+ }
+ mCanReadHistoricalData = false;
+ mReadShareHistoryCalled = true;
+ if (!TextUtils.isEmpty(mHistoryFileName)) {
+ /*AsyncTask.*/SERIAL_EXECUTOR.execute(new HistoryLoader());
+ }
+ }
+ }
+
+ private static final SerialExecutor SERIAL_EXECUTOR = new SerialExecutor();
+
+ private static class SerialExecutor implements Executor {
+ final LinkedList mTasks = new LinkedList();
+ Runnable mActive;
+
+ public synchronized void execute(final Runnable r) {
+ mTasks.offer(new Runnable() {
+ public void run() {
+ try {
+ r.run();
+ } finally {
+ scheduleNext();
+ }
+ }
+ });
+ if (mActive == null) {
+ scheduleNext();
+ }
+ }
+
+ protected synchronized void scheduleNext() {
+ if ((mActive = mTasks.poll()) != null) {
+ mActive.run();
+ }
+ }
+ }
+
+ /**
+ * Persists the history data to the backing file if the latter
+ * was provided. Calling this method before a call to {@link #readHistoricalData()}
+ * throws an exception. Calling this method more than one without choosing an
+ * activity has not effect.
+ *
+ * @throws IllegalStateException If this method is called before a call to
+ * {@link #readHistoricalData()}.
+ */
+ private void persistHistoricalData() {
+ synchronized (mInstanceLock) {
+ if (!mReadShareHistoryCalled) {
+ throw new IllegalStateException("No preceding call to #readHistoricalData");
+ }
+ if (!mHistoricalRecordsChanged) {
+ return;
+ }
+ mHistoricalRecordsChanged = false;
+ mCanReadHistoricalData = true;
+ if (!TextUtils.isEmpty(mHistoryFileName)) {
+ /*AsyncTask.*/SERIAL_EXECUTOR.execute(new HistoryPersister());
+ }
+ }
+ }
+
+ /**
+ * Sets the sorter for ordering activities based on historical data and an intent.
+ *
+ * @param activitySorter The sorter.
+ *
+ * @see ActivitySorter
+ */
+ public void setActivitySorter(ActivitySorter activitySorter) {
+ synchronized (mInstanceLock) {
+ if (mActivitySorter == activitySorter) {
+ return;
+ }
+ mActivitySorter = activitySorter;
+ sortActivities();
+ }
+ }
+
+ /**
+ * Sorts the activities based on history and an intent. If
+ * a sorter is not specified this a default implementation is used.
+ *
+ * @see #setActivitySorter(ActivitySorter)
+ */
+ private void sortActivities() {
+ synchronized (mInstanceLock) {
+ if (mActivitySorter != null && !mActivites.isEmpty()) {
+ mActivitySorter.sort(mIntent, mActivites,
+ Collections.unmodifiableList(mHistoricalRecords));
+ notifyChanged();
+ }
+ }
+ }
+
+ /**
+ * Sets the maximal size of the historical data. Defaults to
+ * {@link #DEFAULT_HISTORY_MAX_LENGTH}
+ *
+ * Note: Setting this property will immediately
+ * enforce the specified max history size by dropping enough old
+ * historical records to enforce the desired size. Thus, any
+ * records that exceed the history size will be discarded and
+ * irreversibly lost.
+ *
+ *
+ * @param historyMaxSize The max history size.
+ */
+ public void setHistoryMaxSize(int historyMaxSize) {
+ synchronized (mInstanceLock) {
+ if (mHistoryMaxSize == historyMaxSize) {
+ return;
+ }
+ mHistoryMaxSize = historyMaxSize;
+ pruneExcessiveHistoricalRecordsLocked();
+ sortActivities();
+ }
+ }
+
+ /**
+ * Gets the history max size.
+ *
+ * @return The history max size.
+ */
+ public int getHistoryMaxSize() {
+ synchronized (mInstanceLock) {
+ return mHistoryMaxSize;
+ }
+ }
+
+ /**
+ * Gets the history size.
+ *
+ * @return The history size.
+ */
+ public int getHistorySize() {
+ synchronized (mInstanceLock) {
+ return mHistoricalRecords.size();
+ }
+ }
+
+ /**
+ * Adds a historical record.
+ *
+ * @param historicalRecord The record to add.
+ * @return True if the record was added.
+ */
+ private boolean addHisoricalRecord(HistoricalRecord historicalRecord) {
+ synchronized (mInstanceLock) {
+ final boolean added = mHistoricalRecords.add(historicalRecord);
+ if (added) {
+ mHistoricalRecordsChanged = true;
+ pruneExcessiveHistoricalRecordsLocked();
+ persistHistoricalData();
+ sortActivities();
+ }
+ return added;
+ }
+ }
+
+ /**
+ * Prunes older excessive records to guarantee {@link #mHistoryMaxSize}.
+ */
+ private void pruneExcessiveHistoricalRecordsLocked() {
+ List choiceRecords = mHistoricalRecords;
+ final int pruneCount = choiceRecords.size() - mHistoryMaxSize;
+ if (pruneCount <= 0) {
+ return;
+ }
+ mHistoricalRecordsChanged = true;
+ for (int i = 0; i < pruneCount; i++) {
+ HistoricalRecord prunedRecord = choiceRecords.remove(0);
+ if (DEBUG) {
+ Log.i(LOG_TAG, "Pruned: " + prunedRecord);
+ }
+ }
+ }
+
+ /**
+ * Loads the activities.
+ */
+ private void loadActivitiesLocked() {
+ mActivites.clear();
+ if (mIntent != null) {
+ List resolveInfos =
+ mContext.getPackageManager().queryIntentActivities(mIntent, 0);
+ final int resolveInfoCount = resolveInfos.size();
+ for (int i = 0; i < resolveInfoCount; i++) {
+ ResolveInfo resolveInfo = resolveInfos.get(i);
+ mActivites.add(new ActivityResolveInfo(resolveInfo));
+ }
+ sortActivities();
+ } else {
+ notifyChanged();
+ }
+ }
+
+ /**
+ * Represents a record in the history.
+ */
+ public final static class HistoricalRecord {
+
+ /**
+ * The activity name.
+ */
+ public final ComponentName activity;
+
+ /**
+ * The choice time.
+ */
+ public final long time;
+
+ /**
+ * The record weight.
+ */
+ public final float weight;
+
+ /**
+ * Creates a new instance.
+ *
+ * @param activityName The activity component name flattened to string.
+ * @param time The time the activity was chosen.
+ * @param weight The weight of the record.
+ */
+ public HistoricalRecord(String activityName, long time, float weight) {
+ this(ComponentName.unflattenFromString(activityName), time, weight);
+ }
+
+ /**
+ * Creates a new instance.
+ *
+ * @param activityName The activity name.
+ * @param time The time the activity was chosen.
+ * @param weight The weight of the record.
+ */
+ public HistoricalRecord(ComponentName activityName, long time, float weight) {
+ this.activity = activityName;
+ this.time = time;
+ this.weight = weight;
+ }
+
+ @Override
+ public int hashCode() {
+ final int prime = 31;
+ int result = 1;
+ result = prime * result + ((activity == null) ? 0 : activity.hashCode());
+ result = prime * result + (int) (time ^ (time >>> 32));
+ result = prime * result + Float.floatToIntBits(weight);
+ return result;
+ }
+
+ @Override
+ public boolean equals(Object obj) {
+ if (this == obj) {
+ return true;
+ }
+ if (obj == null) {
+ return false;
+ }
+ if (getClass() != obj.getClass()) {
+ return false;
+ }
+ HistoricalRecord other = (HistoricalRecord) obj;
+ if (activity == null) {
+ if (other.activity != null) {
+ return false;
+ }
+ } else if (!activity.equals(other.activity)) {
+ return false;
+ }
+ if (time != other.time) {
+ return false;
+ }
+ if (Float.floatToIntBits(weight) != Float.floatToIntBits(other.weight)) {
+ return false;
+ }
+ return true;
+ }
+
+ @Override
+ public String toString() {
+ StringBuilder builder = new StringBuilder();
+ builder.append("[");
+ builder.append("; activity:").append(activity);
+ builder.append("; time:").append(time);
+ builder.append("; weight:").append(new BigDecimal(weight));
+ builder.append("]");
+ return builder.toString();
+ }
+ }
+
+ /**
+ * Represents an activity.
+ */
+ public final class ActivityResolveInfo implements Comparable {
+
+ /**
+ * The {@link ResolveInfo} of the activity.
+ */
+ public final ResolveInfo resolveInfo;
+
+ /**
+ * Weight of the activity. Useful for sorting.
+ */
+ public float weight;
+
+ /**
+ * Creates a new instance.
+ *
+ * @param resolveInfo activity {@link ResolveInfo}.
+ */
+ public ActivityResolveInfo(ResolveInfo resolveInfo) {
+ this.resolveInfo = resolveInfo;
+ }
+
+ @Override
+ public int hashCode() {
+ return 31 + Float.floatToIntBits(weight);
+ }
+
+ @Override
+ public boolean equals(Object obj) {
+ if (this == obj) {
+ return true;
+ }
+ if (obj == null) {
+ return false;
+ }
+ if (getClass() != obj.getClass()) {
+ return false;
+ }
+ ActivityResolveInfo other = (ActivityResolveInfo) obj;
+ if (Float.floatToIntBits(weight) != Float.floatToIntBits(other.weight)) {
+ return false;
+ }
+ return true;
+ }
+
+ public int compareTo(ActivityResolveInfo another) {
+ return Float.floatToIntBits(another.weight) - Float.floatToIntBits(weight);
+ }
+
+ @Override
+ public String toString() {
+ StringBuilder builder = new StringBuilder();
+ builder.append("[");
+ builder.append("resolveInfo:").append(resolveInfo.toString());
+ builder.append("; weight:").append(new BigDecimal(weight));
+ builder.append("]");
+ return builder.toString();
+ }
+ }
+
+ /**
+ * Default activity sorter implementation.
+ */
+ private final class DefaultSorter implements ActivitySorter {
+ private static final float WEIGHT_DECAY_COEFFICIENT = 0.95f;
+
+ private final Map mPackageNameToActivityMap =
+ new HashMap();
+
+ public void sort(Intent intent, List activities,
+ List historicalRecords) {
+ Map packageNameToActivityMap =
+ mPackageNameToActivityMap;
+ packageNameToActivityMap.clear();
+
+ final int activityCount = activities.size();
+ for (int i = 0; i < activityCount; i++) {
+ ActivityResolveInfo activity = activities.get(i);
+ activity.weight = 0.0f;
+ String packageName = activity.resolveInfo.activityInfo.packageName;
+ packageNameToActivityMap.put(packageName, activity);
+ }
+
+ final int lastShareIndex = historicalRecords.size() - 1;
+ float nextRecordWeight = 1;
+ for (int i = lastShareIndex; i >= 0; i--) {
+ HistoricalRecord historicalRecord = historicalRecords.get(i);
+ String packageName = historicalRecord.activity.getPackageName();
+ ActivityResolveInfo activity = packageNameToActivityMap.get(packageName);
+ if (activity != null) {
+ activity.weight += historicalRecord.weight * nextRecordWeight;
+ nextRecordWeight = nextRecordWeight * WEIGHT_DECAY_COEFFICIENT;
+ }
+ }
+
+ Collections.sort(activities);
+
+ if (DEBUG) {
+ for (int i = 0; i < activityCount; i++) {
+ Log.i(LOG_TAG, "Sorted: " + activities.get(i));
+ }
+ }
+ }
+ }
+
+ /**
+ * Command for reading the historical records from a file off the UI thread.
+ */
+ private final class HistoryLoader implements Runnable {
+
+ public void run() {
+ FileInputStream fis = null;
+ try {
+ fis = mContext.openFileInput(mHistoryFileName);
+ } catch (FileNotFoundException fnfe) {
+ if (DEBUG) {
+ Log.i(LOG_TAG, "Could not open historical records file: " + mHistoryFileName);
+ }
+ return;
+ }
+ try {
+ XmlPullParser parser = Xml.newPullParser();
+ parser.setInput(fis, null);
+
+ int type = XmlPullParser.START_DOCUMENT;
+ while (type != XmlPullParser.END_DOCUMENT && type != XmlPullParser.START_TAG) {
+ type = parser.next();
+ }
+
+ if (!TAG_HISTORICAL_RECORDS.equals(parser.getName())) {
+ throw new XmlPullParserException("Share records file does not start with "
+ + TAG_HISTORICAL_RECORDS + " tag.");
+ }
+
+ List readRecords = new ArrayList();
+
+ while (true) {
+ type = parser.next();
+ if (type == XmlPullParser.END_DOCUMENT) {
+ break;
+ }
+ if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
+ continue;
+ }
+ String nodeName = parser.getName();
+ if (!TAG_HISTORICAL_RECORD.equals(nodeName)) {
+ throw new XmlPullParserException("Share records file not well-formed.");
+ }
+
+ String activity = parser.getAttributeValue(null, ATTRIBUTE_ACTIVITY);
+ final long time =
+ Long.parseLong(parser.getAttributeValue(null, ATTRIBUTE_TIME));
+ final float weight =
+ Float.parseFloat(parser.getAttributeValue(null, ATTRIBUTE_WEIGHT));
+
+ HistoricalRecord readRecord = new HistoricalRecord(activity, time,
+ weight);
+ readRecords.add(readRecord);
+
+ if (DEBUG) {
+ Log.i(LOG_TAG, "Read " + readRecord.toString());
+ }
+ }
+
+ if (DEBUG) {
+ Log.i(LOG_TAG, "Read " + readRecords.size() + " historical records.");
+ }
+
+ synchronized (mInstanceLock) {
+ Set uniqueShareRecords =
+ new LinkedHashSet(readRecords);
+
+ // Make sure no duplicates. Example: Read a file with
+ // one record, add one record, persist the two records,
+ // add a record, read the persisted records - the
+ // read two records should not be added again.
+ List historicalRecords = mHistoricalRecords;
+ final int historicalRecordsCount = historicalRecords.size();
+ for (int i = historicalRecordsCount - 1; i >= 0; i--) {
+ HistoricalRecord historicalRecord = historicalRecords.get(i);
+ uniqueShareRecords.add(historicalRecord);
+ }
+
+ if (historicalRecords.size() == uniqueShareRecords.size()) {
+ return;
+ }
+
+ // Make sure the oldest records go to the end.
+ historicalRecords.clear();
+ historicalRecords.addAll(uniqueShareRecords);
+
+ mHistoricalRecordsChanged = true;
+
+ // Do this on the client thread since the client may be on the UI
+ // thread, wait for data changes which happen during sorting, and
+ // perform UI modification based on the data change.
+ mHandler.post(new Runnable() {
+ public void run() {
+ pruneExcessiveHistoricalRecordsLocked();
+ sortActivities();
+ }
+ });
+ }
+ } catch (XmlPullParserException xppe) {
+ Log.e(LOG_TAG, "Error reading historical recrod file: " + mHistoryFileName, xppe);
+ } catch (IOException ioe) {
+ Log.e(LOG_TAG, "Error reading historical recrod file: " + mHistoryFileName, ioe);
+ } finally {
+ if (fis != null) {
+ try {
+ fis.close();
+ } catch (IOException ioe) {
+ /* ignore */
+ }
+ }
+ }
+ }
+ }
+
+ /**
+ * Command for persisting the historical records to a file off the UI thread.
+ */
+ private final class HistoryPersister implements Runnable {
+
+ public void run() {
+ FileOutputStream fos = null;
+ List records = null;
+
+ synchronized (mInstanceLock) {
+ records = new ArrayList(mHistoricalRecords);
+ }
+
+ try {
+ fos = mContext.openFileOutput(mHistoryFileName, Context.MODE_PRIVATE);
+ } catch (FileNotFoundException fnfe) {
+ Log.e(LOG_TAG, "Error writing historical recrod file: " + mHistoryFileName, fnfe);
+ return;
+ }
+
+ XmlSerializer serializer = Xml.newSerializer();
+
+ try {
+ serializer.setOutput(fos, null);
+ serializer.startDocument("UTF-8", true);
+ serializer.startTag(null, TAG_HISTORICAL_RECORDS);
+
+ final int recordCount = records.size();
+ for (int i = 0; i < recordCount; i++) {
+ HistoricalRecord record = records.remove(0);
+ serializer.startTag(null, TAG_HISTORICAL_RECORD);
+ serializer.attribute(null, ATTRIBUTE_ACTIVITY, record.activity.flattenToString());
+ serializer.attribute(null, ATTRIBUTE_TIME, String.valueOf(record.time));
+ serializer.attribute(null, ATTRIBUTE_WEIGHT, String.valueOf(record.weight));
+ serializer.endTag(null, TAG_HISTORICAL_RECORD);
+ if (DEBUG) {
+ Log.i(LOG_TAG, "Wrote " + record.toString());
+ }
+ }
+
+ serializer.endTag(null, TAG_HISTORICAL_RECORDS);
+ serializer.endDocument();
+
+ if (DEBUG) {
+ Log.i(LOG_TAG, "Wrote " + recordCount + " historical records.");
+ }
+ } catch (IllegalArgumentException iae) {
+ Log.e(LOG_TAG, "Error writing historical recrod file: " + mHistoryFileName, iae);
+ } catch (IllegalStateException ise) {
+ Log.e(LOG_TAG, "Error writing historical recrod file: " + mHistoryFileName, ise);
+ } catch (IOException ioe) {
+ Log.e(LOG_TAG, "Error writing historical recrod file: " + mHistoryFileName, ioe);
+ } finally {
+ if (fos != null) {
+ try {
+ fos.close();
+ } catch (IOException e) {
+ /* ignore */
+ }
+ }
+ }
+ }
+ }
+}
diff --git a/libs/ActionBarSherlock/src/com/actionbarsherlock/widget/ActivityChooserView.java b/libs/ActionBarSherlock/src/com/actionbarsherlock/widget/ActivityChooserView.java
new file mode 100644
index 0000000..da13bc9
--- /dev/null
+++ b/libs/ActionBarSherlock/src/com/actionbarsherlock/widget/ActivityChooserView.java
@@ -0,0 +1,818 @@
+/*
+ * Copyright (C) 2011 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 com.actionbarsherlock.widget;
+
+import android.os.Build;
+import com.actionbarsherlock.R;
+import com.actionbarsherlock.internal.widget.IcsLinearLayout;
+import com.actionbarsherlock.internal.widget.IcsListPopupWindow;
+import com.actionbarsherlock.view.ActionProvider;
+import com.actionbarsherlock.widget.ActivityChooserModel.ActivityChooserModelClient;
+import android.content.Context;
+import android.content.Intent;
+import android.content.pm.PackageManager;
+import android.content.pm.ResolveInfo;
+import android.content.res.Resources;
+import android.content.res.TypedArray;
+import android.database.DataSetObserver;
+import android.graphics.drawable.Drawable;
+import android.util.AttributeSet;
+import android.view.LayoutInflater;
+import android.view.View;
+import android.view.ViewGroup;
+import android.view.ViewTreeObserver;
+import android.view.ViewTreeObserver.OnGlobalLayoutListener;
+import android.widget.AdapterView;
+import android.widget.BaseAdapter;
+import android.widget.FrameLayout;
+import android.widget.ImageView;
+import android.widget.PopupWindow;
+import android.widget.TextView;
+
+/**
+ * This class is a view for choosing an activity for handling a given {@link Intent}.
+ *
+ * The view is composed of two adjacent buttons:
+ *
+ * -
+ * The left button is an immediate action and allows one click activity choosing.
+ * Tapping this button immediately executes the intent without requiring any further
+ * user input. Long press on this button shows a popup for changing the default
+ * activity.
+ *
+ * -
+ * The right button is an overflow action and provides an optimized menu
+ * of additional activities. Tapping this button shows a popup anchored to this
+ * view, listing the most frequently used activities. This list is initially
+ * limited to a small number of items in frequency used order. The last item,
+ * "Show all..." serves as an affordance to display all available activities.
+ *
+ *
+ *
+ *
+ * @hide
+ */
+class ActivityChooserView extends ViewGroup implements ActivityChooserModelClient {
+
+ /**
+ * An adapter for displaying the activities in an {@link AdapterView}.
+ */
+ private final ActivityChooserViewAdapter mAdapter;
+
+ /**
+ * Implementation of various interfaces to avoid publishing them in the APIs.
+ */
+ private final Callbacks mCallbacks;
+
+ /**
+ * The content of this view.
+ */
+ private final IcsLinearLayout mActivityChooserContent;
+
+ /**
+ * Stores the background drawable to allow hiding and latter showing.
+ */
+ private final Drawable mActivityChooserContentBackground;
+
+ /**
+ * The expand activities action button;
+ */
+ private final FrameLayout mExpandActivityOverflowButton;
+
+ /**
+ * The image for the expand activities action button;
+ */
+ private final ImageView mExpandActivityOverflowButtonImage;
+
+ /**
+ * The default activities action button;
+ */
+ private final FrameLayout mDefaultActivityButton;
+
+ /**
+ * The image for the default activities action button;
+ */
+ private final ImageView mDefaultActivityButtonImage;
+
+ /**
+ * The maximal width of the list popup.
+ */
+ private final int mListPopupMaxWidth;
+
+ /**
+ * The ActionProvider hosting this view, if applicable.
+ */
+ ActionProvider mProvider;
+
+ /**
+ * Observer for the model data.
+ */
+ private final DataSetObserver mModelDataSetOberver = new DataSetObserver() {
+
+ @Override
+ public void onChanged() {
+ super.onChanged();
+ mAdapter.notifyDataSetChanged();
+ }
+ @Override
+ public void onInvalidated() {
+ super.onInvalidated();
+ mAdapter.notifyDataSetInvalidated();
+ }
+ };
+
+ private final OnGlobalLayoutListener mOnGlobalLayoutListener = new OnGlobalLayoutListener() {
+ @Override
+ public void onGlobalLayout() {
+ if (isShowingPopup()) {
+ if (!isShown()) {
+ getListPopupWindow().dismiss();
+ } else {
+ getListPopupWindow().show();
+ if (mProvider != null) {
+ mProvider.subUiVisibilityChanged(true);
+ }
+ }
+ }
+ }
+ };
+
+ /**
+ * Popup window for showing the activity overflow list.
+ */
+ private IcsListPopupWindow mListPopupWindow;
+
+ /**
+ * Listener for the dismissal of the popup/alert.
+ */
+ private PopupWindow.OnDismissListener mOnDismissListener;
+
+ /**
+ * Flag whether a default activity currently being selected.
+ */
+ private boolean mIsSelectingDefaultActivity;
+
+ /**
+ * The count of activities in the popup.
+ */
+ private int mInitialActivityCount = ActivityChooserViewAdapter.MAX_ACTIVITY_COUNT_DEFAULT;
+
+ /**
+ * Flag whether this view is attached to a window.
+ */
+ private boolean mIsAttachedToWindow;
+
+ /**
+ * String resource for formatting content description of the default target.
+ */
+ private int mDefaultActionButtonContentDescription;
+
+ private final Context mContext;
+
+ /**
+ * Create a new instance.
+ *
+ * @param context The application environment.
+ */
+ public ActivityChooserView(Context context) {
+ this(context, null);
+ }
+
+ /**
+ * Create a new instance.
+ *
+ * @param context The application environment.
+ * @param attrs A collection of attributes.
+ */
+ public ActivityChooserView(Context context, AttributeSet attrs) {
+ this(context, attrs, 0);
+ }
+
+ /**
+ * Create a new instance.
+ *
+ * @param context The application environment.
+ * @param attrs A collection of attributes.
+ * @param defStyle The default style to apply to this view.
+ */
+ public ActivityChooserView(Context context, AttributeSet attrs, int defStyle) {
+ super(context, attrs, defStyle);
+ mContext = context;
+
+ TypedArray attributesArray = context.obtainStyledAttributes(attrs,
+ R.styleable.SherlockActivityChooserView, defStyle, 0);
+
+ mInitialActivityCount = attributesArray.getInt(
+ R.styleable.SherlockActivityChooserView_initialActivityCount,
+ ActivityChooserViewAdapter.MAX_ACTIVITY_COUNT_DEFAULT);
+
+ Drawable expandActivityOverflowButtonDrawable = attributesArray.getDrawable(
+ R.styleable.SherlockActivityChooserView_expandActivityOverflowButtonDrawable);
+
+ attributesArray.recycle();
+
+ LayoutInflater inflater = LayoutInflater.from(mContext);
+ inflater.inflate(R.layout.abs__activity_chooser_view, this, true);
+
+ mCallbacks = new Callbacks();
+
+ mActivityChooserContent = (IcsLinearLayout) findViewById(R.id.abs__activity_chooser_view_content);
+ mActivityChooserContentBackground = mActivityChooserContent.getBackground();
+
+ mDefaultActivityButton = (FrameLayout) findViewById(R.id.abs__default_activity_button);
+ mDefaultActivityButton.setOnClickListener(mCallbacks);
+ mDefaultActivityButton.setOnLongClickListener(mCallbacks);
+ mDefaultActivityButtonImage = (ImageView) mDefaultActivityButton.findViewById(R.id.abs__image);
+
+ mExpandActivityOverflowButton = (FrameLayout) findViewById(R.id.abs__expand_activities_button);
+ mExpandActivityOverflowButton.setOnClickListener(mCallbacks);
+ mExpandActivityOverflowButtonImage =
+ (ImageView) mExpandActivityOverflowButton.findViewById(R.id.abs__image);
+ mExpandActivityOverflowButtonImage.setImageDrawable(expandActivityOverflowButtonDrawable);
+
+ mAdapter = new ActivityChooserViewAdapter();
+ mAdapter.registerDataSetObserver(new DataSetObserver() {
+ @Override
+ public void onChanged() {
+ super.onChanged();
+ updateAppearance();
+ }
+ });
+
+ Resources resources = context.getResources();
+ mListPopupMaxWidth = Math.max(resources.getDisplayMetrics().widthPixels / 2,
+ resources.getDimensionPixelSize(R.dimen.abs__config_prefDialogWidth));
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public void setActivityChooserModel(ActivityChooserModel dataModel) {
+ mAdapter.setDataModel(dataModel);
+ if (isShowingPopup()) {
+ dismissPopup();
+ showPopup();
+ }
+ }
+
+ /**
+ * Sets the background for the button that expands the activity
+ * overflow list.
+ *
+ * Note: Clients would like to set this drawable
+ * as a clue about the action the chosen activity will perform. For
+ * example, if a share activity is to be chosen the drawable should
+ * give a clue that sharing is to be performed.
+ *
+ * @param drawable The drawable.
+ */
+ public void setExpandActivityOverflowButtonDrawable(Drawable drawable) {
+ mExpandActivityOverflowButtonImage.setImageDrawable(drawable);
+ }
+
+ /**
+ * Sets the content description for the button that expands the activity
+ * overflow list.
+ *
+ * description as a clue about the action performed by the button.
+ * For example, if a share activity is to be chosen the content
+ * description should be something like "Share with".
+ *
+ * @param resourceId The content description resource id.
+ */
+ public void setExpandActivityOverflowButtonContentDescription(int resourceId) {
+ CharSequence contentDescription = mContext.getString(resourceId);
+ mExpandActivityOverflowButtonImage.setContentDescription(contentDescription);
+ }
+
+ /**
+ * Set the provider hosting this view, if applicable.
+ * @hide Internal use only
+ */
+ public void setProvider(ActionProvider provider) {
+ mProvider = provider;
+ }
+
+ /**
+ * Shows the popup window with activities.
+ *
+ * @return True if the popup was shown, false if already showing.
+ */
+ public boolean showPopup() {
+ if (isShowingPopup() || !mIsAttachedToWindow) {
+ return false;
+ }
+ mIsSelectingDefaultActivity = false;
+ showPopupUnchecked(mInitialActivityCount);
+ return true;
+ }
+
+ /**
+ * Shows the popup no matter if it was already showing.
+ *
+ * @param maxActivityCount The max number of activities to display.
+ */
+ private void showPopupUnchecked(int maxActivityCount) {
+ if (mAdapter.getDataModel() == null) {
+ throw new IllegalStateException("No data model. Did you call #setDataModel?");
+ }
+
+ getViewTreeObserver().addOnGlobalLayoutListener(mOnGlobalLayoutListener);
+
+ final boolean defaultActivityButtonShown =
+ mDefaultActivityButton.getVisibility() == VISIBLE;
+
+ final int activityCount = mAdapter.getActivityCount();
+ final int maxActivityCountOffset = defaultActivityButtonShown ? 1 : 0;
+ if (maxActivityCount != ActivityChooserViewAdapter.MAX_ACTIVITY_COUNT_UNLIMITED
+ && activityCount > maxActivityCount + maxActivityCountOffset) {
+ mAdapter.setShowFooterView(true);
+ mAdapter.setMaxActivityCount(maxActivityCount - 1);
+ } else {
+ mAdapter.setShowFooterView(false);
+ mAdapter.setMaxActivityCount(maxActivityCount);
+ }
+
+ IcsListPopupWindow popupWindow = getListPopupWindow();
+ if (!popupWindow.isShowing()) {
+ if (mIsSelectingDefaultActivity || !defaultActivityButtonShown) {
+ mAdapter.setShowDefaultActivity(true, defaultActivityButtonShown);
+ } else {
+ mAdapter.setShowDefaultActivity(false, false);
+ }
+ final int contentWidth = Math.min(mAdapter.measureContentWidth(), mListPopupMaxWidth);
+ popupWindow.setContentWidth(contentWidth);
+ popupWindow.show();
+ if (mProvider != null) {
+ mProvider.subUiVisibilityChanged(true);
+ }
+ popupWindow.getListView().setContentDescription(mContext.getString(
+ R.string.abs__activitychooserview_choose_application));
+ }
+ }
+
+ /**
+ * Dismisses the popup window with activities.
+ *
+ * @return True if dismissed, false if already dismissed.
+ */
+ public boolean dismissPopup() {
+ if (isShowingPopup()) {
+ getListPopupWindow().dismiss();
+ ViewTreeObserver viewTreeObserver = getViewTreeObserver();
+ if (viewTreeObserver.isAlive()) {
+ viewTreeObserver.removeGlobalOnLayoutListener(mOnGlobalLayoutListener);
+ }
+ }
+ return true;
+ }
+
+ /**
+ * Gets whether the popup window with activities is shown.
+ *
+ * @return True if the popup is shown.
+ */
+ public boolean isShowingPopup() {
+ return getListPopupWindow().isShowing();
+ }
+
+ @Override
+ protected void onAttachedToWindow() {
+ super.onAttachedToWindow();
+ ActivityChooserModel dataModel = mAdapter.getDataModel();
+ if (dataModel != null) {
+ dataModel.registerObserver(mModelDataSetOberver);
+ }
+ mIsAttachedToWindow = true;
+ }
+
+ @Override
+ protected void onDetachedFromWindow() {
+ super.onDetachedFromWindow();
+ ActivityChooserModel dataModel = mAdapter.getDataModel();
+ if (dataModel != null) {
+ dataModel.unregisterObserver(mModelDataSetOberver);
+ }
+ ViewTreeObserver viewTreeObserver = getViewTreeObserver();
+ if (viewTreeObserver.isAlive()) {
+ viewTreeObserver.removeGlobalOnLayoutListener(mOnGlobalLayoutListener);
+ }
+ mIsAttachedToWindow = false;
+ }
+
+ @Override
+ protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
+ View child = mActivityChooserContent;
+ // If the default action is not visible we want to be as tall as the
+ // ActionBar so if this widget is used in the latter it will look as
+ // a normal action button.
+ if (mDefaultActivityButton.getVisibility() != VISIBLE) {
+ heightMeasureSpec = MeasureSpec.makeMeasureSpec(MeasureSpec.getSize(heightMeasureSpec),
+ MeasureSpec.EXACTLY);
+ }
+ measureChild(child, widthMeasureSpec, heightMeasureSpec);
+ setMeasuredDimension(child.getMeasuredWidth(), child.getMeasuredHeight());
+ }
+
+ @Override
+ protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
+ mActivityChooserContent.layout(0, 0, right - left, bottom - top);
+ if (getListPopupWindow().isShowing()) {
+ showPopupUnchecked(mAdapter.getMaxActivityCount());
+ } else {
+ dismissPopup();
+ }
+ }
+
+ public ActivityChooserModel getDataModel() {
+ return mAdapter.getDataModel();
+ }
+
+ /**
+ * Sets a listener to receive a callback when the popup is dismissed.
+ *
+ * @param listener The listener to be notified.
+ */
+ public void setOnDismissListener(PopupWindow.OnDismissListener listener) {
+ mOnDismissListener = listener;
+ }
+
+ /**
+ * Sets the initial count of items shown in the activities popup
+ * i.e. the items before the popup is expanded. This is an upper
+ * bound since it is not guaranteed that such number of intent
+ * handlers exist.
+ *
+ * @param itemCount The initial popup item count.
+ */
+ public void setInitialActivityCount(int itemCount) {
+ mInitialActivityCount = itemCount;
+ }
+
+ /**
+ * Sets a content description of the default action button. This
+ * resource should be a string taking one formatting argument and
+ * will be used for formatting the content description of the button
+ * dynamically as the default target changes. For example, a resource
+ * pointing to the string "share with %1$s" will result in a content
+ * description "share with Bluetooth" for the Bluetooth activity.
+ *
+ * @param resourceId The resource id.
+ */
+ public void setDefaultActionButtonContentDescription(int resourceId) {
+ mDefaultActionButtonContentDescription = resourceId;
+ }
+
+ /**
+ * Gets the list popup window which is lazily initialized.
+ *
+ * @return The popup.
+ */
+ private IcsListPopupWindow getListPopupWindow() {
+ if (mListPopupWindow == null) {
+ mListPopupWindow = new IcsListPopupWindow(getContext());
+ mListPopupWindow.setAdapter(mAdapter);
+ mListPopupWindow.setAnchorView(ActivityChooserView.this);
+ mListPopupWindow.setModal(true);
+ mListPopupWindow.setOnItemClickListener(mCallbacks);
+ mListPopupWindow.setOnDismissListener(mCallbacks);
+ }
+ return mListPopupWindow;
+ }
+
+ /**
+ * Updates the buttons state.
+ */
+ private void updateAppearance() {
+ // Expand overflow button.
+ if (mAdapter.getCount() > 0) {
+ mExpandActivityOverflowButton.setEnabled(true);
+ } else {
+ mExpandActivityOverflowButton.setEnabled(false);
+ }
+ // Default activity button.
+ final int activityCount = mAdapter.getActivityCount();
+ final int historySize = mAdapter.getHistorySize();
+ if (activityCount > 0 && historySize > 0) {
+ mDefaultActivityButton.setVisibility(VISIBLE);
+ ResolveInfo activity = mAdapter.getDefaultActivity();
+ PackageManager packageManager = mContext.getPackageManager();
+ mDefaultActivityButtonImage.setImageDrawable(activity.loadIcon(packageManager));
+ if (mDefaultActionButtonContentDescription != 0) {
+ CharSequence label = activity.loadLabel(packageManager);
+ String contentDescription = mContext.getString(
+ mDefaultActionButtonContentDescription, label);
+ mDefaultActivityButton.setContentDescription(contentDescription);
+ }
+ } else {
+ mDefaultActivityButton.setVisibility(View.GONE);
+ }
+ // Activity chooser content.
+ if (mDefaultActivityButton.getVisibility() == VISIBLE) {
+ mActivityChooserContent.setBackgroundDrawable(mActivityChooserContentBackground);
+ } else {
+ mActivityChooserContent.setBackgroundDrawable(null);
+ }
+ }
+
+ /**
+ * Interface implementation to avoid publishing them in the APIs.
+ */
+ private class Callbacks implements AdapterView.OnItemClickListener,
+ View.OnClickListener, View.OnLongClickListener, PopupWindow.OnDismissListener {
+
+ // AdapterView#OnItemClickListener
+ public void onItemClick(AdapterView> parent, View view, int position, long id) {
+ ActivityChooserViewAdapter adapter = (ActivityChooserViewAdapter) parent.getAdapter();
+ final int itemViewType = adapter.getItemViewType(position);
+ switch (itemViewType) {
+ case ActivityChooserViewAdapter.ITEM_VIEW_TYPE_FOOTER: {
+ showPopupUnchecked(ActivityChooserViewAdapter.MAX_ACTIVITY_COUNT_UNLIMITED);
+ } break;
+ case ActivityChooserViewAdapter.ITEM_VIEW_TYPE_ACTIVITY: {
+ dismissPopup();
+ if (mIsSelectingDefaultActivity) {
+ // The item at position zero is the default already.
+ if (position > 0) {
+ mAdapter.getDataModel().setDefaultActivity(position);
+ }
+ } else {
+ // If the default target is not shown in the list, the first
+ // item in the model is default action => adjust index
+ position = mAdapter.getShowDefaultActivity() ? position : position + 1;
+ Intent launchIntent = mAdapter.getDataModel().chooseActivity(position);
+ if (launchIntent != null) {
+ mContext.startActivity(launchIntent);
+ }
+ }
+ } break;
+ default:
+ throw new IllegalArgumentException();
+ }
+ }
+
+ // View.OnClickListener
+ public void onClick(View view) {
+ if (view == mDefaultActivityButton) {
+ dismissPopup();
+ ResolveInfo defaultActivity = mAdapter.getDefaultActivity();
+ final int index = mAdapter.getDataModel().getActivityIndex(defaultActivity);
+ Intent launchIntent = mAdapter.getDataModel().chooseActivity(index);
+ if (launchIntent != null) {
+ mContext.startActivity(launchIntent);
+ }
+ } else if (view == mExpandActivityOverflowButton) {
+ mIsSelectingDefaultActivity = false;
+ showPopupUnchecked(mInitialActivityCount);
+ } else {
+ throw new IllegalArgumentException();
+ }
+ }
+
+ // OnLongClickListener#onLongClick
+ @Override
+ public boolean onLongClick(View view) {
+ if (view == mDefaultActivityButton) {
+ if (mAdapter.getCount() > 0) {
+ mIsSelectingDefaultActivity = true;
+ showPopupUnchecked(mInitialActivityCount);
+ }
+ } else {
+ throw new IllegalArgumentException();
+ }
+ return true;
+ }
+
+ // PopUpWindow.OnDismissListener#onDismiss
+ public void onDismiss() {
+ notifyOnDismissListener();
+ if (mProvider != null) {
+ mProvider.subUiVisibilityChanged(false);
+ }
+ }
+
+ private void notifyOnDismissListener() {
+ if (mOnDismissListener != null) {
+ mOnDismissListener.onDismiss();
+ }
+ }
+ }
+
+ private static class SetActivated {
+ public static void invoke(View view, boolean activated) {
+ view.setActivated(activated);
+ }
+ }
+
+ private static final boolean IS_HONEYCOMB = Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB;
+
+ /**
+ * Adapter for backing the list of activities shown in the popup.
+ */
+ private class ActivityChooserViewAdapter extends BaseAdapter {
+
+ public static final int MAX_ACTIVITY_COUNT_UNLIMITED = Integer.MAX_VALUE;
+
+ public static final int MAX_ACTIVITY_COUNT_DEFAULT = 4;
+
+ private static final int ITEM_VIEW_TYPE_ACTIVITY = 0;
+
+ private static final int ITEM_VIEW_TYPE_FOOTER = 1;
+
+ private static final int ITEM_VIEW_TYPE_COUNT = 3;
+
+ private ActivityChooserModel mDataModel;
+
+ private int mMaxActivityCount = MAX_ACTIVITY_COUNT_DEFAULT;
+
+ private boolean mShowDefaultActivity;
+
+ private boolean mHighlightDefaultActivity;
+
+ private boolean mShowFooterView;
+
+ public void setDataModel(ActivityChooserModel dataModel) {
+ ActivityChooserModel oldDataModel = mAdapter.getDataModel();
+ if (oldDataModel != null && isShown()) {
+ oldDataModel.unregisterObserver(mModelDataSetOberver);
+ }
+ mDataModel = dataModel;
+ if (dataModel != null && isShown()) {
+ dataModel.registerObserver(mModelDataSetOberver);
+ }
+ notifyDataSetChanged();
+ }
+
+ @Override
+ public int getItemViewType(int position) {
+ if (mShowFooterView && position == getCount() - 1) {
+ return ITEM_VIEW_TYPE_FOOTER;
+ } else {
+ return ITEM_VIEW_TYPE_ACTIVITY;
+ }
+ }
+
+ @Override
+ public int getViewTypeCount() {
+ return ITEM_VIEW_TYPE_COUNT;
+ }
+
+ public int getCount() {
+ int count = 0;
+ int activityCount = mDataModel.getActivityCount();
+ if (!mShowDefaultActivity && mDataModel.getDefaultActivity() != null) {
+ activityCount--;
+ }
+ count = Math.min(activityCount, mMaxActivityCount);
+ if (mShowFooterView) {
+ count++;
+ }
+ return count;
+ }
+
+ public Object getItem(int position) {
+ final int itemViewType = getItemViewType(position);
+ switch (itemViewType) {
+ case ITEM_VIEW_TYPE_FOOTER:
+ return null;
+ case ITEM_VIEW_TYPE_ACTIVITY:
+ if (!mShowDefaultActivity && mDataModel.getDefaultActivity() != null) {
+ position++;
+ }
+ return mDataModel.getActivity(position);
+ default:
+ throw new IllegalArgumentException();
+ }
+ }
+
+ public long getItemId(int position) {
+ return position;
+ }
+
+ public View getView(int position, View convertView, ViewGroup parent) {
+ final int itemViewType = getItemViewType(position);
+ switch (itemViewType) {
+ case ITEM_VIEW_TYPE_FOOTER:
+ if (convertView == null || convertView.getId() != ITEM_VIEW_TYPE_FOOTER) {
+ convertView = LayoutInflater.from(getContext()).inflate(
+ R.layout.abs__activity_chooser_view_list_item, parent, false);
+ convertView.setId(ITEM_VIEW_TYPE_FOOTER);
+ TextView titleView = (TextView) convertView.findViewById(R.id.abs__title);
+ titleView.setText(mContext.getString(
+ R.string.abs__activity_chooser_view_see_all));
+ }
+ return convertView;
+ case ITEM_VIEW_TYPE_ACTIVITY:
+ if (convertView == null || convertView.getId() != R.id.abs__list_item) {
+ convertView = LayoutInflater.from(getContext()).inflate(
+ R.layout.abs__activity_chooser_view_list_item, parent, false);
+ }
+ PackageManager packageManager = mContext.getPackageManager();
+ // Set the icon
+ ImageView iconView = (ImageView) convertView.findViewById(R.id.abs__icon);
+ ResolveInfo activity = (ResolveInfo) getItem(position);
+ iconView.setImageDrawable(activity.loadIcon(packageManager));
+ // Set the title.
+ TextView titleView = (TextView) convertView.findViewById(R.id.abs__title);
+ titleView.setText(activity.loadLabel(packageManager));
+ if (IS_HONEYCOMB) {
+ // Highlight the default.
+ if (mShowDefaultActivity && position == 0 && mHighlightDefaultActivity) {
+ SetActivated.invoke(convertView, true);
+ } else {
+ SetActivated.invoke(convertView, false);
+ }
+ }
+ return convertView;
+ default:
+ throw new IllegalArgumentException();
+ }
+ }
+
+ public int measureContentWidth() {
+ // The user may have specified some of the target not to be shown but we
+ // want to measure all of them since after expansion they should fit.
+ final int oldMaxActivityCount = mMaxActivityCount;
+ mMaxActivityCount = MAX_ACTIVITY_COUNT_UNLIMITED;
+
+ int contentWidth = 0;
+ View itemView = null;
+
+ final int widthMeasureSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);
+ final int heightMeasureSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);
+ final int count = getCount();
+
+ for (int i = 0; i < count; i++) {
+ itemView = getView(i, itemView, null);
+ itemView.measure(widthMeasureSpec, heightMeasureSpec);
+ contentWidth = Math.max(contentWidth, itemView.getMeasuredWidth());
+ }
+
+ mMaxActivityCount = oldMaxActivityCount;
+
+ return contentWidth;
+ }
+
+ public void setMaxActivityCount(int maxActivityCount) {
+ if (mMaxActivityCount != maxActivityCount) {
+ mMaxActivityCount = maxActivityCount;
+ notifyDataSetChanged();
+ }
+ }
+
+ public ResolveInfo getDefaultActivity() {
+ return mDataModel.getDefaultActivity();
+ }
+
+ public void setShowFooterView(boolean showFooterView) {
+ if (mShowFooterView != showFooterView) {
+ mShowFooterView = showFooterView;
+ notifyDataSetChanged();
+ }
+ }
+
+ public int getActivityCount() {
+ return mDataModel.getActivityCount();
+ }
+
+ public int getHistorySize() {
+ return mDataModel.getHistorySize();
+ }
+
+ public int getMaxActivityCount() {
+ return mMaxActivityCount;
+ }
+
+ public ActivityChooserModel getDataModel() {
+ return mDataModel;
+ }
+
+ public void setShowDefaultActivity(boolean showDefaultActivity,
+ boolean highlightDefaultActivity) {
+ if (mShowDefaultActivity != showDefaultActivity
+ || mHighlightDefaultActivity != highlightDefaultActivity) {
+ mShowDefaultActivity = showDefaultActivity;
+ mHighlightDefaultActivity = highlightDefaultActivity;
+ notifyDataSetChanged();
+ }
+ }
+
+ public boolean getShowDefaultActivity() {
+ return mShowDefaultActivity;
+ }
+ }
+}
diff --git a/libs/ActionBarSherlock/src/com/actionbarsherlock/widget/ShareActionProvider.java b/libs/ActionBarSherlock/src/com/actionbarsherlock/widget/ShareActionProvider.java
new file mode 100644
index 0000000..83e9f0c
--- /dev/null
+++ b/libs/ActionBarSherlock/src/com/actionbarsherlock/widget/ShareActionProvider.java
@@ -0,0 +1,316 @@
+/*
+ * Copyright (C) 2011 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 com.actionbarsherlock.widget;
+
+import android.content.Context;
+import android.content.Intent;
+import android.content.pm.PackageManager;
+import android.content.pm.ResolveInfo;
+import android.graphics.drawable.Drawable;
+import android.util.TypedValue;
+import android.view.View;
+
+import com.actionbarsherlock.R;
+import com.actionbarsherlock.view.ActionProvider;
+import com.actionbarsherlock.view.Menu;
+import com.actionbarsherlock.view.MenuItem;
+import com.actionbarsherlock.view.MenuItem.OnMenuItemClickListener;
+import com.actionbarsherlock.view.SubMenu;
+import com.actionbarsherlock.widget.ActivityChooserModel.OnChooseActivityListener;
+
+/**
+ * This is a provider for a share action. It is responsible for creating views
+ * that enable data sharing and also to show a sub menu with sharing activities
+ * if the hosting item is placed on the overflow menu.
+ *
+ * Here is how to use the action provider with custom backing file in a {@link MenuItem}:
+ *
+ *
+ *
+ *
+ * // In Activity#onCreateOptionsMenu
+ * public boolean onCreateOptionsMenu(Menu menu) {
+ * // Get the menu item.
+ * MenuItem menuItem = menu.findItem(R.id.my_menu_item);
+ * // Get the provider and hold onto it to set/change the share intent.
+ * mShareActionProvider = (ShareActionProvider) menuItem.getActionProvider();
+ * // Set history different from the default before getting the action
+ * // view since a call to {@link MenuItem#getActionView() MenuItem.getActionView()} calls
+ * // {@link ActionProvider#onCreateActionView()} which uses the backing file name. Omit this
+ * // line if using the default share history file is desired.
+ * mShareActionProvider.setShareHistoryFileName("custom_share_history.xml");
+ * . . .
+ * }
+ *
+ * // Somewhere in the application.
+ * public void doShare(Intent shareIntent) {
+ * // When you want to share set the share intent.
+ * mShareActionProvider.setShareIntent(shareIntent);
+ * }
+ *
+ *
+ *
+ *
+ * Note: While the sample snippet demonstrates how to use this provider
+ * in the context of a menu item, the use of the provider is not limited to menu items.
+ *
+ *
+ * @see ActionProvider
+ */
+public class ShareActionProvider extends ActionProvider {
+
+ /**
+ * Listener for the event of selecting a share target.
+ */
+ public interface OnShareTargetSelectedListener {
+
+ /**
+ * Called when a share target has been selected. The client can
+ * decide whether to handle the intent or rely on the default
+ * behavior which is launching it.
+ *
+ * Note: Modifying the intent is not permitted and
+ * any changes to the latter will be ignored.
+ *
+ *
+ * @param source The source of the notification.
+ * @param intent The intent for launching the chosen share target.
+ * @return Whether the client has handled the intent.
+ */
+ public boolean onShareTargetSelected(ShareActionProvider source, Intent intent);
+ }
+
+ /**
+ * The default for the maximal number of activities shown in the sub-menu.
+ */
+ private static final int DEFAULT_INITIAL_ACTIVITY_COUNT = 4;
+
+ /**
+ * The the maximum number activities shown in the sub-menu.
+ */
+ private int mMaxShownActivityCount = DEFAULT_INITIAL_ACTIVITY_COUNT;
+
+ /**
+ * Listener for handling menu item clicks.
+ */
+ private final ShareMenuItemOnMenuItemClickListener mOnMenuItemClickListener =
+ new ShareMenuItemOnMenuItemClickListener();
+
+ /**
+ * The default name for storing share history.
+ */
+ public static final String DEFAULT_SHARE_HISTORY_FILE_NAME = "share_history.xml";
+
+ /**
+ * Context for accessing resources.
+ */
+ private final Context mContext;
+
+ /**
+ * The name of the file with share history data.
+ */
+ private String mShareHistoryFileName = DEFAULT_SHARE_HISTORY_FILE_NAME;
+
+ private OnShareTargetSelectedListener mOnShareTargetSelectedListener;
+
+ private OnChooseActivityListener mOnChooseActivityListener;
+
+ /**
+ * Creates a new instance.
+ *
+ * @param context Context for accessing resources.
+ */
+ public ShareActionProvider(Context context) {
+ super(context);
+ mContext = context;
+ }
+
+ /**
+ * Sets a listener to be notified when a share target has been selected.
+ * The listener can optionally decide to handle the selection and
+ * not rely on the default behavior which is to launch the activity.
+ *
+ * Note: If you choose the backing share history file
+ * you will still be notified in this callback.
+ *
+ * @param listener The listener.
+ */
+ public void setOnShareTargetSelectedListener(OnShareTargetSelectedListener listener) {
+ mOnShareTargetSelectedListener = listener;
+ setActivityChooserPolicyIfNeeded();
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public View onCreateActionView() {
+ // Create the view and set its data model.
+ ActivityChooserModel dataModel = ActivityChooserModel.get(mContext, mShareHistoryFileName);
+ ActivityChooserView activityChooserView = new ActivityChooserView(mContext);
+ activityChooserView.setActivityChooserModel(dataModel);
+
+ // Lookup and set the expand action icon.
+ TypedValue outTypedValue = new TypedValue();
+ mContext.getTheme().resolveAttribute(R.attr.actionModeShareDrawable, outTypedValue, true);
+ Drawable drawable = mContext.getResources().getDrawable(outTypedValue.resourceId);
+ activityChooserView.setExpandActivityOverflowButtonDrawable(drawable);
+ activityChooserView.setProvider(this);
+
+ // Set content description.
+ activityChooserView.setDefaultActionButtonContentDescription(
+ R.string.abs__shareactionprovider_share_with_application);
+ activityChooserView.setExpandActivityOverflowButtonContentDescription(
+ R.string.abs__shareactionprovider_share_with);
+
+ return activityChooserView;
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public boolean hasSubMenu() {
+ return true;
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public void onPrepareSubMenu(SubMenu subMenu) {
+ // Clear since the order of items may change.
+ subMenu.clear();
+
+ ActivityChooserModel dataModel = ActivityChooserModel.get(mContext, mShareHistoryFileName);
+ PackageManager packageManager = mContext.getPackageManager();
+
+ final int expandedActivityCount = dataModel.getActivityCount();
+ final int collapsedActivityCount = Math.min(expandedActivityCount, mMaxShownActivityCount);
+
+ // Populate the sub-menu with a sub set of the activities.
+ for (int i = 0; i < collapsedActivityCount; i++) {
+ ResolveInfo activity = dataModel.getActivity(i);
+ subMenu.add(0, i, i, activity.loadLabel(packageManager))
+ .setIcon(activity.loadIcon(packageManager))
+ .setOnMenuItemClickListener(mOnMenuItemClickListener);
+ }
+
+ if (collapsedActivityCount < expandedActivityCount) {
+ // Add a sub-menu for showing all activities as a list item.
+ SubMenu expandedSubMenu = subMenu.addSubMenu(Menu.NONE, collapsedActivityCount,
+ collapsedActivityCount,
+ mContext.getString(R.string.abs__activity_chooser_view_see_all));
+ for (int i = 0; i < expandedActivityCount; i++) {
+ ResolveInfo activity = dataModel.getActivity(i);
+ expandedSubMenu.add(0, i, i, activity.loadLabel(packageManager))
+ .setIcon(activity.loadIcon(packageManager))
+ .setOnMenuItemClickListener(mOnMenuItemClickListener);
+ }
+ }
+ }
+
+ /**
+ * Sets the file name of a file for persisting the share history which
+ * history will be used for ordering share targets. This file will be used
+ * for all view created by {@link #onCreateActionView()}. Defaults to
+ * {@link #DEFAULT_SHARE_HISTORY_FILE_NAME}. Set to null
+ * if share history should not be persisted between sessions.
+ *
+ * Note: The history file name can be set any time, however
+ * only the action views created by {@link #onCreateActionView()} after setting
+ * the file name will be backed by the provided file.
+ *
+ *
+ * @param shareHistoryFile The share history file name.
+ */
+ public void setShareHistoryFileName(String shareHistoryFile) {
+ mShareHistoryFileName = shareHistoryFile;
+ setActivityChooserPolicyIfNeeded();
+ }
+
+ /**
+ * Sets an intent with information about the share action. Here is a
+ * sample for constructing a share intent:
+ *
+ *
+ *
+ * Intent shareIntent = new Intent(Intent.ACTION_SEND);
+ * shareIntent.setType("image/*");
+ * Uri uri = Uri.fromFile(new File(getFilesDir(), "foo.jpg"));
+ * shareIntent.putExtra(Intent.EXTRA_STREAM, uri.toString());
+ *
+ *
+ *
+ *
+ * @param shareIntent The share intent.
+ *
+ * @see Intent#ACTION_SEND
+ * @see Intent#ACTION_SEND_MULTIPLE
+ */
+ public void setShareIntent(Intent shareIntent) {
+ ActivityChooserModel dataModel = ActivityChooserModel.get(mContext,
+ mShareHistoryFileName);
+ dataModel.setIntent(shareIntent);
+ }
+
+ /**
+ * Reusable listener for handling share item clicks.
+ */
+ private class ShareMenuItemOnMenuItemClickListener implements OnMenuItemClickListener {
+ @Override
+ public boolean onMenuItemClick(MenuItem item) {
+ ActivityChooserModel dataModel = ActivityChooserModel.get(mContext,
+ mShareHistoryFileName);
+ final int itemId = item.getItemId();
+ Intent launchIntent = dataModel.chooseActivity(itemId);
+ if (launchIntent != null) {
+ mContext.startActivity(launchIntent);
+ }
+ return true;
+ }
+ }
+
+ /**
+ * Set the activity chooser policy of the model backed by the current
+ * share history file if needed which is if there is a registered callback.
+ */
+ private void setActivityChooserPolicyIfNeeded() {
+ if (mOnShareTargetSelectedListener == null) {
+ return;
+ }
+ if (mOnChooseActivityListener == null) {
+ mOnChooseActivityListener = new ShareAcitivityChooserModelPolicy();
+ }
+ ActivityChooserModel dataModel = ActivityChooserModel.get(mContext, mShareHistoryFileName);
+ dataModel.setOnChooseActivityListener(mOnChooseActivityListener);
+ }
+
+ /**
+ * Policy that delegates to the {@link OnShareTargetSelectedListener}, if such.
+ */
+ private class ShareAcitivityChooserModelPolicy implements OnChooseActivityListener {
+ @Override
+ public boolean onChooseActivity(ActivityChooserModel host, Intent intent) {
+ if (mOnShareTargetSelectedListener != null) {
+ return mOnShareTargetSelectedListener.onShareTargetSelected(
+ ShareActionProvider.this, intent);
+ }
+ return false;
+ }
+ }
+}