code
stringlengths
3
1.18M
language
stringclasses
1 value
package com.actionbarsherlock.internal.nineoldandroids.widget; import android.content.Context; import android.widget.HorizontalScrollView; import com.actionbarsherlock.internal.nineoldandroids.view.animation.AnimatorProxy; public class NineHorizontalScrollView extends HorizontalScrollView { private final AnimatorProxy mProxy; public NineHorizontalScrollView(Context context) { super(context); mProxy = AnimatorProxy.NEEDS_PROXY ? AnimatorProxy.wrap(this) : null; } @Override public void setVisibility(int visibility) { if (mProxy != null) { if (visibility == GONE) { clearAnimation(); } else if (visibility == VISIBLE) { setAnimation(mProxy); } } super.setVisibility(visibility); } public float getAlpha() { if (AnimatorProxy.NEEDS_PROXY) { return mProxy.getAlpha(); } else { return super.getAlpha(); } } public void setAlpha(float alpha) { if (AnimatorProxy.NEEDS_PROXY) { mProxy.setAlpha(alpha); } else { super.setAlpha(alpha); } } }
Java
package com.actionbarsherlock.internal.nineoldandroids.widget; import android.content.Context; import android.util.AttributeSet; import android.widget.LinearLayout; import com.actionbarsherlock.internal.nineoldandroids.view.animation.AnimatorProxy; public class NineLinearLayout extends LinearLayout { private final AnimatorProxy mProxy; public NineLinearLayout(Context context) { super(context); mProxy = AnimatorProxy.NEEDS_PROXY ? AnimatorProxy.wrap(this) : null; } public NineLinearLayout(Context context, AttributeSet attrs) { super(context, attrs); mProxy = AnimatorProxy.NEEDS_PROXY ? AnimatorProxy.wrap(this) : null; } public NineLinearLayout(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); mProxy = AnimatorProxy.NEEDS_PROXY ? AnimatorProxy.wrap(this) : null; } @Override public void setVisibility(int visibility) { if (mProxy != null) { if (visibility == GONE) { clearAnimation(); } else if (visibility == VISIBLE) { setAnimation(mProxy); } } super.setVisibility(visibility); } public float getAlpha() { if (AnimatorProxy.NEEDS_PROXY) { return mProxy.getAlpha(); } else { return super.getAlpha(); } } public void setAlpha(float alpha) { if (AnimatorProxy.NEEDS_PROXY) { mProxy.setAlpha(alpha); } else { super.setAlpha(alpha); } } public float getTranslationX() { if (AnimatorProxy.NEEDS_PROXY) { return mProxy.getTranslationX(); } else { return super.getTranslationX(); } } public void setTranslationX(float translationX) { if (AnimatorProxy.NEEDS_PROXY) { mProxy.setTranslationX(translationX); } else { super.setTranslationX(translationX); } } }
Java
package com.actionbarsherlock.internal.nineoldandroids.widget; import android.content.Context; import android.util.AttributeSet; import android.widget.FrameLayout; import com.actionbarsherlock.internal.nineoldandroids.view.animation.AnimatorProxy; public class NineFrameLayout extends FrameLayout { private final AnimatorProxy mProxy; public NineFrameLayout(Context context) { super(context); mProxy = AnimatorProxy.NEEDS_PROXY ? AnimatorProxy.wrap(this) : null; } public NineFrameLayout(Context context, AttributeSet attrs) { super(context, attrs); mProxy = AnimatorProxy.NEEDS_PROXY ? AnimatorProxy.wrap(this) : null; } public NineFrameLayout(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); mProxy = AnimatorProxy.NEEDS_PROXY ? AnimatorProxy.wrap(this) : null; } @Override public void setVisibility(int visibility) { if (mProxy != null) { if (visibility == GONE) { clearAnimation(); } else if (visibility == VISIBLE) { setAnimation(mProxy); } } super.setVisibility(visibility); } public float getAlpha() { if (AnimatorProxy.NEEDS_PROXY) { return mProxy.getAlpha(); } else { return super.getAlpha(); } } public void setAlpha(float alpha) { if (AnimatorProxy.NEEDS_PROXY) { mProxy.setAlpha(alpha); } else { super.setAlpha(alpha); } } public float getTranslationY() { if (AnimatorProxy.NEEDS_PROXY) { return mProxy.getTranslationY(); } else { return super.getTranslationY(); } } public void setTranslationY(float translationY) { if (AnimatorProxy.NEEDS_PROXY) { mProxy.setTranslationY(translationY); } else { super.setTranslationY(translationY); } } }
Java
package com.actionbarsherlock.internal.nineoldandroids.view.animation; import java.lang.ref.WeakReference; import java.util.WeakHashMap; import android.graphics.Matrix; import android.graphics.RectF; import android.os.Build; import android.util.FloatMath; import android.view.View; import android.view.animation.Animation; import android.view.animation.Transformation; public final class AnimatorProxy extends Animation { public static final boolean NEEDS_PROXY = Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB; private static final WeakHashMap<View, AnimatorProxy> PROXIES = new WeakHashMap<View, AnimatorProxy>(); public static AnimatorProxy wrap(View view) { AnimatorProxy proxy = PROXIES.get(view); if (proxy == null) { proxy = new AnimatorProxy(view); PROXIES.put(view, proxy); } return proxy; } private final WeakReference<View> mView; private float mAlpha = 1; private float mScaleX = 1; private float mScaleY = 1; private float mTranslationX; private float mTranslationY; private final RectF mBefore = new RectF(); private final RectF mAfter = new RectF(); private final Matrix mTempMatrix = new Matrix(); private AnimatorProxy(View view) { setDuration(0); //perform transformation immediately setFillAfter(true); //persist transformation beyond duration view.setAnimation(this); mView = new WeakReference<View>(view); } public float getAlpha() { return mAlpha; } public void setAlpha(float alpha) { if (mAlpha != alpha) { mAlpha = alpha; View view = mView.get(); if (view != null) { view.invalidate(); } } } public float getScaleX() { return mScaleX; } public void setScaleX(float scaleX) { if (mScaleX != scaleX) { prepareForUpdate(); mScaleX = scaleX; invalidateAfterUpdate(); } } public float getScaleY() { return mScaleY; } public void setScaleY(float scaleY) { if (mScaleY != scaleY) { prepareForUpdate(); mScaleY = scaleY; invalidateAfterUpdate(); } } public int getScrollX() { View view = mView.get(); if (view == null) { return 0; } return view.getScrollX(); } public void setScrollX(int value) { View view = mView.get(); if (view != null) { view.scrollTo(value, view.getScrollY()); } } public int getScrollY() { View view = mView.get(); if (view == null) { return 0; } return view.getScrollY(); } public void setScrollY(int value) { View view = mView.get(); if (view != null) { view.scrollTo(view.getScrollY(), value); } } public float getTranslationX() { return mTranslationX; } public void setTranslationX(float translationX) { if (mTranslationX != translationX) { prepareForUpdate(); mTranslationX = translationX; invalidateAfterUpdate(); } } public float getTranslationY() { return mTranslationY; } public void setTranslationY(float translationY) { if (mTranslationY != translationY) { prepareForUpdate(); mTranslationY = translationY; invalidateAfterUpdate(); } } private void prepareForUpdate() { View view = mView.get(); if (view != null) { computeRect(mBefore, view); } } private void invalidateAfterUpdate() { View view = mView.get(); if (view == null) { return; } View parent = (View)view.getParent(); if (parent == null) { return; } view.setAnimation(this); final RectF after = mAfter; computeRect(after, view); after.union(mBefore); parent.invalidate( (int) FloatMath.floor(after.left), (int) FloatMath.floor(after.top), (int) FloatMath.ceil(after.right), (int) FloatMath.ceil(after.bottom)); } private void computeRect(final RectF r, View view) { // compute current rectangle according to matrix transformation final float w = view.getWidth(); final float h = view.getHeight(); // use a rectangle at 0,0 to make sure we don't run into issues with scaling r.set(0, 0, w, h); final Matrix m = mTempMatrix; m.reset(); transformMatrix(m, view); mTempMatrix.mapRect(r); r.offset(view.getLeft(), view.getTop()); // Straighten coords if rotations flipped them if (r.right < r.left) { final float f = r.right; r.right = r.left; r.left = f; } if (r.bottom < r.top) { final float f = r.top; r.top = r.bottom; r.bottom = f; } } private void transformMatrix(Matrix m, View view) { final float w = view.getWidth(); final float h = view.getHeight(); final float sX = mScaleX; final float sY = mScaleY; if ((sX != 1.0f) || (sY != 1.0f)) { final float deltaSX = ((sX * w) - w) / 2f; final float deltaSY = ((sY * h) - h) / 2f; m.postScale(sX, sY); m.postTranslate(-deltaSX, -deltaSY); } m.postTranslate(mTranslationX, mTranslationY); } @Override protected void applyTransformation(float interpolatedTime, Transformation t) { View view = mView.get(); if (view != null) { t.setAlpha(mAlpha); transformMatrix(t.getMatrix(), view); } } @Override public void reset() { /* Do nothing. */ } }
Java
package com.actionbarsherlock.internal.nineoldandroids.view; import android.content.Context; import android.util.AttributeSet; import android.view.ViewGroup; import com.actionbarsherlock.internal.nineoldandroids.view.animation.AnimatorProxy; public abstract class NineViewGroup extends ViewGroup { private final AnimatorProxy mProxy; public NineViewGroup(Context context) { super(context); mProxy = AnimatorProxy.NEEDS_PROXY ? AnimatorProxy.wrap(this) : null; } public NineViewGroup(Context context, AttributeSet attrs) { super(context, attrs); mProxy = AnimatorProxy.NEEDS_PROXY ? AnimatorProxy.wrap(this) : null; } public NineViewGroup(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); mProxy = AnimatorProxy.NEEDS_PROXY ? AnimatorProxy.wrap(this) : null; } @Override public void setVisibility(int visibility) { if (mProxy != null) { if (visibility == GONE) { clearAnimation(); } else if (visibility == VISIBLE) { setAnimation(mProxy); } } super.setVisibility(visibility); } public float getAlpha() { if (AnimatorProxy.NEEDS_PROXY) { return mProxy.getAlpha(); } else { return super.getAlpha(); } } public void setAlpha(float alpha) { if (AnimatorProxy.NEEDS_PROXY) { mProxy.setAlpha(alpha); } else { super.setAlpha(alpha); } } public float getTranslationX() { if (AnimatorProxy.NEEDS_PROXY) { return mProxy.getTranslationX(); } else { return super.getTranslationX(); } } public void setTranslationX(float translationX) { if (AnimatorProxy.NEEDS_PROXY) { mProxy.setTranslationX(translationX); } else { super.setTranslationX(translationX); } } public float getTranslationY() { if (AnimatorProxy.NEEDS_PROXY) { return mProxy.getTranslationY(); } else { return super.getTranslationY(); } } public void setTranslationY(float translationY) { if (AnimatorProxy.NEEDS_PROXY) { mProxy.setTranslationY(translationY); } else { super.setTranslationY(translationY); } } }
Java
package com.actionbarsherlock.internal.widget; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Canvas; import android.graphics.drawable.Drawable; import android.util.AttributeSet; import android.view.View; import com.actionbarsherlock.internal.nineoldandroids.widget.NineLinearLayout; /** * A simple extension of a regular linear layout that supports the divider API * of Android 4.0+. The dividers are added adjacent to the children by changing * their layout params. If you need to rely on the margins which fall in the * same orientation as the layout you should wrap the child in a simple * {@link android.widget.FrameLayout} so it can receive the margin. */ public class IcsLinearLayout extends NineLinearLayout { private static final int[] LinearLayout = new int[] { /* 0 */ android.R.attr.divider, /* 1 */ android.R.attr.showDividers, /* 2 */ android.R.attr.dividerPadding, }; private static final int LinearLayout_divider = 0; private static final int LinearLayout_showDividers = 1; private static final int LinearLayout_dividerPadding = 2; /** * Don't show any dividers. */ public static final int SHOW_DIVIDER_NONE = 0; /** * Show a divider at the beginning of the group. */ public static final int SHOW_DIVIDER_BEGINNING = 1; /** * Show dividers between each item in the group. */ public static final int SHOW_DIVIDER_MIDDLE = 2; /** * Show a divider at the end of the group. */ public static final int SHOW_DIVIDER_END = 4; private Drawable mDivider; private int mDividerWidth; private int mDividerHeight; private int mShowDividers; private int mDividerPadding; public IcsLinearLayout(Context context, AttributeSet attrs) { super(context, attrs); TypedArray a = context.obtainStyledAttributes(attrs, /*com.android.internal.R.styleable.*/LinearLayout); setDividerDrawable(a.getDrawable(/*com.android.internal.R.styleable.*/LinearLayout_divider)); mShowDividers = a.getInt(/*com.android.internal.R.styleable.*/LinearLayout_showDividers, SHOW_DIVIDER_NONE); mDividerPadding = a.getDimensionPixelSize(/*com.android.internal.R.styleable.*/LinearLayout_dividerPadding, 0); a.recycle(); } /** * Set how dividers should be shown between items in this layout * * @param showDividers One or more of {@link #SHOW_DIVIDER_BEGINNING}, * {@link #SHOW_DIVIDER_MIDDLE}, or {@link #SHOW_DIVIDER_END}, * or {@link #SHOW_DIVIDER_NONE} to show no dividers. */ public void setShowDividers(int showDividers) { if (showDividers != mShowDividers) { requestLayout(); invalidate(); //XXX This is required if you are toggling a divider off } mShowDividers = showDividers; } /** * @return A flag set indicating how dividers should be shown around items. * @see #setShowDividers(int) */ public int getShowDividers() { return mShowDividers; } /** * Set a drawable to be used as a divider between items. * @param divider Drawable that will divide each item. * @see #setShowDividers(int) */ public void setDividerDrawable(Drawable divider) { if (divider == mDivider) { return; } mDivider = divider; if (divider != null) { mDividerWidth = divider.getIntrinsicWidth(); mDividerHeight = divider.getIntrinsicHeight(); } else { mDividerWidth = 0; mDividerHeight = 0; } setWillNotDraw(divider == null); requestLayout(); } /** * Set padding displayed on both ends of dividers. * * @param padding Padding value in pixels that will be applied to each end * * @see #setShowDividers(int) * @see #setDividerDrawable(Drawable) * @see #getDividerPadding() */ public void setDividerPadding(int padding) { mDividerPadding = padding; } /** * Get the padding size used to inset dividers in pixels * * @see #setShowDividers(int) * @see #setDividerDrawable(Drawable) * @see #setDividerPadding(int) */ public int getDividerPadding() { return mDividerPadding; } /** * Get the width of the current divider drawable. * * @hide Used internally by framework. */ public int getDividerWidth() { return mDividerWidth; } @Override protected void measureChildWithMargins(View child, int parentWidthMeasureSpec, int widthUsed, int parentHeightMeasureSpec, int heightUsed) { final int index = indexOfChild(child); final int orientation = getOrientation(); final LayoutParams params = (LayoutParams) child.getLayoutParams(); if (hasDividerBeforeChildAt(index)) { if (orientation == VERTICAL) { //Account for the divider by pushing everything up params.topMargin = mDividerHeight; } else { //Account for the divider by pushing everything left params.leftMargin = mDividerWidth; } } final int count = getChildCount(); if (index == count - 1) { if (hasDividerBeforeChildAt(count)) { if (orientation == VERTICAL) { params.bottomMargin = mDividerHeight; } else { params.rightMargin = mDividerWidth; } } } super.measureChildWithMargins(child, parentWidthMeasureSpec, widthUsed, parentHeightMeasureSpec, heightUsed); } @Override protected void onDraw(Canvas canvas) { if (mDivider != null) { if (getOrientation() == VERTICAL) { drawDividersVertical(canvas); } else { drawDividersHorizontal(canvas); } } super.onDraw(canvas); } void drawDividersVertical(Canvas canvas) { final int count = getChildCount(); for (int i = 0; i < count; i++) { final View child = getChildAt(i); if (child != null && child.getVisibility() != GONE) { if (hasDividerBeforeChildAt(i)) { final LayoutParams lp = (LayoutParams) child.getLayoutParams(); final int top = child.getTop() - lp.topMargin/* - mDividerHeight*/; drawHorizontalDivider(canvas, top); } } } if (hasDividerBeforeChildAt(count)) { final View child = getChildAt(count - 1); int bottom = 0; if (child == null) { bottom = getHeight() - getPaddingBottom() - mDividerHeight; } else { final LayoutParams lp = (LayoutParams) child.getLayoutParams(); bottom = child.getBottom()/* + lp.bottomMargin*/; } drawHorizontalDivider(canvas, bottom); } } void drawDividersHorizontal(Canvas canvas) { final int count = getChildCount(); for (int i = 0; i < count; i++) { final View child = getChildAt(i); if (child != null && child.getVisibility() != GONE) { if (hasDividerBeforeChildAt(i)) { final LayoutParams lp = (LayoutParams) child.getLayoutParams(); final int left = child.getLeft() - lp.leftMargin/* - mDividerWidth*/; drawVerticalDivider(canvas, left); } } } if (hasDividerBeforeChildAt(count)) { final View child = getChildAt(count - 1); int right = 0; if (child == null) { right = getWidth() - getPaddingRight() - mDividerWidth; } else { final LayoutParams lp = (LayoutParams) child.getLayoutParams(); right = child.getRight()/* + lp.rightMargin*/; } drawVerticalDivider(canvas, right); } } void drawHorizontalDivider(Canvas canvas, int top) { mDivider.setBounds(getPaddingLeft() + mDividerPadding, top, getWidth() - getPaddingRight() - mDividerPadding, top + mDividerHeight); mDivider.draw(canvas); } void drawVerticalDivider(Canvas canvas, int left) { mDivider.setBounds(left, getPaddingTop() + mDividerPadding, left + mDividerWidth, getHeight() - getPaddingBottom() - mDividerPadding); mDivider.draw(canvas); } /** * Determines where to position dividers between children. * * @param childIndex Index of child to check for preceding divider * @return true if there should be a divider before the child at childIndex * @hide Pending API consideration. Currently only used internally by the system. */ protected boolean hasDividerBeforeChildAt(int childIndex) { if (childIndex == 0) { return (mShowDividers & SHOW_DIVIDER_BEGINNING) != 0; } else if (childIndex == getChildCount()) { return (mShowDividers & SHOW_DIVIDER_END) != 0; } else if ((mShowDividers & SHOW_DIVIDER_MIDDLE) != 0) { boolean hasVisibleViewBefore = false; for (int i = childIndex - 1; i >= 0; i--) { if (getChildAt(i).getVisibility() != GONE) { hasVisibleViewBefore = true; break; } } return hasVisibleViewBefore; } return false; } }
Java
/* * Copyright (C) 2006 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.actionbarsherlock.internal.widget; import android.content.Context; import android.database.DataSetObserver; import android.os.Parcelable; import android.os.SystemClock; import android.util.AttributeSet; import android.util.SparseArray; import android.view.ContextMenu; import android.view.SoundEffectConstants; import android.view.View; import android.view.ViewDebug; import android.view.ViewGroup; import android.view.accessibility.AccessibilityEvent; import android.view.accessibility.AccessibilityNodeInfo; import android.widget.Adapter; import android.widget.AdapterView.OnItemClickListener; import android.widget.ListView; /** * An AdapterView is a view whose children are determined by an {@link Adapter}. * * <p> * See {@link ListView}, {@link GridView}, {@link Spinner} and * {@link Gallery} for commonly used subclasses of AdapterView. * * <div class="special reference"> * <h3>Developer Guides</h3> * <p>For more information about using AdapterView, read the * <a href="{@docRoot}guide/topics/ui/binding.html">Binding to Data with AdapterView</a> * developer guide.</p></div> */ public abstract class IcsAdapterView<T extends Adapter> extends ViewGroup { /** * The item view type returned by {@link Adapter#getItemViewType(int)} when * the adapter does not want the item's view recycled. */ public static final int ITEM_VIEW_TYPE_IGNORE = -1; /** * The item view type returned by {@link Adapter#getItemViewType(int)} when * the item is a header or footer. */ public static final int ITEM_VIEW_TYPE_HEADER_OR_FOOTER = -2; /** * The position of the first child displayed */ @ViewDebug.ExportedProperty(category = "scrolling") int mFirstPosition = 0; /** * The offset in pixels from the top of the AdapterView to the top * of the view to select during the next layout. */ int mSpecificTop; /** * Position from which to start looking for mSyncRowId */ int mSyncPosition; /** * Row id to look for when data has changed */ long mSyncRowId = INVALID_ROW_ID; /** * Height of the view when mSyncPosition and mSyncRowId where set */ long mSyncHeight; /** * True if we need to sync to mSyncRowId */ boolean mNeedSync = false; /** * Indicates whether to sync based on the selection or position. Possible * values are {@link #SYNC_SELECTED_POSITION} or * {@link #SYNC_FIRST_POSITION}. */ int mSyncMode; /** * Our height after the last layout */ private int mLayoutHeight; /** * Sync based on the selected child */ static final int SYNC_SELECTED_POSITION = 0; /** * Sync based on the first child displayed */ static final int SYNC_FIRST_POSITION = 1; /** * Maximum amount of time to spend in {@link #findSyncPosition()} */ static final int SYNC_MAX_DURATION_MILLIS = 100; /** * Indicates that this view is currently being laid out. */ boolean mInLayout = false; /** * The listener that receives notifications when an item is selected. */ OnItemSelectedListener mOnItemSelectedListener; /** * The listener that receives notifications when an item is clicked. */ OnItemClickListener mOnItemClickListener; /** * The listener that receives notifications when an item is long clicked. */ OnItemLongClickListener mOnItemLongClickListener; /** * True if the data has changed since the last layout */ boolean mDataChanged; /** * The position within the adapter's data set of the item to select * during the next layout. */ @ViewDebug.ExportedProperty(category = "list") int mNextSelectedPosition = INVALID_POSITION; /** * The item id of the item to select during the next layout. */ long mNextSelectedRowId = INVALID_ROW_ID; /** * The position within the adapter's data set of the currently selected item. */ @ViewDebug.ExportedProperty(category = "list") int mSelectedPosition = INVALID_POSITION; /** * The item id of the currently selected item. */ long mSelectedRowId = INVALID_ROW_ID; /** * View to show if there are no items to show. */ private View mEmptyView; /** * The number of items in the current adapter. */ @ViewDebug.ExportedProperty(category = "list") int mItemCount; /** * The number of items in the adapter before a data changed event occurred. */ int mOldItemCount; /** * Represents an invalid position. All valid positions are in the range 0 to 1 less than the * number of items in the current adapter. */ public static final int INVALID_POSITION = -1; /** * Represents an empty or invalid row id */ public static final long INVALID_ROW_ID = Long.MIN_VALUE; /** * The last selected position we used when notifying */ int mOldSelectedPosition = INVALID_POSITION; /** * The id of the last selected position we used when notifying */ long mOldSelectedRowId = INVALID_ROW_ID; /** * Indicates what focusable state is requested when calling setFocusable(). * In addition to this, this view has other criteria for actually * determining the focusable state (such as whether its empty or the text * filter is shown). * * @see #setFocusable(boolean) * @see #checkFocus() */ private boolean mDesiredFocusableState; private boolean mDesiredFocusableInTouchModeState; private SelectionNotifier mSelectionNotifier; /** * When set to true, calls to requestLayout() will not propagate up the parent hierarchy. * This is used to layout the children during a layout pass. */ boolean mBlockLayoutRequests = false; public IcsAdapterView(Context context) { super(context); } public IcsAdapterView(Context context, AttributeSet attrs) { super(context, attrs); } public IcsAdapterView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } /** * Register a callback to be invoked when an item in this AdapterView has * been clicked. * * @param listener The callback that will be invoked. */ public void setOnItemClickListener(OnItemClickListener listener) { mOnItemClickListener = listener; } /** * @return The callback to be invoked with an item in this AdapterView has * been clicked, or null id no callback has been set. */ public final OnItemClickListener getOnItemClickListener() { return mOnItemClickListener; } /** * Call the OnItemClickListener, if it is defined. * * @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 was clicked. * @return True if there was an assigned OnItemClickListener that was * called, false otherwise is returned. */ public boolean performItemClick(View view, int position, long id) { if (mOnItemClickListener != null) { playSoundEffect(SoundEffectConstants.CLICK); if (view != null) { view.sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED); } mOnItemClickListener.onItemClick(/*this*/null, view, position, id); return true; } return false; } /** * Interface definition for a callback to be invoked when an item in this * view has been clicked and held. */ public interface OnItemLongClickListener { /** * Callback method to be invoked when an item in this view has been * clicked and held. * * Implementers can call getItemAtPosition(position) if they need to access * the data associated with the selected item. * * @param parent The AbsListView where the click happened * @param view The view within the AbsListView that was clicked * @param position The position of the view in the list * @param id The row id of the item that was clicked * * @return true if the callback consumed the long click, false otherwise */ boolean onItemLongClick(IcsAdapterView<?> parent, View view, int position, long id); } /** * Register a callback to be invoked when an item in this AdapterView has * been clicked and held * * @param listener The callback that will run */ public void setOnItemLongClickListener(OnItemLongClickListener listener) { if (!isLongClickable()) { setLongClickable(true); } mOnItemLongClickListener = listener; } /** * @return The callback to be invoked with an item in this AdapterView has * been clicked and held, or null id no callback as been set. */ public final OnItemLongClickListener getOnItemLongClickListener() { return mOnItemLongClickListener; } /** * Interface definition for a callback to be invoked when * an item in this view has been selected. */ public interface OnItemSelectedListener { /** * <p>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.</p> * * 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(SparseArray<Parcelable> container) { dispatchFreezeSelfOnly(container); } /** * Override to prevent thawing of any views created by the adapter. */ @Override protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) { dispatchThawSelfOnly(container); } class AdapterDataSetObserver extends DataSetObserver { private Parcelable mInstanceState = null; @Override public void onChanged() { mDataChanged = true; mOldItemCount = mItemCount; mItemCount = getAdapter().getCount(); // Detect the case where a cursor that was previously invalidated has // been repopulated with new data. if (IcsAdapterView.this.getAdapter().hasStableIds() && mInstanceState != null && mOldItemCount == 0 && mItemCount > 0) { IcsAdapterView.this.onRestoreInstanceState(mInstanceState); mInstanceState = null; } else { rememberSyncState(); } checkFocus(); requestLayout(); } @Override public void onInvalidated() { mDataChanged = true; if (IcsAdapterView.this.getAdapter().hasStableIds()) { // Remember the current state for the case where our hosting activity is being // stopped and later restarted mInstanceState = IcsAdapterView.this.onSaveInstanceState(); } // Data is invalid so we should reset our state mOldItemCount = mItemCount; mItemCount = 0; mSelectedPosition = INVALID_POSITION; mSelectedRowId = INVALID_ROW_ID; mNextSelectedPosition = INVALID_POSITION; mNextSelectedRowId = INVALID_ROW_ID; mNeedSync = false; checkFocus(); requestLayout(); } public void clearSavedState() { mInstanceState = null; } } @Override protected void onDetachedFromWindow() { super.onDetachedFromWindow(); removeCallbacks(mSelectionNotifier); } private class SelectionNotifier implements Runnable { public void run() { if (mDataChanged) { // Data has changed between when this SelectionNotifier // was posted and now. We need to wait until the AdapterView // has been synched to the new data. if (getAdapter() != null) { post(this); } } else { fireOnSelected(); } } } void selectionChanged() { if (mOnItemSelectedListener != null) { if (mInLayout || mBlockLayoutRequests) { // If we are in a layout traversal, defer notification // by posting. This ensures that the view tree is // in a consistent state and is able to accomodate // new layout or invalidate requests. if (mSelectionNotifier == null) { mSelectionNotifier = new SelectionNotifier(); } post(mSelectionNotifier); } else { fireOnSelected(); } } // we fire selection events here not in View if (mSelectedPosition != ListView.INVALID_POSITION && isShown() && !isInTouchMode()) { sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SELECTED); } } private void fireOnSelected() { if (mOnItemSelectedListener == null) return; int selection = this.getSelectedItemPosition(); if (selection >= 0) { View v = getSelectedView(); mOnItemSelectedListener.onItemSelected(this, v, selection, getAdapter().getItemId(selection)); } else { mOnItemSelectedListener.onNothingSelected(this); } } @Override public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) { View selectedView = getSelectedView(); if (selectedView != null && selectedView.getVisibility() == VISIBLE && selectedView.dispatchPopulateAccessibilityEvent(event)) { return true; } return false; } @Override public boolean onRequestSendAccessibilityEvent(View child, AccessibilityEvent event) { if (super.onRequestSendAccessibilityEvent(child, event)) { // Add a record for ourselves as well. AccessibilityEvent record = AccessibilityEvent.obtain(); onInitializeAccessibilityEvent(record); // Populate with the text of the requesting child. child.dispatchPopulateAccessibilityEvent(record); event.appendRecord(record); return true; } return false; } @Override public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) { super.onInitializeAccessibilityNodeInfo(info); info.setScrollable(isScrollableForAccessibility()); View selectedView = getSelectedView(); if (selectedView != null) { info.setEnabled(selectedView.isEnabled()); } } @Override public void onInitializeAccessibilityEvent(AccessibilityEvent event) { super.onInitializeAccessibilityEvent(event); event.setScrollable(isScrollableForAccessibility()); View selectedView = getSelectedView(); if (selectedView != null) { event.setEnabled(selectedView.isEnabled()); } event.setCurrentItemIndex(getSelectedItemPosition()); event.setFromIndex(getFirstVisiblePosition()); event.setToIndex(getLastVisiblePosition()); event.setItemCount(getCount()); } private boolean isScrollableForAccessibility() { T adapter = getAdapter(); if (adapter != null) { final int itemCount = adapter.getCount(); return itemCount > 0 && (getFirstVisiblePosition() > 0 || getLastVisiblePosition() < itemCount - 1); } return false; } @Override protected boolean canAnimate() { return super.canAnimate() && mItemCount > 0; } void handleDataChanged() { final int count = mItemCount; boolean found = false; if (count > 0) { int newPos; // Find the row we are supposed to sync to if (mNeedSync) { // Update this first, since setNextSelectedPositionInt inspects // it mNeedSync = false; // See if we can find a position in the new data with the same // id as the old selection newPos = findSyncPosition(); if (newPos >= 0) { // Verify that new selection is selectable int selectablePos = lookForSelectablePosition(newPos, true); if (selectablePos == newPos) { // Same row id is selected setNextSelectedPositionInt(newPos); found = true; } } } if (!found) { // Try to use the same position if we can't find matching data newPos = getSelectedItemPosition(); // Pin position to the available range if (newPos >= count) { newPos = count - 1; } if (newPos < 0) { newPos = 0; } // Make sure we select something selectable -- first look down int selectablePos = lookForSelectablePosition(newPos, true); if (selectablePos < 0) { // Looking down didn't work -- try looking up selectablePos = lookForSelectablePosition(newPos, false); } if (selectablePos >= 0) { setNextSelectedPositionInt(selectablePos); checkSelectionChanged(); found = true; } } } if (!found) { // Nothing is selected mSelectedPosition = INVALID_POSITION; mSelectedRowId = INVALID_ROW_ID; mNextSelectedPosition = INVALID_POSITION; mNextSelectedRowId = INVALID_ROW_ID; mNeedSync = false; checkSelectionChanged(); } } void checkSelectionChanged() { if ((mSelectedPosition != mOldSelectedPosition) || (mSelectedRowId != mOldSelectedRowId)) { selectionChanged(); mOldSelectedPosition = mSelectedPosition; mOldSelectedRowId = mSelectedRowId; } } /** * Searches the adapter for a position matching mSyncRowId. The search starts at mSyncPosition * and then alternates between moving up and moving down until 1) we find the right position, or * 2) we run out of time, or 3) we have looked at every position * * @return Position of the row that matches mSyncRowId, or {@link #INVALID_POSITION} if it can't * be found */ int findSyncPosition() { int count = mItemCount; if (count == 0) { return INVALID_POSITION; } long idToMatch = mSyncRowId; int seed = mSyncPosition; // If there isn't a selection don't hunt for it if (idToMatch == INVALID_ROW_ID) { return INVALID_POSITION; } // Pin seed to reasonable values seed = Math.max(0, seed); seed = Math.min(count - 1, seed); long endTime = SystemClock.uptimeMillis() + SYNC_MAX_DURATION_MILLIS; long rowId; // first position scanned so far int first = seed; // last position scanned so far int last = seed; // True if we should move down on the next iteration boolean next = false; // True when we have looked at the first item in the data boolean hitFirst; // True when we have looked at the last item in the data boolean hitLast; // Get the item ID locally (instead of getItemIdAtPosition), so // we need the adapter T adapter = getAdapter(); if (adapter == null) { return INVALID_POSITION; } while (SystemClock.uptimeMillis() <= endTime) { rowId = adapter.getItemId(seed); if (rowId == idToMatch) { // Found it! return seed; } hitLast = last == count - 1; hitFirst = first == 0; if (hitLast && hitFirst) { // Looked at everything break; } if (hitFirst || (next && !hitLast)) { // Either we hit the top, or we are trying to move down last++; seed = last; // Try going up next time next = false; } else if (hitLast || (!next && !hitFirst)) { // Either we hit the bottom, or we are trying to move up first--; seed = first; // Try going down next time next = true; } } return INVALID_POSITION; } /** * Find a position that can be selected (i.e., is not a separator). * * @param position The starting position to look at. * @param lookDown Whether to look down for other positions. * @return The next selectable position starting at position and then searching either up or * down. Returns {@link #INVALID_POSITION} if nothing can be found. */ int lookForSelectablePosition(int position, boolean lookDown) { return position; } /** * Utility to keep mSelectedPosition and mSelectedRowId in sync * @param position Our current position */ void setSelectedPositionInt(int position) { mSelectedPosition = position; mSelectedRowId = getItemIdAtPosition(position); } /** * Utility to keep mNextSelectedPosition and mNextSelectedRowId in sync * @param position Intended value for mSelectedPosition the next time we go * through layout */ void setNextSelectedPositionInt(int position) { mNextSelectedPosition = position; mNextSelectedRowId = getItemIdAtPosition(position); // If we are trying to sync to the selection, update that too if (mNeedSync && mSyncMode == SYNC_SELECTED_POSITION && position >= 0) { mSyncPosition = position; mSyncRowId = mNextSelectedRowId; } } /** * Remember enough information to restore the screen state when the data has * changed. * */ void rememberSyncState() { if (getChildCount() > 0) { mNeedSync = true; mSyncHeight = mLayoutHeight; if (mSelectedPosition >= 0) { // Sync the selection state View v = getChildAt(mSelectedPosition - mFirstPosition); mSyncRowId = mNextSelectedRowId; mSyncPosition = mNextSelectedPosition; if (v != null) { mSpecificTop = v.getTop(); } mSyncMode = SYNC_SELECTED_POSITION; } else { // Sync the based on the offset of the first view View v = getChildAt(0); T adapter = getAdapter(); if (mFirstPosition >= 0 && mFirstPosition < adapter.getCount()) { mSyncRowId = adapter.getItemId(mFirstPosition); } else { mSyncRowId = NO_ID; } mSyncPosition = mFirstPosition; if (v != null) { mSpecificTop = v.getTop(); } mSyncMode = SYNC_FIRST_POSITION; } } } }
Java
/* * 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.internal.widget; import android.content.Context; import android.content.res.Configuration; import android.content.res.TypedArray; import android.graphics.drawable.Drawable; import android.text.TextUtils.TruncateAt; import android.util.AttributeSet; 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.BaseAdapter; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ListView; 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 NineHorizontalScrollView implements IcsAdapterView.OnItemSelectedListener { //UNUSED private static final String TAG = "ScrollingTabContainerView"; Runnable mTabSelector; private TabClickListener mTabClickListener; private IcsLinearLayout mTabLayout; private IcsSpinner mTabSpinner; private boolean mAllowCollapse; private LayoutInflater mInflater; int mMaxTabWidth; private int mContentHeight; private int mSelectedTabIndex; protected Animator mVisibilityAnim; protected final VisibilityAnimListener mVisAnimListener = new VisibilityAnimListener(); private static final /*Time*/Interpolator sAlphaInterpolator = new DecelerateInterpolator(); private static final int FADE_DURATION = 200; public ScrollingTabContainerView(Context context) { super(context); setHorizontalScrollBarEnabled(false); TypedArray a = getContext().obtainStyledAttributes(null, R.styleable.SherlockActionBar, R.attr.actionBarStyle, 0); setContentHeight(a.getLayoutDimension(R.styleable.SherlockActionBar_height, 0)); a.recycle(); mInflater = LayoutInflater.from(context); mTabLayout = createTabLayout(); addView(mTabLayout, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT)); } @Override public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { final int widthMode = MeasureSpec.getMode(widthMeasureSpec); final boolean lockedExpanded = widthMode == MeasureSpec.EXACTLY; setFillViewport(lockedExpanded); final int childCount = mTabLayout.getChildCount(); if (childCount > 1 && (widthMode == MeasureSpec.EXACTLY || widthMode == MeasureSpec.AT_MOST)) { if (childCount > 2) { mMaxTabWidth = (int) (MeasureSpec.getSize(widthMeasureSpec) * 0.4f); } else { mMaxTabWidth = MeasureSpec.getSize(widthMeasureSpec) / 2; } } else { mMaxTabWidth = -1; } heightMeasureSpec = MeasureSpec.makeMeasureSpec(mContentHeight, MeasureSpec.EXACTLY); final boolean canCollapse = !lockedExpanded && mAllowCollapse; if (canCollapse) { // See if we should expand mTabLayout.measure(MeasureSpec.UNSPECIFIED, heightMeasureSpec); if (mTabLayout.getMeasuredWidth() > MeasureSpec.getSize(widthMeasureSpec)) { performCollapse(); } else { performExpand(); } } else { performExpand(); } final int oldWidth = getMeasuredWidth(); super.onMeasure(widthMeasureSpec, heightMeasureSpec); final int newWidth = getMeasuredWidth(); if (lockedExpanded && oldWidth != newWidth) { // Recenter the tab display if we're at a new (scrollable) size. setTabSelected(mSelectedTabIndex); } } /** * Indicates whether this view is collapsed into a dropdown menu instead * of traditional tabs. * @return true if showing as a spinner */ private boolean isCollapsed() { return mTabSpinner != null && mTabSpinner.getParent() == this; } public void setAllowCollapse(boolean allowCollapse) { mAllowCollapse = allowCollapse; } private void performCollapse() { if (isCollapsed()) return; if (mTabSpinner == null) { mTabSpinner = createSpinner(); } removeView(mTabLayout); addView(mTabSpinner, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT)); if (mTabSpinner.getAdapter() == null) { mTabSpinner.setAdapter(new TabAdapter()); } if (mTabSelector != null) { removeCallbacks(mTabSelector); mTabSelector = null; } mTabSpinner.setSelection(mSelectedTabIndex); } private boolean performExpand() { if (!isCollapsed()) return false; removeView(mTabSpinner); addView(mTabLayout, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT)); setTabSelected(mTabSpinner.getSelectedItemPosition()); return false; } public void setTabSelected(int position) { mSelectedTabIndex = position; final int tabCount = mTabLayout.getChildCount(); for (int i = 0; i < tabCount; i++) { final View child = mTabLayout.getChildAt(i); final boolean isSelected = i == position; child.setSelected(isSelected); if (isSelected) { animateToTab(position); } } } public void setContentHeight(int contentHeight) { mContentHeight = contentHeight; requestLayout(); } private IcsLinearLayout createTabLayout() { 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 IcsSpinner createSpinner() { final IcsSpinner spinner = new IcsSpinner(getContext(), null, R.attr.actionDropDownStyle); spinner.setLayoutParams(new LinearLayout.LayoutParams( LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.MATCH_PARENT)); spinner.setOnItemSelectedListener(this); return spinner; } @Override protected void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); // Action bar can change size on configuration changes. // Reread the desired height from the theme-specified style. TypedArray a = getContext().obtainStyledAttributes(null, R.styleable.SherlockActionBar, R.attr.actionBarStyle, 0); setContentHeight(a.getLayoutDimension(R.styleable.SherlockActionBar_height, 0)); a.recycle(); } public void animateToVisibility(int visibility) { if (mVisibilityAnim != null) { mVisibilityAnim.cancel(); } if (visibility == VISIBLE) { if (getVisibility() != VISIBLE) { setAlpha(0); } ObjectAnimator anim = ObjectAnimator.ofFloat(this, "alpha", 1); anim.setDuration(FADE_DURATION); anim.setInterpolator(sAlphaInterpolator); anim.addListener(mVisAnimListener.withFinalVisibility(visibility)); anim.start(); } else { ObjectAnimator anim = ObjectAnimator.ofFloat(this, "alpha", 0); anim.setDuration(FADE_DURATION); anim.setInterpolator(sAlphaInterpolator); anim.addListener(mVisAnimListener.withFinalVisibility(visibility)); anim.start(); } } public void animateToTab(final int position) { final View tabView = mTabLayout.getChildAt(position); if (mTabSelector != null) { removeCallbacks(mTabSelector); } mTabSelector = new Runnable() { public void run() { final int scrollPos = tabView.getLeft() - (getWidth() - tabView.getWidth()) / 2; smoothScrollTo(scrollPos, 0); mTabSelector = null; } }; post(mTabSelector); } @Override public void onAttachedToWindow() { super.onAttachedToWindow(); if (mTabSelector != null) { // Re-post the selector we saved post(mTabSelector); } } @Override public void onDetachedFromWindow() { super.onDetachedFromWindow(); if (mTabSelector != null) { removeCallbacks(mTabSelector); } } private TabView createTabView(ActionBar.Tab tab, boolean forAdapter) { //Workaround for not being able to pass a defStyle on pre-3.0 final TabView tabView = (TabView)mInflater.inflate(R.layout.abs__action_bar_tab, null); tabView.init(this, tab, forAdapter); if (forAdapter) { tabView.setBackgroundDrawable(null); tabView.setLayoutParams(new ListView.LayoutParams(ListView.LayoutParams.MATCH_PARENT, mContentHeight)); } else { tabView.setFocusable(true); if (mTabClickListener == null) { mTabClickListener = new TabClickListener(); } tabView.setOnClickListener(mTabClickListener); } return tabView; } public void addTab(ActionBar.Tab tab, boolean setSelected) { TabView tabView = createTabView(tab, false); mTabLayout.addView(tabView, new IcsLinearLayout.LayoutParams(0, LayoutParams.MATCH_PARENT, 1)); if (mTabSpinner != null) { ((TabAdapter) mTabSpinner.getAdapter()).notifyDataSetChanged(); } if (setSelected) { tabView.setSelected(true); } if (mAllowCollapse) { requestLayout(); } } 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.MATCH_PARENT, 1)); if (mTabSpinner != null) { ((TabAdapter) mTabSpinner.getAdapter()).notifyDataSetChanged(); } if (setSelected) { tabView.setSelected(true); } if (mAllowCollapse) { requestLayout(); } } public void updateTab(int position) { ((TabView) mTabLayout.getChildAt(position)).update(); if (mTabSpinner != null) { ((TabAdapter) mTabSpinner.getAdapter()).notifyDataSetChanged(); } if (mAllowCollapse) { requestLayout(); } } public void removeTabAt(int position) { mTabLayout.removeViewAt(position); if (mTabSpinner != null) { ((TabAdapter) mTabSpinner.getAdapter()).notifyDataSetChanged(); } if (mAllowCollapse) { requestLayout(); } } public void removeAllTabs() { mTabLayout.removeAllViews(); if (mTabSpinner != null) { ((TabAdapter) mTabSpinner.getAdapter()).notifyDataSetChanged(); } if (mAllowCollapse) { requestLayout(); } } @Override public void onItemSelected(IcsAdapterView<?> parent, View view, int position, long id) { TabView tabView = (TabView) view; tabView.getTab().select(); } @Override public void onNothingSelected(IcsAdapterView<?> parent) { } public static class TabView extends LinearLayout { private ScrollingTabContainerView mParent; private ActionBar.Tab mTab; private CapitalizingTextView mTextView; private ImageView mIconView; private View mCustomView; public TabView(Context context, AttributeSet attrs) { //TODO super(context, null, R.attr.actionBarTabStyle); super(context, attrs); } public void init(ScrollingTabContainerView parent, ActionBar.Tab tab, boolean forList) { mParent = parent; mTab = tab; if (forList) { setGravity(Gravity.LEFT | Gravity.CENTER_VERTICAL); } update(); } public void bindTab(ActionBar.Tab tab) { mTab = tab; update(); } @Override public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); // Re-measure if we went beyond our maximum size. if (mParent.mMaxTabWidth > 0 && getMeasuredWidth() > mParent.mMaxTabWidth) { super.onMeasure(MeasureSpec.makeMeasureSpec(mParent.mMaxTabWidth, MeasureSpec.EXACTLY), heightMeasureSpec); } } public void update() { final ActionBar.Tab tab = mTab; final View custom = tab.getCustomView(); if (custom != null) { 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) { mIconView.setVisibility(GONE); mIconView.setImageDrawable(null); } } else { if (mCustomView != null) { removeView(mCustomView); mCustomView = null; } final Drawable icon = tab.getIcon(); final CharSequence text = tab.getText(); if (icon != null) { if (mIconView == null) { ImageView iconView = new ImageView(getContext()); LayoutParams lp = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); lp.gravity = Gravity.CENTER_VERTICAL; iconView.setLayoutParams(lp); addView(iconView, 0); mIconView = iconView; } mIconView.setImageDrawable(icon); mIconView.setVisibility(VISIBLE); } else if (mIconView != null) { mIconView.setVisibility(GONE); mIconView.setImageDrawable(null); } if (text != null) { if (mTextView == null) { CapitalizingTextView textView = new CapitalizingTextView(getContext(), null, R.attr.actionBarTabTextStyle); textView.setEllipsize(TruncateAt.END); LayoutParams lp = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); lp.gravity = Gravity.CENTER_VERTICAL; textView.setLayoutParams(lp); addView(textView); mTextView = textView; } mTextView.setTextCompat(text); mTextView.setVisibility(VISIBLE); } else if (mTextView != null) { mTextView.setVisibility(GONE); mTextView.setText(null); } if (mIconView != null) { mIconView.setContentDescription(tab.getContentDescription()); } } } public ActionBar.Tab getTab() { return mTab; } } private class TabAdapter extends BaseAdapter { @Override public int getCount() { return mTabLayout.getChildCount(); } @Override public Object getItem(int position) { return ((TabView) mTabLayout.getChildAt(position)).getTab(); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { if (convertView == null) { convertView = createTabView((ActionBar.Tab) getItem(position), true); } else { ((TabView) convertView).bindTab((ActionBar.Tab) getItem(position)); } return convertView; } } private class TabClickListener implements OnClickListener { public void onClick(View view) { TabView tabView = (TabView) view; tabView.getTab().select(); final int tabCount = mTabLayout.getChildCount(); for (int i = 0; i < tabCount; i++) { final View child = mTabLayout.getChildAt(i); child.setSelected(child == view); } } } protected class VisibilityAnimListener implements Animator.AnimatorListener { private boolean mCanceled = false; private int mFinalVisibility; public VisibilityAnimListener withFinalVisibility(int visibility) { mFinalVisibility = visibility; return this; } @Override public void onAnimationStart(Animator animation) { setVisibility(VISIBLE); mVisibilityAnim = animation; mCanceled = false; } @Override public void onAnimationEnd(Animator animation) { if (mCanceled) return; mVisibilityAnim = null; setVisibility(mFinalVisibility); } @Override public void onAnimationCancel(Animator animation) { mCanceled = true; } @Override public void onAnimationRepeat(Animator animation) { } } }
Java
/* * Copyright (C) 2010 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.internal.widget; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Canvas; import android.graphics.drawable.Drawable; import android.util.AttributeSet; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import com.actionbarsherlock.R; import com.actionbarsherlock.app.ActionBar; import com.actionbarsherlock.internal.nineoldandroids.widget.NineFrameLayout; /** * This class acts as a container for the action bar view and action mode context views. * It applies special styles as needed to help handle animated transitions between them. * @hide */ public class ActionBarContainer extends NineFrameLayout { private boolean mIsTransitioning; private View mTabContainer; private ActionBarView mActionBarView; private Drawable mBackground; private Drawable mStackedBackground; private Drawable mSplitBackground; private boolean mIsSplit; private boolean mIsStacked; public ActionBarContainer(Context context) { this(context, null); } public ActionBarContainer(Context context, AttributeSet attrs) { super(context, attrs); setBackgroundDrawable(null); TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.SherlockActionBar); mBackground = a.getDrawable(R.styleable.SherlockActionBar_background); mStackedBackground = a.getDrawable( R.styleable.SherlockActionBar_backgroundStacked); if (getId() == R.id.abs__split_action_bar) { mIsSplit = true; mSplitBackground = a.getDrawable( R.styleable.SherlockActionBar_backgroundSplit); } a.recycle(); setWillNotDraw(mIsSplit ? mSplitBackground == null : mBackground == null && mStackedBackground == null); } @Override public void onFinishInflate() { super.onFinishInflate(); mActionBarView = (ActionBarView) findViewById(R.id.abs__action_bar); } public void setPrimaryBackground(Drawable bg) { mBackground = bg; invalidate(); } public void setStackedBackground(Drawable bg) { mStackedBackground = bg; invalidate(); } public void setSplitBackground(Drawable bg) { mSplitBackground = bg; invalidate(); } /** * Set the action bar into a "transitioning" state. While transitioning * the bar will block focus and touch from all of its descendants. This * prevents the user from interacting with the bar while it is animating * in or out. * * @param isTransitioning true if the bar is currently transitioning, false otherwise. */ public void setTransitioning(boolean isTransitioning) { mIsTransitioning = isTransitioning; setDescendantFocusability(isTransitioning ? FOCUS_BLOCK_DESCENDANTS : FOCUS_AFTER_DESCENDANTS); } @Override public boolean onInterceptTouchEvent(MotionEvent ev) { return mIsTransitioning || super.onInterceptTouchEvent(ev); } @Override public boolean onTouchEvent(MotionEvent ev) { super.onTouchEvent(ev); // An action bar always eats touch events. return true; } @Override public boolean onHoverEvent(MotionEvent ev) { super.onHoverEvent(ev); // An action bar always eats hover events. return true; } public void setTabContainer(ScrollingTabContainerView tabView) { if (mTabContainer != null) { removeView(mTabContainer); } mTabContainer = tabView; if (tabView != null) { addView(tabView); final ViewGroup.LayoutParams lp = tabView.getLayoutParams(); lp.width = LayoutParams.MATCH_PARENT; lp.height = LayoutParams.WRAP_CONTENT; tabView.setAllowCollapse(false); } } public View getTabContainer() { return mTabContainer; } @Override public void onDraw(Canvas canvas) { if (getWidth() == 0 || getHeight() == 0) { return; } if (mIsSplit) { if (mSplitBackground != null) mSplitBackground.draw(canvas); } else { if (mBackground != null) { mBackground.draw(canvas); } if (mStackedBackground != null && mIsStacked) { mStackedBackground.draw(canvas); } } } //This causes the animation reflection to fail on pre-HC platforms //@Override //public android.view.ActionMode startActionModeForChild(View child, android.view.ActionMode.Callback callback) { // // No starting an action mode for an action bar child! (Where would it go?) // return null; //} @Override public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); if (mActionBarView == null) return; final LayoutParams lp = (LayoutParams) mActionBarView.getLayoutParams(); final int actionBarViewHeight = mActionBarView.isCollapsed() ? 0 : mActionBarView.getMeasuredHeight() + lp.topMargin + lp.bottomMargin; if (mTabContainer != null && mTabContainer.getVisibility() != GONE) { final int mode = MeasureSpec.getMode(heightMeasureSpec); if (mode == MeasureSpec.AT_MOST) { final int maxHeight = MeasureSpec.getSize(heightMeasureSpec); setMeasuredDimension(getMeasuredWidth(), Math.min(actionBarViewHeight + mTabContainer.getMeasuredHeight(), maxHeight)); } } } @Override public void onLayout(boolean changed, int l, int t, int r, int b) { super.onLayout(changed, l, t, r, b); final boolean hasTabs = mTabContainer != null && mTabContainer.getVisibility() != GONE; if (mTabContainer != null && mTabContainer.getVisibility() != GONE) { final int containerHeight = getMeasuredHeight(); final int tabHeight = mTabContainer.getMeasuredHeight(); if ((mActionBarView.getDisplayOptions() & ActionBar.DISPLAY_SHOW_HOME) == 0) { // Not showing home, put tabs on top. final int count = getChildCount(); for (int i = 0; i < count; i++) { final View child = getChildAt(i); if (child == mTabContainer) continue; if (!mActionBarView.isCollapsed()) { child.offsetTopAndBottom(tabHeight); } } mTabContainer.layout(l, 0, r, tabHeight); } else { mTabContainer.layout(l, containerHeight - tabHeight, r, containerHeight); } } boolean needsInvalidate = false; if (mIsSplit) { if (mSplitBackground != null) { mSplitBackground.setBounds(0, 0, getMeasuredWidth(), getMeasuredHeight()); needsInvalidate = true; } } else { if (mBackground != null) { mBackground.setBounds(mActionBarView.getLeft(), mActionBarView.getTop(), mActionBarView.getRight(), mActionBarView.getBottom()); needsInvalidate = true; } if ((mIsStacked = hasTabs && mStackedBackground != null)) { mStackedBackground.setBounds(mTabContainer.getLeft(), mTabContainer.getTop(), mTabContainer.getRight(), mTabContainer.getBottom()); needsInvalidate = true; } } if (needsInvalidate) { invalidate(); } } }
Java
/* * Copyright (C) 2006 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.actionbarsherlock.internal.widget; import android.content.Context; import android.database.DataSetObserver; import android.graphics.Rect; import android.os.Build; import android.os.Parcel; import android.os.Parcelable; import android.util.AttributeSet; import android.util.SparseArray; import android.view.View; import android.view.ViewGroup; import android.widget.SpinnerAdapter; /** * An abstract base class for spinner widgets. SDK users will probably not * need to use this class. * * @attr ref android.R.styleable#AbsSpinner_entries */ public abstract class IcsAbsSpinner extends IcsAdapterView<SpinnerAdapter> { private static final boolean IS_HONEYCOMB = Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB; SpinnerAdapter mAdapter; int mHeightMeasureSpec; int mWidthMeasureSpec; boolean mBlockLayoutRequests; int mSelectionLeftPadding = 0; int mSelectionTopPadding = 0; int mSelectionRightPadding = 0; int mSelectionBottomPadding = 0; final Rect mSpinnerPadding = new Rect(); final RecycleBin mRecycler = new RecycleBin(); private DataSetObserver mDataSetObserver; /** Temporary frame to hold a child View's frame rectangle */ private Rect mTouchFrame; public IcsAbsSpinner(Context context) { super(context); initAbsSpinner(); } public IcsAbsSpinner(Context context, AttributeSet attrs) { this(context, attrs, 0); } public IcsAbsSpinner(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); initAbsSpinner(); /* TypedArray a = context.obtainStyledAttributes(attrs, com.android.internal.R.styleable.AbsSpinner, defStyle, 0); CharSequence[] entries = a.getTextArray(R.styleable.AbsSpinner_entries); if (entries != null) { ArrayAdapter<CharSequence> adapter = new ArrayAdapter<CharSequence>(context, R.layout.simple_spinner_item, entries); adapter.setDropDownViewResource(R.layout.simple_spinner_dropdown_item); setAdapter(adapter); } a.recycle(); */ } /** * Common code for different constructor flavors */ private void initAbsSpinner() { setFocusable(true); setWillNotDraw(false); } /** * The Adapter is used to provide the data which backs this Spinner. * It also provides methods to transform spinner items based on their position * relative to the selected item. * @param adapter The SpinnerAdapter to use for this Spinner */ @Override public void setAdapter(SpinnerAdapter adapter) { if (null != mAdapter) { mAdapter.unregisterDataSetObserver(mDataSetObserver); resetList(); } mAdapter = adapter; mOldSelectedPosition = INVALID_POSITION; mOldSelectedRowId = INVALID_ROW_ID; if (mAdapter != null) { mOldItemCount = mItemCount; mItemCount = mAdapter.getCount(); checkFocus(); mDataSetObserver = new AdapterDataSetObserver(); mAdapter.registerDataSetObserver(mDataSetObserver); int position = mItemCount > 0 ? 0 : INVALID_POSITION; setSelectedPositionInt(position); setNextSelectedPositionInt(position); if (mItemCount == 0) { // Nothing selected checkSelectionChanged(); } } else { checkFocus(); resetList(); // Nothing selected checkSelectionChanged(); } requestLayout(); } /** * Clear out all children from the list */ void resetList() { mDataChanged = false; mNeedSync = false; removeAllViewsInLayout(); mOldSelectedPosition = INVALID_POSITION; mOldSelectedRowId = INVALID_ROW_ID; setSelectedPositionInt(INVALID_POSITION); setNextSelectedPositionInt(INVALID_POSITION); invalidate(); } /** * @see android.view.View#measure(int, int) * * Figure out the dimensions of this Spinner. The width comes from * the widthMeasureSpec as Spinnners can't have their width set to * UNSPECIFIED. The height is based on the height of the selected item * plus padding. */ @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int widthMode = MeasureSpec.getMode(widthMeasureSpec); int widthSize; int heightSize; final int mPaddingLeft = getPaddingLeft(); final int mPaddingTop = getPaddingTop(); final int mPaddingRight = getPaddingRight(); final int mPaddingBottom = getPaddingBottom(); mSpinnerPadding.left = mPaddingLeft > mSelectionLeftPadding ? mPaddingLeft : mSelectionLeftPadding; mSpinnerPadding.top = mPaddingTop > mSelectionTopPadding ? mPaddingTop : mSelectionTopPadding; mSpinnerPadding.right = mPaddingRight > mSelectionRightPadding ? mPaddingRight : mSelectionRightPadding; mSpinnerPadding.bottom = mPaddingBottom > mSelectionBottomPadding ? mPaddingBottom : mSelectionBottomPadding; if (mDataChanged) { handleDataChanged(); } int preferredHeight = 0; int preferredWidth = 0; boolean needsMeasuring = true; int selectedPosition = getSelectedItemPosition(); if (selectedPosition >= 0 && mAdapter != null && selectedPosition < mAdapter.getCount()) { // Try looking in the recycler. (Maybe we were measured once already) View view = mRecycler.get(selectedPosition); if (view == null) { // Make a new one view = mAdapter.getView(selectedPosition, null, this); } if (view != null) { // Put in recycler for re-measuring and/or layout mRecycler.put(selectedPosition, view); } if (view != null) { if (view.getLayoutParams() == null) { mBlockLayoutRequests = true; view.setLayoutParams(generateDefaultLayoutParams()); mBlockLayoutRequests = false; } measureChild(view, widthMeasureSpec, heightMeasureSpec); preferredHeight = getChildHeight(view) + mSpinnerPadding.top + mSpinnerPadding.bottom; preferredWidth = getChildWidth(view) + mSpinnerPadding.left + mSpinnerPadding.right; needsMeasuring = false; } } if (needsMeasuring) { // No views -- just use padding preferredHeight = mSpinnerPadding.top + mSpinnerPadding.bottom; if (widthMode == MeasureSpec.UNSPECIFIED) { preferredWidth = mSpinnerPadding.left + mSpinnerPadding.right; } } preferredHeight = Math.max(preferredHeight, getSuggestedMinimumHeight()); preferredWidth = Math.max(preferredWidth, getSuggestedMinimumWidth()); if (IS_HONEYCOMB) { heightSize = resolveSizeAndState(preferredHeight, heightMeasureSpec, 0); widthSize = resolveSizeAndState(preferredWidth, widthMeasureSpec, 0); } else { heightSize = resolveSize(preferredHeight, heightMeasureSpec); widthSize = resolveSize(preferredWidth, widthMeasureSpec); } setMeasuredDimension(widthSize, heightSize); mHeightMeasureSpec = heightMeasureSpec; mWidthMeasureSpec = widthMeasureSpec; } int getChildHeight(View child) { return child.getMeasuredHeight(); } int getChildWidth(View child) { return child.getMeasuredWidth(); } @Override protected ViewGroup.LayoutParams generateDefaultLayoutParams() { return new ViewGroup.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT); } void recycleAllViews() { final int childCount = getChildCount(); final IcsAbsSpinner.RecycleBin recycleBin = mRecycler; final int position = mFirstPosition; // All views go in recycler for (int i = 0; i < childCount; i++) { View v = getChildAt(i); int index = position + i; recycleBin.put(index, v); } } /** * Jump directly to a specific item in the adapter data. */ public void setSelection(int position, boolean animate) { // Animate only if requested position is already on screen somewhere boolean shouldAnimate = animate && mFirstPosition <= position && position <= mFirstPosition + getChildCount() - 1; setSelectionInt(position, shouldAnimate); } @Override public void setSelection(int position) { setNextSelectedPositionInt(position); requestLayout(); invalidate(); } /** * Makes the item at the supplied position selected. * * @param position Position to select * @param animate Should the transition be animated * */ void setSelectionInt(int position, boolean animate) { if (position != mOldSelectedPosition) { mBlockLayoutRequests = true; int delta = position - mSelectedPosition; setNextSelectedPositionInt(position); layout(delta, animate); mBlockLayoutRequests = false; } } abstract void layout(int delta, boolean animate); @Override public View getSelectedView() { if (mItemCount > 0 && mSelectedPosition >= 0) { return getChildAt(mSelectedPosition - mFirstPosition); } else { return null; } } /** * Override to prevent spamming ourselves with layout requests * as we place views * * @see android.view.View#requestLayout() */ @Override public void requestLayout() { if (!mBlockLayoutRequests) { super.requestLayout(); } } @Override public SpinnerAdapter getAdapter() { return mAdapter; } @Override public int getCount() { return mItemCount; } /** * Maps a point to a position in the list. * * @param x X in local coordinate * @param y Y in local coordinate * @return The position of the item which contains the specified point, or * {@link #INVALID_POSITION} if the point does not intersect an item. */ public int pointToPosition(int x, int y) { Rect frame = mTouchFrame; if (frame == null) { mTouchFrame = new Rect(); frame = mTouchFrame; } final int count = getChildCount(); for (int i = count - 1; i >= 0; i--) { View child = getChildAt(i); if (child.getVisibility() == View.VISIBLE) { child.getHitRect(frame); if (frame.contains(x, y)) { return mFirstPosition + i; } } } return INVALID_POSITION; } static class SavedState extends BaseSavedState { long selectedId; int position; /** * Constructor called from {@link AbsSpinner#onSaveInstanceState()} */ SavedState(Parcelable superState) { super(superState); } /** * Constructor called from {@link #CREATOR} */ private SavedState(Parcel in) { super(in); selectedId = in.readLong(); position = in.readInt(); } @Override public void writeToParcel(Parcel out, int flags) { super.writeToParcel(out, flags); out.writeLong(selectedId); out.writeInt(position); } @Override public String toString() { return "AbsSpinner.SavedState{" + Integer.toHexString(System.identityHashCode(this)) + " selectedId=" + selectedId + " position=" + position + "}"; } public static final Parcelable.Creator<SavedState> CREATOR = new Parcelable.Creator<SavedState>() { public SavedState createFromParcel(Parcel in) { return new SavedState(in); } public SavedState[] newArray(int size) { return new SavedState[size]; } }; } @Override public Parcelable onSaveInstanceState() { Parcelable superState = super.onSaveInstanceState(); SavedState ss = new SavedState(superState); ss.selectedId = getSelectedItemId(); if (ss.selectedId >= 0) { ss.position = getSelectedItemPosition(); } else { ss.position = INVALID_POSITION; } return ss; } @Override public void onRestoreInstanceState(Parcelable state) { SavedState ss = (SavedState) state; super.onRestoreInstanceState(ss.getSuperState()); if (ss.selectedId >= 0) { mDataChanged = true; mNeedSync = true; mSyncRowId = ss.selectedId; mSyncPosition = ss.position; mSyncMode = SYNC_SELECTED_POSITION; requestLayout(); } } class RecycleBin { private final SparseArray<View> mScrapHeap = new SparseArray<View>(); public void put(int position, View v) { mScrapHeap.put(position, v); } View get(int position) { // System.out.print("Looking for " + position); View result = mScrapHeap.get(position); if (result != null) { // System.out.println(" HIT"); mScrapHeap.delete(position); } else { // System.out.println(" MISS"); } return result; } void clear() { final SparseArray<View> scrapHeap = mScrapHeap; final int count = scrapHeap.size(); for (int i = 0; i < count; i++) { final View view = scrapHeap.valueAt(i); if (view != null) { removeDetachedView(view, true); } } scrapHeap.clear(); } } }
Java
/* * Copyright (C) 2007 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.internal.widget; import static android.view.ViewGroup.LayoutParams.MATCH_PARENT; import static android.view.ViewGroup.LayoutParams.WRAP_CONTENT; import com.actionbarsherlock.R; import android.content.Context; import android.content.DialogInterface; import android.content.DialogInterface.OnClickListener; import android.content.res.TypedArray; import android.database.DataSetObserver; import android.graphics.Rect; import android.graphics.drawable.Drawable; import android.util.AttributeSet; import android.view.Gravity; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ListAdapter; import android.widget.ListView; import android.widget.PopupWindow; import android.widget.SpinnerAdapter; /** * A view that displays one child at a time and lets the user pick among them. * The items in the Spinner come from the {@link Adapter} associated with * this view. * * <p>See the <a href="{@docRoot}resources/tutorials/views/hello-spinner.html">Spinner * tutorial</a>.</p> * * @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(); public IcsSpinner(Context context, AttributeSet attrs) { this(context, attrs, R.attr.actionDropDownStyle); } /** * 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(); } } /** * <p>A spinner does not support item click events. Calling this method * will raise an exception.</p> * * @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; } /** * <p>Wrapper class for an Adapter. Transforms the embedded Adapter instance * into a ListAdapter.</p> */ private static class DropDownAdapter implements ListAdapter, SpinnerAdapter { private SpinnerAdapter mAdapter; private ListAdapter mListAdapter; /** * <p>Creates a new ListAdapter wrapper for the specified adapter.</p> * * @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()); } } }
Java
package com.actionbarsherlock.internal.widget; import java.util.Locale; import android.content.Context; import android.content.res.TypedArray; import android.os.Build; import android.util.AttributeSet; import android.widget.TextView; public class CapitalizingTextView extends TextView { private static final boolean SANS_ICE_CREAM = Build.VERSION.SDK_INT < Build.VERSION_CODES.ICE_CREAM_SANDWICH; private static final boolean IS_GINGERBREAD = Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD; private static final int[] R_styleable_TextView = new int[] { android.R.attr.textAllCaps }; private static final int R_styleable_TextView_textAllCaps = 0; private boolean mAllCaps; public CapitalizingTextView(Context context, AttributeSet attrs) { this(context, attrs, 0); } public CapitalizingTextView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); TypedArray a = context.obtainStyledAttributes(attrs, R_styleable_TextView, defStyle, 0); mAllCaps = a.getBoolean(R_styleable_TextView_textAllCaps, true); a.recycle(); } public void setTextCompat(CharSequence text) { if (SANS_ICE_CREAM && mAllCaps && text != null) { if (IS_GINGERBREAD) { setText(text.toString().toUpperCase(Locale.ROOT)); } else { setText(text.toString().toUpperCase()); } } else { setText(text); } } }
Java
package com.actionbarsherlock.internal.widget; import com.actionbarsherlock.R; import android.content.Context; import android.content.res.Resources; import android.database.DataSetObserver; import android.graphics.Rect; import android.graphics.drawable.Drawable; import android.os.Build; import android.os.Handler; import android.util.AttributeSet; import android.view.ContextThemeWrapper; import android.view.MotionEvent; import android.view.View; import android.view.View.MeasureSpec; import android.view.View.OnTouchListener; import android.view.ViewGroup; import android.view.ViewParent; import android.widget.AbsListView; import android.widget.AdapterView; import android.widget.LinearLayout; import android.widget.ListAdapter; import android.widget.ListView; import android.widget.PopupWindow; /** * A proxy between pre- and post-Honeycomb implementations of this class. */ public class IcsListPopupWindow { /** * This value controls the length of time that the user * must leave a pointer down without scrolling to expand * the autocomplete dropdown list to cover the IME. */ private static final int EXPAND_LIST_TIMEOUT = 250; private Context mContext; private PopupWindow mPopup; private ListAdapter mAdapter; private DropDownListView mDropDownList; private int mDropDownHeight = ViewGroup.LayoutParams.WRAP_CONTENT; private int mDropDownWidth = ViewGroup.LayoutParams.WRAP_CONTENT; private int mDropDownHorizontalOffset; private int mDropDownVerticalOffset; private boolean mDropDownVerticalOffsetSet; private int mListItemExpandMaximum = Integer.MAX_VALUE; private View mPromptView; private int mPromptPosition = POSITION_PROMPT_ABOVE; private DataSetObserver mObserver; private View mDropDownAnchorView; private Drawable mDropDownListHighlight; private AdapterView.OnItemClickListener mItemClickListener; private AdapterView.OnItemSelectedListener mItemSelectedListener; private final ResizePopupRunnable mResizePopupRunnable = new ResizePopupRunnable(); private final PopupTouchInterceptor mTouchInterceptor = new PopupTouchInterceptor(); private final PopupScrollListener mScrollListener = new PopupScrollListener(); private final ListSelectorHider mHideSelector = new ListSelectorHider(); private Handler mHandler = new Handler(); private Rect mTempRect = new Rect(); private boolean mModal; public static final int POSITION_PROMPT_ABOVE = 0; public static final int POSITION_PROMPT_BELOW = 1; public IcsListPopupWindow(Context context) { this(context, null, R.attr.listPopupWindowStyle); } public IcsListPopupWindow(Context context, AttributeSet attrs, int defStyleAttr) { mContext = context; mPopup = new PopupWindow(context, attrs, defStyleAttr); mPopup.setInputMethodMode(PopupWindow.INPUT_METHOD_NEEDED); } public IcsListPopupWindow(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { mContext = context; if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) { Context wrapped = new ContextThemeWrapper(context, defStyleRes); mPopup = new PopupWindow(wrapped, attrs, defStyleAttr); } else { mPopup = new PopupWindow(context, attrs, defStyleAttr, defStyleRes); } mPopup.setInputMethodMode(PopupWindow.INPUT_METHOD_NEEDED); } public void setAdapter(ListAdapter adapter) { if (mObserver == null) { mObserver = new PopupDataSetObserver(); } else if (mAdapter != null) { mAdapter.unregisterDataSetObserver(mObserver); } mAdapter = adapter; if (mAdapter != null) { adapter.registerDataSetObserver(mObserver); } if (mDropDownList != null) { mDropDownList.setAdapter(mAdapter); } } public void setPromptPosition(int position) { mPromptPosition = position; } public void setModal(boolean modal) { mModal = true; mPopup.setFocusable(modal); } public void setBackgroundDrawable(Drawable d) { mPopup.setBackgroundDrawable(d); } public void setAnchorView(View anchor) { mDropDownAnchorView = anchor; } public void setHorizontalOffset(int offset) { mDropDownHorizontalOffset = offset; } public void setVerticalOffset(int offset) { mDropDownVerticalOffset = offset; mDropDownVerticalOffsetSet = true; } public void setContentWidth(int width) { Drawable popupBackground = mPopup.getBackground(); if (popupBackground != null) { popupBackground.getPadding(mTempRect); mDropDownWidth = mTempRect.left + mTempRect.right + width; } else { mDropDownWidth = width; } } public void setOnItemClickListener(AdapterView.OnItemClickListener clickListener) { mItemClickListener = clickListener; } public void show() { int height = buildDropDown(); int widthSpec = 0; int heightSpec = 0; boolean noInputMethod = isInputMethodNotNeeded(); //XXX mPopup.setAllowScrollingAnchorParent(!noInputMethod); if (mPopup.isShowing()) { if (mDropDownWidth == ViewGroup.LayoutParams.MATCH_PARENT) { // The call to PopupWindow's update method below can accept -1 for any // value you do not want to update. widthSpec = -1; } else if (mDropDownWidth == ViewGroup.LayoutParams.WRAP_CONTENT) { widthSpec = mDropDownAnchorView.getWidth(); } else { widthSpec = mDropDownWidth; } if (mDropDownHeight == ViewGroup.LayoutParams.MATCH_PARENT) { // The call to PopupWindow's update method below can accept -1 for any // value you do not want to update. heightSpec = noInputMethod ? height : ViewGroup.LayoutParams.MATCH_PARENT; if (noInputMethod) { mPopup.setWindowLayoutMode( mDropDownWidth == ViewGroup.LayoutParams.MATCH_PARENT ? ViewGroup.LayoutParams.MATCH_PARENT : 0, 0); } else { mPopup.setWindowLayoutMode( mDropDownWidth == ViewGroup.LayoutParams.MATCH_PARENT ? ViewGroup.LayoutParams.MATCH_PARENT : 0, ViewGroup.LayoutParams.MATCH_PARENT); } } else if (mDropDownHeight == ViewGroup.LayoutParams.WRAP_CONTENT) { heightSpec = height; } else { heightSpec = mDropDownHeight; } mPopup.setOutsideTouchable(true); mPopup.update(mDropDownAnchorView, mDropDownHorizontalOffset, mDropDownVerticalOffset, widthSpec, heightSpec); } else { if (mDropDownWidth == ViewGroup.LayoutParams.MATCH_PARENT) { widthSpec = ViewGroup.LayoutParams.MATCH_PARENT; } else { if (mDropDownWidth == ViewGroup.LayoutParams.WRAP_CONTENT) { mPopup.setWidth(mDropDownAnchorView.getWidth()); } else { mPopup.setWidth(mDropDownWidth); } } if (mDropDownHeight == ViewGroup.LayoutParams.MATCH_PARENT) { heightSpec = ViewGroup.LayoutParams.MATCH_PARENT; } else { if (mDropDownHeight == ViewGroup.LayoutParams.WRAP_CONTENT) { mPopup.setHeight(height); } else { mPopup.setHeight(mDropDownHeight); } } mPopup.setWindowLayoutMode(widthSpec, heightSpec); //XXX mPopup.setClipToScreenEnabled(true); // use outside touchable to dismiss drop down when touching outside of it, so // only set this if the dropdown is not always visible mPopup.setOutsideTouchable(true); mPopup.setTouchInterceptor(mTouchInterceptor); mPopup.showAsDropDown(mDropDownAnchorView, mDropDownHorizontalOffset, mDropDownVerticalOffset); mDropDownList.setSelection(ListView.INVALID_POSITION); if (!mModal || mDropDownList.isInTouchMode()) { clearListSelection(); } if (!mModal) { mHandler.post(mHideSelector); } } } public void dismiss() { mPopup.dismiss(); if (mPromptView != null) { final ViewParent parent = mPromptView.getParent(); if (parent instanceof ViewGroup) { final ViewGroup group = (ViewGroup) parent; group.removeView(mPromptView); } } mPopup.setContentView(null); mDropDownList = null; mHandler.removeCallbacks(mResizePopupRunnable); } public void setOnDismissListener(PopupWindow.OnDismissListener listener) { mPopup.setOnDismissListener(listener); } public void setInputMethodMode(int mode) { mPopup.setInputMethodMode(mode); } public void clearListSelection() { final DropDownListView list = mDropDownList; if (list != null) { // WARNING: Please read the comment where mListSelectionHidden is declared list.mListSelectionHidden = true; //XXX list.hideSelector(); list.requestLayout(); } } public boolean isShowing() { return mPopup.isShowing(); } private boolean isInputMethodNotNeeded() { return mPopup.getInputMethodMode() == PopupWindow.INPUT_METHOD_NOT_NEEDED; } public ListView getListView() { return mDropDownList; } private int buildDropDown() { ViewGroup dropDownView; int otherHeights = 0; if (mDropDownList == null) { Context context = mContext; mDropDownList = new DropDownListView(context, !mModal); if (mDropDownListHighlight != null) { mDropDownList.setSelector(mDropDownListHighlight); } mDropDownList.setAdapter(mAdapter); mDropDownList.setOnItemClickListener(mItemClickListener); mDropDownList.setFocusable(true); mDropDownList.setFocusableInTouchMode(true); mDropDownList.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { if (position != -1) { DropDownListView dropDownList = mDropDownList; if (dropDownList != null) { dropDownList.mListSelectionHidden = false; } } } public void onNothingSelected(AdapterView<?> parent) { } }); mDropDownList.setOnScrollListener(mScrollListener); if (mItemSelectedListener != null) { mDropDownList.setOnItemSelectedListener(mItemSelectedListener); } dropDownView = mDropDownList; View hintView = mPromptView; if (hintView != null) { // if an hint has been specified, we accomodate more space for it and // add a text view in the drop down menu, at the bottom of the list LinearLayout hintContainer = new LinearLayout(context); hintContainer.setOrientation(LinearLayout.VERTICAL); LinearLayout.LayoutParams hintParams = new LinearLayout.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, 0, 1.0f ); switch (mPromptPosition) { case POSITION_PROMPT_BELOW: hintContainer.addView(dropDownView, hintParams); hintContainer.addView(hintView); break; case POSITION_PROMPT_ABOVE: hintContainer.addView(hintView); hintContainer.addView(dropDownView, hintParams); break; default: break; } // measure the hint's height to find how much more vertical space // we need to add to the drop down's height int widthSpec = MeasureSpec.makeMeasureSpec(mDropDownWidth, MeasureSpec.AT_MOST); int heightSpec = MeasureSpec.UNSPECIFIED; hintView.measure(widthSpec, heightSpec); hintParams = (LinearLayout.LayoutParams) hintView.getLayoutParams(); otherHeights = hintView.getMeasuredHeight() + hintParams.topMargin + hintParams.bottomMargin; dropDownView = hintContainer; } mPopup.setContentView(dropDownView); } else { dropDownView = (ViewGroup) mPopup.getContentView(); final View view = mPromptView; if (view != null) { LinearLayout.LayoutParams hintParams = (LinearLayout.LayoutParams) view.getLayoutParams(); otherHeights = view.getMeasuredHeight() + hintParams.topMargin + hintParams.bottomMargin; } } // getMaxAvailableHeight() subtracts the padding, so we put it back // to get the available height for the whole window int padding = 0; Drawable background = mPopup.getBackground(); if (background != null) { background.getPadding(mTempRect); padding = mTempRect.top + mTempRect.bottom; // If we don't have an explicit vertical offset, determine one from the window // background so that content will line up. if (!mDropDownVerticalOffsetSet) { mDropDownVerticalOffset = -mTempRect.top; } } // Max height available on the screen for a popup. boolean ignoreBottomDecorations = mPopup.getInputMethodMode() == PopupWindow.INPUT_METHOD_NOT_NEEDED; final int maxHeight = /*mPopup.*/getMaxAvailableHeight( mDropDownAnchorView, mDropDownVerticalOffset, ignoreBottomDecorations); if (mDropDownHeight == ViewGroup.LayoutParams.MATCH_PARENT) { return maxHeight + padding; } final int listContent = /*mDropDownList.*/measureHeightOfChildren(MeasureSpec.UNSPECIFIED, 0, -1/*ListView.NO_POSITION*/, maxHeight - otherHeights, -1); // add padding only if the list has items in it, that way we don't show // the popup if it is not needed if (listContent > 0) otherHeights += padding; return listContent + otherHeights; } private int getMaxAvailableHeight(View anchor, int yOffset, boolean ignoreBottomDecorations) { final Rect displayFrame = new Rect(); anchor.getWindowVisibleDisplayFrame(displayFrame); final int[] anchorPos = new int[2]; anchor.getLocationOnScreen(anchorPos); int bottomEdge = displayFrame.bottom; if (ignoreBottomDecorations) { Resources res = anchor.getContext().getResources(); bottomEdge = res.getDisplayMetrics().heightPixels; } final int distanceToBottom = bottomEdge - (anchorPos[1] + anchor.getHeight()) - yOffset; final int distanceToTop = anchorPos[1] - displayFrame.top + yOffset; // anchorPos[1] is distance from anchor to top of screen int returnedHeight = Math.max(distanceToBottom, distanceToTop); if (mPopup.getBackground() != null) { mPopup.getBackground().getPadding(mTempRect); returnedHeight -= mTempRect.top + mTempRect.bottom; } return returnedHeight; } private int measureHeightOfChildren(int widthMeasureSpec, int startPosition, int endPosition, final int maxHeight, int disallowPartialChildPosition) { final ListAdapter adapter = mAdapter; if (adapter == null) { return mDropDownList.getListPaddingTop() + mDropDownList.getListPaddingBottom(); } // Include the padding of the list int returnedHeight = mDropDownList.getListPaddingTop() + mDropDownList.getListPaddingBottom(); final int dividerHeight = ((mDropDownList.getDividerHeight() > 0) && mDropDownList.getDivider() != null) ? mDropDownList.getDividerHeight() : 0; // The previous height value that was less than maxHeight and contained // no partial children int prevHeightWithoutPartialChild = 0; int i; View child; // mItemCount - 1 since endPosition parameter is inclusive endPosition = (endPosition == -1/*NO_POSITION*/) ? adapter.getCount() - 1 : endPosition; for (i = startPosition; i <= endPosition; ++i) { child = mAdapter.getView(i, null, mDropDownList); if (mDropDownList.getCacheColorHint() != 0) { child.setDrawingCacheBackgroundColor(mDropDownList.getCacheColorHint()); } measureScrapChild(child, i, widthMeasureSpec); if (i > 0) { // Count the divider for all but one child returnedHeight += dividerHeight; } returnedHeight += child.getMeasuredHeight(); if (returnedHeight >= maxHeight) { // We went over, figure out which height to return. If returnedHeight > maxHeight, // then the i'th position did not fit completely. return (disallowPartialChildPosition >= 0) // Disallowing is enabled (> -1) && (i > disallowPartialChildPosition) // We've past the min pos && (prevHeightWithoutPartialChild > 0) // We have a prev height && (returnedHeight != maxHeight) // i'th child did not fit completely ? prevHeightWithoutPartialChild : maxHeight; } if ((disallowPartialChildPosition >= 0) && (i >= disallowPartialChildPosition)) { prevHeightWithoutPartialChild = returnedHeight; } } // At this point, we went through the range of children, and they each // completely fit, so return the returnedHeight return returnedHeight; } private void measureScrapChild(View child, int position, int widthMeasureSpec) { ListView.LayoutParams p = (ListView.LayoutParams) child.getLayoutParams(); if (p == null) { p = new ListView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, 0); child.setLayoutParams(p); } //XXX p.viewType = mAdapter.getItemViewType(position); //XXX p.forceAdd = true; int childWidthSpec = ViewGroup.getChildMeasureSpec(widthMeasureSpec, mDropDownList.getPaddingLeft() + mDropDownList.getPaddingRight(), p.width); int lpHeight = p.height; int childHeightSpec; if (lpHeight > 0) { childHeightSpec = MeasureSpec.makeMeasureSpec(lpHeight, MeasureSpec.EXACTLY); } else { childHeightSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED); } child.measure(childWidthSpec, childHeightSpec); } private static class DropDownListView extends ListView { /* * WARNING: This is a workaround for a touch mode issue. * * Touch mode is propagated lazily to windows. This causes problems in * the following scenario: * - Type something in the AutoCompleteTextView and get some results * - Move down with the d-pad to select an item in the list * - Move up with the d-pad until the selection disappears * - Type more text in the AutoCompleteTextView *using the soft keyboard* * and get new results; you are now in touch mode * - The selection comes back on the first item in the list, even though * the list is supposed to be in touch mode * * Using the soft keyboard triggers the touch mode change but that change * is propagated to our window only after the first list layout, therefore * after the list attempts to resurrect the selection. * * The trick to work around this issue is to pretend the list is in touch * mode when we know that the selection should not appear, that is when * we know the user moved the selection away from the list. * * This boolean is set to true whenever we explicitly hide the list's * selection and reset to false whenever we know the user moved the * selection back to the list. * * When this boolean is true, isInTouchMode() returns true, otherwise it * returns super.isInTouchMode(). */ private boolean mListSelectionHidden; private boolean mHijackFocus; public DropDownListView(Context context, boolean hijackFocus) { super(context, null, /*com.android.internal.*/R.attr.dropDownListViewStyle); mHijackFocus = hijackFocus; // TODO: Add an API to control this setCacheColorHint(0); // Transparent, since the background drawable could be anything. } //XXX @Override //View obtainView(int position, boolean[] isScrap) { // View view = super.obtainView(position, isScrap); // if (view instanceof TextView) { // ((TextView) view).setHorizontallyScrolling(true); // } // return view; //} @Override public boolean isInTouchMode() { // WARNING: Please read the comment where mListSelectionHidden is declared return (mHijackFocus && mListSelectionHidden) || super.isInTouchMode(); } @Override public boolean hasWindowFocus() { return mHijackFocus || super.hasWindowFocus(); } @Override public boolean isFocused() { return mHijackFocus || super.isFocused(); } @Override public boolean hasFocus() { return mHijackFocus || super.hasFocus(); } } private class PopupDataSetObserver extends DataSetObserver { @Override public void onChanged() { if (isShowing()) { // Resize the popup to fit new content show(); } } @Override public void onInvalidated() { dismiss(); } } private class ListSelectorHider implements Runnable { public void run() { clearListSelection(); } } private class ResizePopupRunnable implements Runnable { public void run() { if (mDropDownList != null && mDropDownList.getCount() > mDropDownList.getChildCount() && mDropDownList.getChildCount() <= mListItemExpandMaximum) { mPopup.setInputMethodMode(PopupWindow.INPUT_METHOD_NOT_NEEDED); show(); } } } private class PopupTouchInterceptor implements OnTouchListener { public boolean onTouch(View v, MotionEvent event) { final int action = event.getAction(); final int x = (int) event.getX(); final int y = (int) event.getY(); if (action == MotionEvent.ACTION_DOWN && mPopup != null && mPopup.isShowing() && (x >= 0 && x < mPopup.getWidth() && y >= 0 && y < mPopup.getHeight())) { mHandler.postDelayed(mResizePopupRunnable, EXPAND_LIST_TIMEOUT); } else if (action == MotionEvent.ACTION_UP) { mHandler.removeCallbacks(mResizePopupRunnable); } return false; } } private class PopupScrollListener implements ListView.OnScrollListener { public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { } public void onScrollStateChanged(AbsListView view, int scrollState) { if (scrollState == SCROLL_STATE_TOUCH_SCROLL && !isInputMethodNotNeeded() && mPopup.getContentView() != null) { mHandler.removeCallbacks(mResizePopupRunnable); mResizePopupRunnable.run(); } } } }
Java
/* * Copyright (C) 2010 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.internal.widget; import org.xmlpull.v1.XmlPullParser; import android.app.Activity; import android.content.Context; import android.content.pm.ApplicationInfo; import android.content.pm.PackageManager; import android.content.pm.PackageManager.NameNotFoundException; import android.content.res.AssetManager; import android.content.res.Configuration; import android.content.res.TypedArray; import android.content.res.XmlResourceParser; import android.graphics.drawable.Drawable; import android.os.Build; import android.os.Parcel; import android.os.Parcelable; import android.text.TextUtils; import android.util.AttributeSet; import android.util.Log; import android.view.Gravity; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.view.ViewParent; import android.view.accessibility.AccessibilityEvent; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.SpinnerAdapter; import android.widget.TextView; import com.actionbarsherlock.R; import com.actionbarsherlock.app.ActionBar; import com.actionbarsherlock.app.ActionBar.OnNavigationListener; import com.actionbarsherlock.internal.ActionBarSherlockCompat; import com.actionbarsherlock.internal.view.menu.ActionMenuItem; import com.actionbarsherlock.internal.view.menu.ActionMenuPresenter; import com.actionbarsherlock.internal.view.menu.ActionMenuView; import com.actionbarsherlock.internal.view.menu.MenuBuilder; import com.actionbarsherlock.internal.view.menu.MenuItemImpl; import com.actionbarsherlock.internal.view.menu.MenuPresenter; import com.actionbarsherlock.internal.view.menu.MenuView; import com.actionbarsherlock.internal.view.menu.SubMenuBuilder; import com.actionbarsherlock.view.CollapsibleActionView; import com.actionbarsherlock.view.Menu; import com.actionbarsherlock.view.MenuItem; import com.actionbarsherlock.view.Window; import static com.actionbarsherlock.internal.ResourcesCompat.getResources_getBoolean; /** * @hide */ public class ActionBarView extends AbsActionBarView { private static final String TAG = "ActionBarView"; private static final boolean DEBUG = false; /** * Display options applied by default */ public static final int DISPLAY_DEFAULT = 0; /** * Display options that require re-layout as opposed to a simple invalidate */ private static final int DISPLAY_RELAYOUT_MASK = ActionBar.DISPLAY_SHOW_HOME | ActionBar.DISPLAY_USE_LOGO | ActionBar.DISPLAY_HOME_AS_UP | ActionBar.DISPLAY_SHOW_CUSTOM | ActionBar.DISPLAY_SHOW_TITLE; private static final int DEFAULT_CUSTOM_GRAVITY = Gravity.LEFT | Gravity.CENTER_VERTICAL; private int mNavigationMode; private int mDisplayOptions = -1; private CharSequence mTitle; private CharSequence mSubtitle; private Drawable mIcon; private Drawable mLogo; private HomeView mHomeLayout; private HomeView mExpandedHomeLayout; private LinearLayout mTitleLayout; private TextView mTitleView; private TextView mSubtitleView; private View mTitleUpView; private IcsSpinner mSpinner; private IcsLinearLayout mListNavLayout; private ScrollingTabContainerView mTabScrollView; private View mCustomNavView; private IcsProgressBar mProgressView; private IcsProgressBar mIndeterminateProgressView; private int mProgressBarPadding; private int mItemPadding; private int mTitleStyleRes; private int mSubtitleStyleRes; private int mProgressStyle; private int mIndeterminateProgressStyle; private boolean mUserTitle; private boolean mIncludeTabs; private boolean mIsCollapsable; private boolean mIsCollapsed; private MenuBuilder mOptionsMenu; private ActionBarContextView mContextView; private ActionMenuItem mLogoNavItem; private SpinnerAdapter mSpinnerAdapter; private OnNavigationListener mCallback; //UNUSED private Runnable mTabSelector; private ExpandedActionViewMenuPresenter mExpandedMenuPresenter; View mExpandedActionView; Window.Callback mWindowCallback; @SuppressWarnings("rawtypes") private final IcsAdapterView.OnItemSelectedListener mNavItemSelectedListener = new IcsAdapterView.OnItemSelectedListener() { public void onItemSelected(IcsAdapterView parent, View view, int position, long id) { if (mCallback != null) { mCallback.onNavigationItemSelected(position, id); } } public void onNothingSelected(IcsAdapterView parent) { // Do nothing } }; private final OnClickListener mExpandedActionViewUpListener = new OnClickListener() { @Override public void onClick(View v) { final MenuItemImpl item = mExpandedMenuPresenter.mCurrentExpandedItem; if (item != null) { item.collapseActionView(); } } }; private final OnClickListener mUpClickListener = new OnClickListener() { public void onClick(View v) { mWindowCallback.onMenuItemSelected(Window.FEATURE_OPTIONS_PANEL, mLogoNavItem); } }; public ActionBarView(Context context, AttributeSet attrs) { super(context, attrs); // Background is always provided by the container. setBackgroundResource(0); TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.SherlockActionBar, R.attr.actionBarStyle, 0); ApplicationInfo appInfo = context.getApplicationInfo(); PackageManager pm = context.getPackageManager(); mNavigationMode = a.getInt(R.styleable.SherlockActionBar_navigationMode, ActionBar.NAVIGATION_MODE_STANDARD); mTitle = a.getText(R.styleable.SherlockActionBar_title); mSubtitle = a.getText(R.styleable.SherlockActionBar_subtitle); mLogo = a.getDrawable(R.styleable.SherlockActionBar_logo); if (mLogo == null) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) { if (context instanceof Activity) { //Even though native methods existed in API 9 and 10 they don't work //so just parse the manifest to look for the logo pre-Honeycomb final int resId = loadLogoFromManifest((Activity) context); if (resId != 0) { mLogo = context.getResources().getDrawable(resId); } } } else { if (context instanceof Activity) { try { mLogo = pm.getActivityLogo(((Activity) context).getComponentName()); } catch (NameNotFoundException e) { Log.e(TAG, "Activity component name not found!", e); } } if (mLogo == null) { mLogo = appInfo.loadLogo(pm); } } } mIcon = a.getDrawable(R.styleable.SherlockActionBar_icon); if (mIcon == null) { if (context instanceof Activity) { try { mIcon = pm.getActivityIcon(((Activity) context).getComponentName()); } catch (NameNotFoundException e) { Log.e(TAG, "Activity component name not found!", e); } } if (mIcon == null) { mIcon = appInfo.loadIcon(pm); } } final LayoutInflater inflater = LayoutInflater.from(context); final int homeResId = a.getResourceId( R.styleable.SherlockActionBar_homeLayout, R.layout.abs__action_bar_home); mHomeLayout = (HomeView) inflater.inflate(homeResId, this, false); mExpandedHomeLayout = (HomeView) inflater.inflate(homeResId, this, false); mExpandedHomeLayout.setUp(true); mExpandedHomeLayout.setOnClickListener(mExpandedActionViewUpListener); mExpandedHomeLayout.setContentDescription(getResources().getText( R.string.abs__action_bar_up_description)); mTitleStyleRes = a.getResourceId(R.styleable.SherlockActionBar_titleTextStyle, 0); mSubtitleStyleRes = a.getResourceId(R.styleable.SherlockActionBar_subtitleTextStyle, 0); mProgressStyle = a.getResourceId(R.styleable.SherlockActionBar_progressBarStyle, 0); mIndeterminateProgressStyle = a.getResourceId( R.styleable.SherlockActionBar_indeterminateProgressStyle, 0); mProgressBarPadding = a.getDimensionPixelOffset(R.styleable.SherlockActionBar_progressBarPadding, 0); mItemPadding = a.getDimensionPixelOffset(R.styleable.SherlockActionBar_itemPadding, 0); setDisplayOptions(a.getInt(R.styleable.SherlockActionBar_displayOptions, DISPLAY_DEFAULT)); final int customNavId = a.getResourceId(R.styleable.SherlockActionBar_customNavigationLayout, 0); if (customNavId != 0) { mCustomNavView = inflater.inflate(customNavId, this, false); mNavigationMode = ActionBar.NAVIGATION_MODE_STANDARD; setDisplayOptions(mDisplayOptions | ActionBar.DISPLAY_SHOW_CUSTOM); } mContentHeight = a.getLayoutDimension(R.styleable.SherlockActionBar_height, 0); a.recycle(); mLogoNavItem = new ActionMenuItem(context, 0, android.R.id.home, 0, 0, mTitle); mHomeLayout.setOnClickListener(mUpClickListener); mHomeLayout.setClickable(true); mHomeLayout.setFocusable(true); } /** * Attempt to programmatically load the logo from the manifest file of an * activity by using an XML pull parser. This should allow us to read the * logo attribute regardless of the platform it is being run on. * * @param activity Activity instance. * @return Logo resource ID. */ private static int loadLogoFromManifest(Activity activity) { int logo = 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 <application> has the attribute if (DEBUG) Log.d(TAG, "Got <application>"); for (int i = xml.getAttributeCount() - 1; i >= 0; i--) { if (DEBUG) Log.d(TAG, xml.getAttributeName(i) + ": " + xml.getAttributeValue(i)); if ("logo".equals(xml.getAttributeName(i))) { logo = xml.getAttributeResourceValue(i, 0); break; //out of for loop } } } else if ("activity".equals(name)) { //Check if the <activity> is us and has the attribute if (DEBUG) Log.d(TAG, "Got <activity>"); Integer activityLogo = null; String activityPackage = null; boolean isOurActivity = false; for (int i = xml.getAttributeCount() - 1; i >= 0; i--) { if (DEBUG) Log.d(TAG, xml.getAttributeName(i) + ": " + xml.getAttributeValue(i)); //We need both uiOptions and name attributes String attrName = xml.getAttributeName(i); if ("logo".equals(attrName)) { activityLogo = xml.getAttributeResourceValue(i, 0); } else if ("name".equals(attrName)) { activityPackage = ActionBarSherlockCompat.cleanActivityName(packageName, xml.getAttributeValue(i)); if (!thisPackage.equals(activityPackage)) { break; //on to the next } isOurActivity = true; } //Make sure we have both attributes before processing if ((activityLogo != null) && (activityPackage != null)) { //Our activity, logo specified, override with our value logo = activityLogo.intValue(); } } if (isOurActivity) { //If we matched our activity but it had no logo don't //do any more processing of the manifest break; } } } eventType = xml.nextToken(); } } catch (Exception e) { e.printStackTrace(); } if (DEBUG) Log.i(TAG, "Returning " + Integer.toHexString(logo)); return logo; } /* * Must be public so we can dispatch pre-2.2 via ActionBarImpl. */ @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); mTitleView = null; mSubtitleView = null; mTitleUpView = null; if (mTitleLayout != null && mTitleLayout.getParent() == this) { removeView(mTitleLayout); } mTitleLayout = null; if ((mDisplayOptions & ActionBar.DISPLAY_SHOW_TITLE) != 0) { initTitle(); } if (mTabScrollView != null && mIncludeTabs) { ViewGroup.LayoutParams lp = mTabScrollView.getLayoutParams(); if (lp != null) { lp.width = LayoutParams.WRAP_CONTENT; lp.height = LayoutParams.MATCH_PARENT; } mTabScrollView.setAllowCollapse(true); } } /** * Set the window callback used to invoke menu items; used for dispatching home button presses. * @param cb Window callback to dispatch to */ public void setWindowCallback(Window.Callback cb) { mWindowCallback = cb; } @Override public void onDetachedFromWindow() { super.onDetachedFromWindow(); //UNUSED removeCallbacks(mTabSelector); if (mActionMenuPresenter != null) { mActionMenuPresenter.hideOverflowMenu(); mActionMenuPresenter.hideSubMenus(); } } @Override public boolean shouldDelayChildPressedState() { return false; } public void initProgress() { mProgressView = new IcsProgressBar(mContext, null, 0, mProgressStyle); mProgressView.setId(R.id.abs__progress_horizontal); mProgressView.setMax(10000); addView(mProgressView); } public void initIndeterminateProgress() { mIndeterminateProgressView = new IcsProgressBar(mContext, null, 0, mIndeterminateProgressStyle); mIndeterminateProgressView.setId(R.id.abs__progress_circular); addView(mIndeterminateProgressView); } @Override public void setSplitActionBar(boolean splitActionBar) { if (mSplitActionBar != splitActionBar) { if (mMenuView != null) { final ViewGroup oldParent = (ViewGroup) mMenuView.getParent(); if (oldParent != null) { oldParent.removeView(mMenuView); } if (splitActionBar) { if (mSplitView != null) { mSplitView.addView(mMenuView); } } else { addView(mMenuView); } } if (mSplitView != null) { mSplitView.setVisibility(splitActionBar ? VISIBLE : GONE); } super.setSplitActionBar(splitActionBar); } } public boolean isSplitActionBar() { return mSplitActionBar; } public boolean hasEmbeddedTabs() { return mIncludeTabs; } public void setEmbeddedTabView(ScrollingTabContainerView tabs) { if (mTabScrollView != null) { removeView(mTabScrollView); } mTabScrollView = tabs; mIncludeTabs = tabs != null; if (mIncludeTabs && mNavigationMode == ActionBar.NAVIGATION_MODE_TABS) { addView(mTabScrollView); ViewGroup.LayoutParams lp = mTabScrollView.getLayoutParams(); lp.width = LayoutParams.WRAP_CONTENT; lp.height = LayoutParams.MATCH_PARENT; tabs.setAllowCollapse(true); } } public void setCallback(OnNavigationListener callback) { mCallback = callback; } public void setMenu(Menu menu, MenuPresenter.Callback cb) { if (menu == mOptionsMenu) return; if (mOptionsMenu != null) { mOptionsMenu.removeMenuPresenter(mActionMenuPresenter); mOptionsMenu.removeMenuPresenter(mExpandedMenuPresenter); } MenuBuilder builder = (MenuBuilder) menu; mOptionsMenu = builder; if (mMenuView != null) { final ViewGroup oldParent = (ViewGroup) mMenuView.getParent(); if (oldParent != null) { oldParent.removeView(mMenuView); } } if (mActionMenuPresenter == null) { mActionMenuPresenter = new ActionMenuPresenter(mContext); mActionMenuPresenter.setCallback(cb); mActionMenuPresenter.setId(R.id.abs__action_menu_presenter); mExpandedMenuPresenter = new ExpandedActionViewMenuPresenter(); } ActionMenuView menuView; final LayoutParams layoutParams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT); if (!mSplitActionBar) { mActionMenuPresenter.setExpandedActionViewsExclusive( getResources_getBoolean(getContext(), R.bool.abs__action_bar_expanded_action_views_exclusive)); configPresenters(builder); menuView = (ActionMenuView) mActionMenuPresenter.getMenuView(this); final ViewGroup oldParent = (ViewGroup) menuView.getParent(); if (oldParent != null && oldParent != this) { oldParent.removeView(menuView); } addView(menuView, layoutParams); } else { mActionMenuPresenter.setExpandedActionViewsExclusive(false); // Allow full screen width in split mode. mActionMenuPresenter.setWidthLimit( getContext().getResources().getDisplayMetrics().widthPixels, true); // No limit to the item count; use whatever will fit. mActionMenuPresenter.setItemLimit(Integer.MAX_VALUE); // Span the whole width layoutParams.width = LayoutParams.MATCH_PARENT; configPresenters(builder); menuView = (ActionMenuView) mActionMenuPresenter.getMenuView(this); if (mSplitView != null) { final ViewGroup oldParent = (ViewGroup) menuView.getParent(); if (oldParent != null && oldParent != mSplitView) { oldParent.removeView(menuView); } menuView.setVisibility(getAnimatedVisibility()); mSplitView.addView(menuView, layoutParams); } else { // We'll add this later if we missed it this time. menuView.setLayoutParams(layoutParams); } } mMenuView = menuView; } private void configPresenters(MenuBuilder builder) { if (builder != null) { builder.addMenuPresenter(mActionMenuPresenter); builder.addMenuPresenter(mExpandedMenuPresenter); } else { mActionMenuPresenter.initForMenu(mContext, null); mExpandedMenuPresenter.initForMenu(mContext, null); mActionMenuPresenter.updateMenuView(true); mExpandedMenuPresenter.updateMenuView(true); } } public boolean hasExpandedActionView() { return mExpandedMenuPresenter != null && mExpandedMenuPresenter.mCurrentExpandedItem != null; } public void collapseActionView() { final MenuItemImpl item = mExpandedMenuPresenter == null ? null : mExpandedMenuPresenter.mCurrentExpandedItem; if (item != null) { item.collapseActionView(); } } public void setCustomNavigationView(View view) { final boolean showCustom = (mDisplayOptions & ActionBar.DISPLAY_SHOW_CUSTOM) != 0; if (mCustomNavView != null && showCustom) { removeView(mCustomNavView); } mCustomNavView = view; if (mCustomNavView != null && showCustom) { addView(mCustomNavView); } } public CharSequence getTitle() { return mTitle; } /** * Set the action bar title. This will always replace or override window titles. * @param title Title to set * * @see #setWindowTitle(CharSequence) */ public void setTitle(CharSequence title) { mUserTitle = true; setTitleImpl(title); } /** * Set the window title. A window title will always be replaced or overridden by a user title. * @param title Title to set * * @see #setTitle(CharSequence) */ public void setWindowTitle(CharSequence title) { if (!mUserTitle) { setTitleImpl(title); } } private void setTitleImpl(CharSequence title) { mTitle = title; if (mTitleView != null) { mTitleView.setText(title); final boolean visible = mExpandedActionView == null && (mDisplayOptions & ActionBar.DISPLAY_SHOW_TITLE) != 0 && (!TextUtils.isEmpty(mTitle) || !TextUtils.isEmpty(mSubtitle)); mTitleLayout.setVisibility(visible ? VISIBLE : GONE); } if (mLogoNavItem != null) { mLogoNavItem.setTitle(title); } } public CharSequence getSubtitle() { return mSubtitle; } public void setSubtitle(CharSequence subtitle) { mSubtitle = subtitle; if (mSubtitleView != null) { mSubtitleView.setText(subtitle); mSubtitleView.setVisibility(subtitle != null ? VISIBLE : GONE); final boolean visible = mExpandedActionView == null && (mDisplayOptions & ActionBar.DISPLAY_SHOW_TITLE) != 0 && (!TextUtils.isEmpty(mTitle) || !TextUtils.isEmpty(mSubtitle)); mTitleLayout.setVisibility(visible ? VISIBLE : GONE); } } public void setHomeButtonEnabled(boolean enable) { mHomeLayout.setEnabled(enable); mHomeLayout.setFocusable(enable); // Make sure the home button has an accurate content description for accessibility. if (!enable) { mHomeLayout.setContentDescription(null); } else if ((mDisplayOptions & ActionBar.DISPLAY_HOME_AS_UP) != 0) { mHomeLayout.setContentDescription(mContext.getResources().getText( R.string.abs__action_bar_up_description)); } else { mHomeLayout.setContentDescription(mContext.getResources().getText( R.string.abs__action_bar_home_description)); } } public void setDisplayOptions(int options) { final int flagsChanged = mDisplayOptions == -1 ? -1 : options ^ mDisplayOptions; mDisplayOptions = options; if ((flagsChanged & DISPLAY_RELAYOUT_MASK) != 0) { final boolean showHome = (options & ActionBar.DISPLAY_SHOW_HOME) != 0; final int vis = showHome && mExpandedActionView == null ? VISIBLE : GONE; mHomeLayout.setVisibility(vis); if ((flagsChanged & ActionBar.DISPLAY_HOME_AS_UP) != 0) { final boolean setUp = (options & ActionBar.DISPLAY_HOME_AS_UP) != 0; mHomeLayout.setUp(setUp); // Showing home as up implicitly enables interaction with it. // In honeycomb it was always enabled, so make this transition // a bit easier for developers in the common case. // (It would be silly to show it as up without responding to it.) if (setUp) { setHomeButtonEnabled(true); } } if ((flagsChanged & ActionBar.DISPLAY_USE_LOGO) != 0) { final boolean logoVis = mLogo != null && (options & ActionBar.DISPLAY_USE_LOGO) != 0; mHomeLayout.setIcon(logoVis ? mLogo : mIcon); } if ((flagsChanged & ActionBar.DISPLAY_SHOW_TITLE) != 0) { if ((options & ActionBar.DISPLAY_SHOW_TITLE) != 0) { initTitle(); } else { removeView(mTitleLayout); } } if (mTitleLayout != null && (flagsChanged & (ActionBar.DISPLAY_HOME_AS_UP | ActionBar.DISPLAY_SHOW_HOME)) != 0) { final boolean homeAsUp = (mDisplayOptions & ActionBar.DISPLAY_HOME_AS_UP) != 0; mTitleUpView.setVisibility(!showHome ? (homeAsUp ? VISIBLE : INVISIBLE) : GONE); mTitleLayout.setEnabled(!showHome && homeAsUp); } if ((flagsChanged & ActionBar.DISPLAY_SHOW_CUSTOM) != 0 && mCustomNavView != null) { if ((options & ActionBar.DISPLAY_SHOW_CUSTOM) != 0) { addView(mCustomNavView); } else { removeView(mCustomNavView); } } requestLayout(); } else { invalidate(); } // Make sure the home button has an accurate content description for accessibility. if (!mHomeLayout.isEnabled()) { mHomeLayout.setContentDescription(null); } else if ((options & ActionBar.DISPLAY_HOME_AS_UP) != 0) { mHomeLayout.setContentDescription(mContext.getResources().getText( R.string.abs__action_bar_up_description)); } else { mHomeLayout.setContentDescription(mContext.getResources().getText( R.string.abs__action_bar_home_description)); } } public void setIcon(Drawable icon) { mIcon = icon; if (icon != null && ((mDisplayOptions & ActionBar.DISPLAY_USE_LOGO) == 0 || mLogo == null)) { mHomeLayout.setIcon(icon); } } public void setIcon(int resId) { setIcon(mContext.getResources().getDrawable(resId)); } public void setLogo(Drawable logo) { mLogo = logo; if (logo != null && (mDisplayOptions & ActionBar.DISPLAY_USE_LOGO) != 0) { mHomeLayout.setIcon(logo); } } public void setLogo(int resId) { setLogo(mContext.getResources().getDrawable(resId)); } public void setNavigationMode(int mode) { final int oldMode = mNavigationMode; if (mode != oldMode) { switch (oldMode) { case ActionBar.NAVIGATION_MODE_LIST: if (mListNavLayout != null) { removeView(mListNavLayout); } break; case ActionBar.NAVIGATION_MODE_TABS: if (mTabScrollView != null && mIncludeTabs) { removeView(mTabScrollView); } } switch (mode) { case ActionBar.NAVIGATION_MODE_LIST: if (mSpinner == null) { mSpinner = new IcsSpinner(mContext, null, R.attr.actionDropDownStyle); mListNavLayout = (IcsLinearLayout) LayoutInflater.from(mContext) .inflate(R.layout.abs__action_bar_tab_bar_view, null); LinearLayout.LayoutParams params = new LinearLayout.LayoutParams( LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT); params.gravity = Gravity.CENTER; mListNavLayout.addView(mSpinner, params); } if (mSpinner.getAdapter() != mSpinnerAdapter) { mSpinner.setAdapter(mSpinnerAdapter); } mSpinner.setOnItemSelectedListener(mNavItemSelectedListener); addView(mListNavLayout); break; case ActionBar.NAVIGATION_MODE_TABS: if (mTabScrollView != null && mIncludeTabs) { addView(mTabScrollView); } break; } mNavigationMode = mode; requestLayout(); } } public void setDropdownAdapter(SpinnerAdapter adapter) { mSpinnerAdapter = adapter; if (mSpinner != null) { mSpinner.setAdapter(adapter); } } public SpinnerAdapter getDropdownAdapter() { return mSpinnerAdapter; } public void setDropdownSelectedPosition(int position) { mSpinner.setSelection(position); } public int getDropdownSelectedPosition() { return mSpinner.getSelectedItemPosition(); } public View getCustomNavigationView() { return mCustomNavView; } public int getNavigationMode() { return mNavigationMode; } public int getDisplayOptions() { return mDisplayOptions; } @Override protected ViewGroup.LayoutParams generateDefaultLayoutParams() { // Used by custom nav views if they don't supply layout params. Everything else // added to an ActionBarView should have them already. return new ActionBar.LayoutParams(DEFAULT_CUSTOM_GRAVITY); } @Override protected void onFinishInflate() { super.onFinishInflate(); addView(mHomeLayout); if (mCustomNavView != null && (mDisplayOptions & ActionBar.DISPLAY_SHOW_CUSTOM) != 0) { final ViewParent parent = mCustomNavView.getParent(); if (parent != this) { if (parent instanceof ViewGroup) { ((ViewGroup) parent).removeView(mCustomNavView); } addView(mCustomNavView); } } } private void initTitle() { if (mTitleLayout == null) { LayoutInflater inflater = LayoutInflater.from(getContext()); mTitleLayout = (LinearLayout) inflater.inflate(R.layout.abs__action_bar_title_item, this, false); mTitleView = (TextView) mTitleLayout.findViewById(R.id.abs__action_bar_title); mSubtitleView = (TextView) mTitleLayout.findViewById(R.id.abs__action_bar_subtitle); mTitleUpView = mTitleLayout.findViewById(R.id.abs__up); mTitleLayout.setOnClickListener(mUpClickListener); if (mTitleStyleRes != 0) { mTitleView.setTextAppearance(mContext, mTitleStyleRes); } if (mTitle != null) { mTitleView.setText(mTitle); } if (mSubtitleStyleRes != 0) { mSubtitleView.setTextAppearance(mContext, mSubtitleStyleRes); } if (mSubtitle != null) { mSubtitleView.setText(mSubtitle); mSubtitleView.setVisibility(VISIBLE); } final boolean homeAsUp = (mDisplayOptions & ActionBar.DISPLAY_HOME_AS_UP) != 0; final boolean showHome = (mDisplayOptions & ActionBar.DISPLAY_SHOW_HOME) != 0; mTitleUpView.setVisibility(!showHome ? (homeAsUp ? VISIBLE : INVISIBLE) : GONE); mTitleLayout.setEnabled(homeAsUp && !showHome); } addView(mTitleLayout); if (mExpandedActionView != null || (TextUtils.isEmpty(mTitle) && TextUtils.isEmpty(mSubtitle))) { // Don't show while in expanded mode or with empty text mTitleLayout.setVisibility(GONE); } } public void setContextView(ActionBarContextView view) { mContextView = view; } public void setCollapsable(boolean collapsable) { mIsCollapsable = collapsable; } public boolean isCollapsed() { return mIsCollapsed; } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { final int childCount = getChildCount(); if (mIsCollapsable) { int visibleChildren = 0; for (int i = 0; i < childCount; i++) { final View child = getChildAt(i); if (child.getVisibility() != GONE && !(child == mMenuView && mMenuView.getChildCount() == 0)) { visibleChildren++; } } if (visibleChildren == 0) { // No size for an empty action bar when collapsable. setMeasuredDimension(0, 0); mIsCollapsed = true; return; } } mIsCollapsed = false; int widthMode = MeasureSpec.getMode(widthMeasureSpec); if (widthMode != MeasureSpec.EXACTLY) { throw new IllegalStateException(getClass().getSimpleName() + " can only be used " + "with android:layout_width=\"match_parent\" (or fill_parent)"); } int heightMode = MeasureSpec.getMode(heightMeasureSpec); if (heightMode != MeasureSpec.AT_MOST) { throw new IllegalStateException(getClass().getSimpleName() + " can only be used " + "with android:layout_height=\"wrap_content\""); } int contentWidth = MeasureSpec.getSize(widthMeasureSpec); int maxHeight = mContentHeight > 0 ? mContentHeight : MeasureSpec.getSize(heightMeasureSpec); final int verticalPadding = getPaddingTop() + getPaddingBottom(); final int paddingLeft = getPaddingLeft(); final int paddingRight = getPaddingRight(); final int height = maxHeight - verticalPadding; final int childSpecHeight = MeasureSpec.makeMeasureSpec(height, MeasureSpec.AT_MOST); int availableWidth = contentWidth - paddingLeft - paddingRight; int leftOfCenter = availableWidth / 2; int rightOfCenter = leftOfCenter; HomeView homeLayout = mExpandedActionView != null ? mExpandedHomeLayout : mHomeLayout; if (homeLayout.getVisibility() != GONE) { final ViewGroup.LayoutParams lp = homeLayout.getLayoutParams(); int homeWidthSpec; if (lp.width < 0) { homeWidthSpec = MeasureSpec.makeMeasureSpec(availableWidth, MeasureSpec.AT_MOST); } else { homeWidthSpec = MeasureSpec.makeMeasureSpec(lp.width, MeasureSpec.EXACTLY); } homeLayout.measure(homeWidthSpec, MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY)); final int homeWidth = homeLayout.getMeasuredWidth() + homeLayout.getLeftOffset(); availableWidth = Math.max(0, availableWidth - homeWidth); leftOfCenter = Math.max(0, availableWidth - homeWidth); } if (mMenuView != null && mMenuView.getParent() == this) { availableWidth = measureChildView(mMenuView, availableWidth, childSpecHeight, 0); rightOfCenter = Math.max(0, rightOfCenter - mMenuView.getMeasuredWidth()); } if (mIndeterminateProgressView != null && mIndeterminateProgressView.getVisibility() != GONE) { availableWidth = measureChildView(mIndeterminateProgressView, availableWidth, childSpecHeight, 0); rightOfCenter = Math.max(0, rightOfCenter - mIndeterminateProgressView.getMeasuredWidth()); } final boolean showTitle = mTitleLayout != null && mTitleLayout.getVisibility() != GONE && (mDisplayOptions & ActionBar.DISPLAY_SHOW_TITLE) != 0; if (mExpandedActionView == null) { switch (mNavigationMode) { case ActionBar.NAVIGATION_MODE_LIST: if (mListNavLayout != null) { final int itemPaddingSize = showTitle ? mItemPadding * 2 : mItemPadding; availableWidth = Math.max(0, availableWidth - itemPaddingSize); leftOfCenter = Math.max(0, leftOfCenter - itemPaddingSize); mListNavLayout.measure( MeasureSpec.makeMeasureSpec(availableWidth, MeasureSpec.AT_MOST), MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY)); final int listNavWidth = mListNavLayout.getMeasuredWidth(); availableWidth = Math.max(0, availableWidth - listNavWidth); leftOfCenter = Math.max(0, leftOfCenter - listNavWidth); } break; case ActionBar.NAVIGATION_MODE_TABS: if (mTabScrollView != null) { final int itemPaddingSize = showTitle ? mItemPadding * 2 : mItemPadding; availableWidth = Math.max(0, availableWidth - itemPaddingSize); leftOfCenter = Math.max(0, leftOfCenter - itemPaddingSize); mTabScrollView.measure( MeasureSpec.makeMeasureSpec(availableWidth, MeasureSpec.AT_MOST), MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY)); final int tabWidth = mTabScrollView.getMeasuredWidth(); availableWidth = Math.max(0, availableWidth - tabWidth); leftOfCenter = Math.max(0, leftOfCenter - tabWidth); } break; } } View customView = null; if (mExpandedActionView != null) { customView = mExpandedActionView; } else if ((mDisplayOptions & ActionBar.DISPLAY_SHOW_CUSTOM) != 0 && mCustomNavView != null) { customView = mCustomNavView; } if (customView != null) { final ViewGroup.LayoutParams lp = generateLayoutParams(customView.getLayoutParams()); final ActionBar.LayoutParams ablp = lp instanceof ActionBar.LayoutParams ? (ActionBar.LayoutParams) lp : null; int horizontalMargin = 0; int verticalMargin = 0; if (ablp != null) { horizontalMargin = ablp.leftMargin + ablp.rightMargin; verticalMargin = ablp.topMargin + ablp.bottomMargin; } // If the action bar is wrapping to its content height, don't allow a custom // view to MATCH_PARENT. int customNavHeightMode; if (mContentHeight <= 0) { customNavHeightMode = MeasureSpec.AT_MOST; } else { customNavHeightMode = lp.height != LayoutParams.WRAP_CONTENT ? MeasureSpec.EXACTLY : MeasureSpec.AT_MOST; } final int customNavHeight = Math.max(0, (lp.height >= 0 ? Math.min(lp.height, height) : height) - verticalMargin); final int customNavWidthMode = lp.width != LayoutParams.WRAP_CONTENT ? MeasureSpec.EXACTLY : MeasureSpec.AT_MOST; int customNavWidth = Math.max(0, (lp.width >= 0 ? Math.min(lp.width, availableWidth) : availableWidth) - horizontalMargin); final int hgrav = (ablp != null ? ablp.gravity : DEFAULT_CUSTOM_GRAVITY) & Gravity.HORIZONTAL_GRAVITY_MASK; // Centering a custom view is treated specially; we try to center within the whole // action bar rather than in the available space. if (hgrav == Gravity.CENTER_HORIZONTAL && lp.width == LayoutParams.MATCH_PARENT) { customNavWidth = Math.min(leftOfCenter, rightOfCenter) * 2; } customView.measure( MeasureSpec.makeMeasureSpec(customNavWidth, customNavWidthMode), MeasureSpec.makeMeasureSpec(customNavHeight, customNavHeightMode)); availableWidth -= horizontalMargin + customView.getMeasuredWidth(); } if (mExpandedActionView == null && showTitle) { availableWidth = measureChildView(mTitleLayout, availableWidth, MeasureSpec.makeMeasureSpec(mContentHeight, MeasureSpec.EXACTLY), 0); leftOfCenter = Math.max(0, leftOfCenter - mTitleLayout.getMeasuredWidth()); } if (mContentHeight <= 0) { int measuredHeight = 0; for (int i = 0; i < childCount; i++) { View v = getChildAt(i); int paddedViewHeight = v.getMeasuredHeight() + verticalPadding; if (paddedViewHeight > measuredHeight) { measuredHeight = paddedViewHeight; } } setMeasuredDimension(contentWidth, measuredHeight); } else { setMeasuredDimension(contentWidth, maxHeight); } if (mContextView != null) { mContextView.setContentHeight(getMeasuredHeight()); } if (mProgressView != null && mProgressView.getVisibility() != GONE) { mProgressView.measure(MeasureSpec.makeMeasureSpec( contentWidth - mProgressBarPadding * 2, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(getMeasuredHeight(), MeasureSpec.AT_MOST)); } } @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { int x = getPaddingLeft(); final int y = getPaddingTop(); final int contentHeight = b - t - getPaddingTop() - getPaddingBottom(); if (contentHeight <= 0) { // Nothing to do if we can't see anything. return; } HomeView homeLayout = mExpandedActionView != null ? mExpandedHomeLayout : mHomeLayout; if (homeLayout.getVisibility() != GONE) { final int leftOffset = homeLayout.getLeftOffset(); x += positionChild(homeLayout, x + leftOffset, y, contentHeight) + leftOffset; } if (mExpandedActionView == null) { final boolean showTitle = mTitleLayout != null && mTitleLayout.getVisibility() != GONE && (mDisplayOptions & ActionBar.DISPLAY_SHOW_TITLE) != 0; if (showTitle) { x += positionChild(mTitleLayout, x, y, contentHeight); } switch (mNavigationMode) { case ActionBar.NAVIGATION_MODE_STANDARD: break; case ActionBar.NAVIGATION_MODE_LIST: if (mListNavLayout != null) { if (showTitle) x += mItemPadding; x += positionChild(mListNavLayout, x, y, contentHeight) + mItemPadding; } break; case ActionBar.NAVIGATION_MODE_TABS: if (mTabScrollView != null) { if (showTitle) x += mItemPadding; x += positionChild(mTabScrollView, x, y, contentHeight) + mItemPadding; } break; } } int menuLeft = r - l - getPaddingRight(); if (mMenuView != null && mMenuView.getParent() == this) { positionChildInverse(mMenuView, menuLeft, y, contentHeight); menuLeft -= mMenuView.getMeasuredWidth(); } if (mIndeterminateProgressView != null && mIndeterminateProgressView.getVisibility() != GONE) { positionChildInverse(mIndeterminateProgressView, menuLeft, y, contentHeight); menuLeft -= mIndeterminateProgressView.getMeasuredWidth(); } View customView = null; if (mExpandedActionView != null) { customView = mExpandedActionView; } else if ((mDisplayOptions & ActionBar.DISPLAY_SHOW_CUSTOM) != 0 && mCustomNavView != null) { customView = mCustomNavView; } if (customView != null) { ViewGroup.LayoutParams lp = customView.getLayoutParams(); final ActionBar.LayoutParams ablp = lp instanceof ActionBar.LayoutParams ? (ActionBar.LayoutParams) lp : null; final int gravity = ablp != null ? ablp.gravity : DEFAULT_CUSTOM_GRAVITY; final int navWidth = customView.getMeasuredWidth(); int topMargin = 0; int bottomMargin = 0; if (ablp != null) { x += ablp.leftMargin; menuLeft -= ablp.rightMargin; topMargin = ablp.topMargin; bottomMargin = ablp.bottomMargin; } int hgravity = gravity & Gravity.HORIZONTAL_GRAVITY_MASK; // See if we actually have room to truly center; if not push against left or right. if (hgravity == Gravity.CENTER_HORIZONTAL) { final int centeredLeft = ((getRight() - getLeft()) - navWidth) / 2; if (centeredLeft < x) { hgravity = Gravity.LEFT; } else if (centeredLeft + navWidth > menuLeft) { hgravity = Gravity.RIGHT; } } else if (gravity == -1) { hgravity = Gravity.LEFT; } int xpos = 0; switch (hgravity) { case Gravity.CENTER_HORIZONTAL: xpos = ((getRight() - getLeft()) - navWidth) / 2; break; case Gravity.LEFT: xpos = x; break; case Gravity.RIGHT: xpos = menuLeft - navWidth; break; } int vgravity = gravity & Gravity.VERTICAL_GRAVITY_MASK; if (gravity == -1) { vgravity = Gravity.CENTER_VERTICAL; } int ypos = 0; switch (vgravity) { case Gravity.CENTER_VERTICAL: final int paddedTop = getPaddingTop(); final int paddedBottom = getBottom() - getTop() - getPaddingBottom(); ypos = ((paddedBottom - paddedTop) - customView.getMeasuredHeight()) / 2; break; case Gravity.TOP: ypos = getPaddingTop() + topMargin; break; case Gravity.BOTTOM: ypos = getHeight() - getPaddingBottom() - customView.getMeasuredHeight() - bottomMargin; break; } final int customWidth = customView.getMeasuredWidth(); customView.layout(xpos, ypos, xpos + customWidth, ypos + customView.getMeasuredHeight()); x += customWidth; } if (mProgressView != null) { mProgressView.bringToFront(); final int halfProgressHeight = mProgressView.getMeasuredHeight() / 2; mProgressView.layout(mProgressBarPadding, -halfProgressHeight, mProgressBarPadding + mProgressView.getMeasuredWidth(), halfProgressHeight); } } @Override public ViewGroup.LayoutParams generateLayoutParams(AttributeSet attrs) { return new ActionBar.LayoutParams(getContext(), attrs); } @Override public ViewGroup.LayoutParams generateLayoutParams(ViewGroup.LayoutParams lp) { if (lp == null) { lp = generateDefaultLayoutParams(); } return lp; } @Override public Parcelable onSaveInstanceState() { Parcelable superState = super.onSaveInstanceState(); SavedState state = new SavedState(superState); if (mExpandedMenuPresenter != null && mExpandedMenuPresenter.mCurrentExpandedItem != null) { state.expandedMenuItemId = mExpandedMenuPresenter.mCurrentExpandedItem.getItemId(); } state.isOverflowOpen = isOverflowMenuShowing(); return state; } @Override public void onRestoreInstanceState(Parcelable p) { SavedState state = (SavedState) p; super.onRestoreInstanceState(state.getSuperState()); if (state.expandedMenuItemId != 0 && mExpandedMenuPresenter != null && mOptionsMenu != null) { final MenuItem item = mOptionsMenu.findItem(state.expandedMenuItemId); if (item != null) { item.expandActionView(); } } if (state.isOverflowOpen) { postShowOverflowMenu(); } } static class SavedState extends BaseSavedState { int expandedMenuItemId; boolean isOverflowOpen; SavedState(Parcelable superState) { super(superState); } private SavedState(Parcel in) { super(in); expandedMenuItemId = in.readInt(); isOverflowOpen = in.readInt() != 0; } @Override public void writeToParcel(Parcel out, int flags) { super.writeToParcel(out, flags); out.writeInt(expandedMenuItemId); out.writeInt(isOverflowOpen ? 1 : 0); } public static final Parcelable.Creator<SavedState> CREATOR = new Parcelable.Creator<SavedState>() { public SavedState createFromParcel(Parcel in) { return new SavedState(in); } public SavedState[] newArray(int size) { return new SavedState[size]; } }; } public static class HomeView extends FrameLayout { private View mUpView; private ImageView mIconView; private int mUpWidth; public HomeView(Context context) { this(context, null); } public HomeView(Context context, AttributeSet attrs) { super(context, attrs); } public void setUp(boolean isUp) { mUpView.setVisibility(isUp ? VISIBLE : GONE); } public void setIcon(Drawable icon) { mIconView.setImageDrawable(icon); } @Override public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) { onPopulateAccessibilityEvent(event); return true; } @Override public void onPopulateAccessibilityEvent(AccessibilityEvent event) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) { super.onPopulateAccessibilityEvent(event); } final CharSequence cdesc = getContentDescription(); if (!TextUtils.isEmpty(cdesc)) { event.getText().add(cdesc); } } @Override public boolean dispatchHoverEvent(MotionEvent event) { // Don't allow children to hover; we want this to be treated as a single component. return onHoverEvent(event); } @Override protected void onFinishInflate() { mUpView = findViewById(R.id.abs__up); mIconView = (ImageView) findViewById(R.id.abs__home); } public int getLeftOffset() { return mUpView.getVisibility() == GONE ? mUpWidth : 0; } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { measureChildWithMargins(mUpView, widthMeasureSpec, 0, heightMeasureSpec, 0); final LayoutParams upLp = (LayoutParams) mUpView.getLayoutParams(); mUpWidth = upLp.leftMargin + mUpView.getMeasuredWidth() + upLp.rightMargin; int width = mUpView.getVisibility() == GONE ? 0 : mUpWidth; int height = upLp.topMargin + mUpView.getMeasuredHeight() + upLp.bottomMargin; measureChildWithMargins(mIconView, widthMeasureSpec, width, heightMeasureSpec, 0); final LayoutParams iconLp = (LayoutParams) mIconView.getLayoutParams(); width += iconLp.leftMargin + mIconView.getMeasuredWidth() + iconLp.rightMargin; height = Math.max(height, iconLp.topMargin + mIconView.getMeasuredHeight() + iconLp.bottomMargin); final int widthMode = MeasureSpec.getMode(widthMeasureSpec); final int heightMode = MeasureSpec.getMode(heightMeasureSpec); final int widthSize = MeasureSpec.getSize(widthMeasureSpec); final int heightSize = MeasureSpec.getSize(heightMeasureSpec); switch (widthMode) { case MeasureSpec.AT_MOST: width = Math.min(width, widthSize); break; case MeasureSpec.EXACTLY: width = widthSize; break; case MeasureSpec.UNSPECIFIED: default: break; } switch (heightMode) { case MeasureSpec.AT_MOST: height = Math.min(height, heightSize); break; case MeasureSpec.EXACTLY: height = heightSize; break; case MeasureSpec.UNSPECIFIED: default: break; } setMeasuredDimension(width, height); } @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { final int vCenter = (b - t) / 2; //UNUSED int width = r - l; int upOffset = 0; if (mUpView.getVisibility() != GONE) { final LayoutParams upLp = (LayoutParams) mUpView.getLayoutParams(); final int upHeight = mUpView.getMeasuredHeight(); final int upWidth = mUpView.getMeasuredWidth(); final int upTop = vCenter - upHeight / 2; mUpView.layout(0, upTop, upWidth, upTop + upHeight); upOffset = upLp.leftMargin + upWidth + upLp.rightMargin; //UNUSED width -= upOffset; l += upOffset; } final LayoutParams iconLp = (LayoutParams) mIconView.getLayoutParams(); final int iconHeight = mIconView.getMeasuredHeight(); final int iconWidth = mIconView.getMeasuredWidth(); final int hCenter = (r - l) / 2; final int iconLeft = upOffset + Math.max(iconLp.leftMargin, hCenter - iconWidth / 2); final int iconTop = Math.max(iconLp.topMargin, vCenter - iconHeight / 2); mIconView.layout(iconLeft, iconTop, iconLeft + iconWidth, iconTop + iconHeight); } } private class ExpandedActionViewMenuPresenter implements MenuPresenter { MenuBuilder mMenu; MenuItemImpl mCurrentExpandedItem; @Override public void initForMenu(Context context, MenuBuilder menu) { // Clear the expanded action view when menus change. if (mMenu != null && mCurrentExpandedItem != null) { mMenu.collapseItemActionView(mCurrentExpandedItem); } mMenu = menu; } @Override public MenuView getMenuView(ViewGroup root) { return null; } @Override public void updateMenuView(boolean cleared) { // Make sure the expanded item we have is still there. if (mCurrentExpandedItem != null) { boolean found = false; if (mMenu != null) { final int count = mMenu.size(); for (int i = 0; i < count; i++) { final MenuItem item = mMenu.getItem(i); if (item == mCurrentExpandedItem) { found = true; break; } } } if (!found) { // The item we had expanded disappeared. Collapse. collapseItemActionView(mMenu, mCurrentExpandedItem); } } } @Override public void setCallback(Callback cb) { } @Override public boolean onSubMenuSelected(SubMenuBuilder subMenu) { return false; } @Override public void onCloseMenu(MenuBuilder menu, boolean allMenusAreClosing) { } @Override public boolean flagActionItems() { return false; } @Override public boolean expandItemActionView(MenuBuilder menu, MenuItemImpl item) { mExpandedActionView = item.getActionView(); mExpandedHomeLayout.setIcon(mIcon.getConstantState().newDrawable(/* TODO getResources() */)); mCurrentExpandedItem = item; if (mExpandedActionView.getParent() != ActionBarView.this) { addView(mExpandedActionView); } if (mExpandedHomeLayout.getParent() != ActionBarView.this) { addView(mExpandedHomeLayout); } mHomeLayout.setVisibility(GONE); if (mTitleLayout != null) mTitleLayout.setVisibility(GONE); if (mTabScrollView != null) mTabScrollView.setVisibility(GONE); if (mSpinner != null) mSpinner.setVisibility(GONE); if (mCustomNavView != null) mCustomNavView.setVisibility(GONE); requestLayout(); item.setActionViewExpanded(true); if (mExpandedActionView instanceof CollapsibleActionView) { ((CollapsibleActionView) mExpandedActionView).onActionViewExpanded(); } return true; } @Override public boolean collapseItemActionView(MenuBuilder menu, MenuItemImpl item) { // Do this before detaching the actionview from the hierarchy, in case // it needs to dismiss the soft keyboard, etc. if (mExpandedActionView instanceof CollapsibleActionView) { ((CollapsibleActionView) mExpandedActionView).onActionViewCollapsed(); } removeView(mExpandedActionView); removeView(mExpandedHomeLayout); mExpandedActionView = null; if ((mDisplayOptions & ActionBar.DISPLAY_SHOW_HOME) != 0) { mHomeLayout.setVisibility(VISIBLE); } if ((mDisplayOptions & ActionBar.DISPLAY_SHOW_TITLE) != 0) { if (mTitleLayout == null) { initTitle(); } else { mTitleLayout.setVisibility(VISIBLE); } } if (mTabScrollView != null && mNavigationMode == ActionBar.NAVIGATION_MODE_TABS) { mTabScrollView.setVisibility(VISIBLE); } if (mSpinner != null && mNavigationMode == ActionBar.NAVIGATION_MODE_LIST) { mSpinner.setVisibility(VISIBLE); } if (mCustomNavView != null && (mDisplayOptions & ActionBar.DISPLAY_SHOW_CUSTOM) != 0) { mCustomNavView.setVisibility(VISIBLE); } mExpandedHomeLayout.setIcon(null); mCurrentExpandedItem = null; requestLayout(); item.setActionViewExpanded(false); return true; } @Override public int getId() { return 0; } @Override public Parcelable onSaveInstanceState() { return null; } @Override public void onRestoreInstanceState(Parcelable state) { } } }
Java
/* * Copyright (C) 2010 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.internal.widget; import android.content.Context; import android.content.res.TypedArray; import android.graphics.drawable.Drawable; import android.text.TextUtils; import android.util.AttributeSet; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.accessibility.AccessibilityEvent; import android.view.animation.DecelerateInterpolator; import android.widget.LinearLayout; import android.widget.TextView; import com.actionbarsherlock.R; import com.actionbarsherlock.internal.nineoldandroids.animation.Animator; import com.actionbarsherlock.internal.nineoldandroids.animation.Animator.AnimatorListener; import com.actionbarsherlock.internal.nineoldandroids.animation.AnimatorSet; import com.actionbarsherlock.internal.nineoldandroids.animation.ObjectAnimator; import com.actionbarsherlock.internal.nineoldandroids.view.animation.AnimatorProxy; import com.actionbarsherlock.internal.nineoldandroids.widget.NineLinearLayout; import com.actionbarsherlock.internal.view.menu.ActionMenuPresenter; import com.actionbarsherlock.internal.view.menu.ActionMenuView; import com.actionbarsherlock.internal.view.menu.MenuBuilder; import com.actionbarsherlock.view.ActionMode; /** * @hide */ public class ActionBarContextView extends AbsActionBarView implements AnimatorListener { //UNUSED private static final String TAG = "ActionBarContextView"; private CharSequence mTitle; private CharSequence mSubtitle; private NineLinearLayout mClose; private View mCustomView; private LinearLayout mTitleLayout; private TextView mTitleView; private TextView mSubtitleView; private int mTitleStyleRes; private int mSubtitleStyleRes; private Drawable mSplitBackground; private Animator mCurrentAnimation; private boolean mAnimateInOnLayout; private int mAnimationMode; private static final int ANIMATE_IDLE = 0; private static final int ANIMATE_IN = 1; private static final int ANIMATE_OUT = 2; public ActionBarContextView(Context context) { this(context, null); } public ActionBarContextView(Context context, AttributeSet attrs) { this(context, attrs, R.attr.actionModeStyle); } public ActionBarContextView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.SherlockActionMode, defStyle, 0); setBackgroundDrawable(a.getDrawable( R.styleable.SherlockActionMode_background)); mTitleStyleRes = a.getResourceId( R.styleable.SherlockActionMode_titleTextStyle, 0); mSubtitleStyleRes = a.getResourceId( R.styleable.SherlockActionMode_subtitleTextStyle, 0); mContentHeight = a.getLayoutDimension( R.styleable.SherlockActionMode_height, 0); mSplitBackground = a.getDrawable( R.styleable.SherlockActionMode_backgroundSplit); a.recycle(); } @Override public void onDetachedFromWindow() { super.onDetachedFromWindow(); if (mActionMenuPresenter != null) { mActionMenuPresenter.hideOverflowMenu(); mActionMenuPresenter.hideSubMenus(); } } @Override public void setSplitActionBar(boolean split) { if (mSplitActionBar != split) { if (mActionMenuPresenter != null) { // Mode is already active; move everything over and adjust the menu itself. final LayoutParams layoutParams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT); if (!split) { mMenuView = (ActionMenuView) mActionMenuPresenter.getMenuView(this); mMenuView.setBackgroundDrawable(null); final ViewGroup oldParent = (ViewGroup) mMenuView.getParent(); if (oldParent != null) oldParent.removeView(mMenuView); addView(mMenuView, layoutParams); } else { // Allow full screen width in split mode. mActionMenuPresenter.setWidthLimit( getContext().getResources().getDisplayMetrics().widthPixels, true); // No limit to the item count; use whatever will fit. mActionMenuPresenter.setItemLimit(Integer.MAX_VALUE); // Span the whole width layoutParams.width = LayoutParams.MATCH_PARENT; layoutParams.height = mContentHeight; mMenuView = (ActionMenuView) mActionMenuPresenter.getMenuView(this); mMenuView.setBackgroundDrawable(mSplitBackground); final ViewGroup oldParent = (ViewGroup) mMenuView.getParent(); if (oldParent != null) oldParent.removeView(mMenuView); mSplitView.addView(mMenuView, layoutParams); } } super.setSplitActionBar(split); } } public void setContentHeight(int height) { mContentHeight = height; } public void setCustomView(View view) { if (mCustomView != null) { removeView(mCustomView); } mCustomView = view; if (mTitleLayout != null) { removeView(mTitleLayout); mTitleLayout = null; } if (view != null) { addView(view); } requestLayout(); } public void setTitle(CharSequence title) { mTitle = title; initTitle(); } public void setSubtitle(CharSequence subtitle) { mSubtitle = subtitle; initTitle(); } public CharSequence getTitle() { return mTitle; } public CharSequence getSubtitle() { return mSubtitle; } private void initTitle() { if (mTitleLayout == null) { LayoutInflater inflater = LayoutInflater.from(getContext()); inflater.inflate(R.layout.abs__action_bar_title_item, this); mTitleLayout = (LinearLayout) getChildAt(getChildCount() - 1); mTitleView = (TextView) mTitleLayout.findViewById(R.id.abs__action_bar_title); mSubtitleView = (TextView) mTitleLayout.findViewById(R.id.abs__action_bar_subtitle); if (mTitleStyleRes != 0) { mTitleView.setTextAppearance(mContext, mTitleStyleRes); } if (mSubtitleStyleRes != 0) { mSubtitleView.setTextAppearance(mContext, mSubtitleStyleRes); } } mTitleView.setText(mTitle); mSubtitleView.setText(mSubtitle); final boolean hasTitle = !TextUtils.isEmpty(mTitle); final boolean hasSubtitle = !TextUtils.isEmpty(mSubtitle); mSubtitleView.setVisibility(hasSubtitle ? VISIBLE : GONE); mTitleLayout.setVisibility(hasTitle || hasSubtitle ? VISIBLE : GONE); if (mTitleLayout.getParent() == null) { addView(mTitleLayout); } } public void initForMode(final ActionMode mode) { if (mClose == null) { LayoutInflater inflater = LayoutInflater.from(mContext); mClose = (NineLinearLayout)inflater.inflate(R.layout.abs__action_mode_close_item, this, false); addView(mClose); } else if (mClose.getParent() == null) { addView(mClose); } View closeButton = mClose.findViewById(R.id.abs__action_mode_close_button); closeButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { mode.finish(); } }); final MenuBuilder menu = (MenuBuilder) mode.getMenu(); if (mActionMenuPresenter != null) { mActionMenuPresenter.dismissPopupMenus(); } mActionMenuPresenter = new ActionMenuPresenter(mContext); mActionMenuPresenter.setReserveOverflow(true); final LayoutParams layoutParams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT); if (!mSplitActionBar) { menu.addMenuPresenter(mActionMenuPresenter); mMenuView = (ActionMenuView) mActionMenuPresenter.getMenuView(this); mMenuView.setBackgroundDrawable(null); addView(mMenuView, layoutParams); } else { // Allow full screen width in split mode. mActionMenuPresenter.setWidthLimit( getContext().getResources().getDisplayMetrics().widthPixels, true); // No limit to the item count; use whatever will fit. mActionMenuPresenter.setItemLimit(Integer.MAX_VALUE); // Span the whole width layoutParams.width = LayoutParams.MATCH_PARENT; layoutParams.height = mContentHeight; menu.addMenuPresenter(mActionMenuPresenter); mMenuView = (ActionMenuView) mActionMenuPresenter.getMenuView(this); mMenuView.setBackgroundDrawable(mSplitBackground); mSplitView.addView(mMenuView, layoutParams); } mAnimateInOnLayout = true; } public void closeMode() { if (mAnimationMode == ANIMATE_OUT) { // Called again during close; just finish what we were doing. return; } if (mClose == null) { killMode(); return; } finishAnimation(); mAnimationMode = ANIMATE_OUT; mCurrentAnimation = makeOutAnimation(); mCurrentAnimation.start(); } private void finishAnimation() { final Animator a = mCurrentAnimation; if (a != null) { mCurrentAnimation = null; a.end(); } } public void killMode() { finishAnimation(); removeAllViews(); if (mSplitView != null) { mSplitView.removeView(mMenuView); } mCustomView = null; mMenuView = null; mAnimateInOnLayout = false; } @Override public boolean showOverflowMenu() { if (mActionMenuPresenter != null) { return mActionMenuPresenter.showOverflowMenu(); } return false; } @Override public boolean hideOverflowMenu() { if (mActionMenuPresenter != null) { return mActionMenuPresenter.hideOverflowMenu(); } return false; } @Override public boolean isOverflowMenuShowing() { if (mActionMenuPresenter != null) { return mActionMenuPresenter.isOverflowMenuShowing(); } return false; } @Override protected ViewGroup.LayoutParams generateDefaultLayoutParams() { // Used by custom views if they don't supply layout params. Everything else // added to an ActionBarContextView should have them already. return new MarginLayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT); } @Override public ViewGroup.LayoutParams generateLayoutParams(AttributeSet attrs) { return new MarginLayoutParams(getContext(), attrs); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { final int widthMode = MeasureSpec.getMode(widthMeasureSpec); if (widthMode != MeasureSpec.EXACTLY) { throw new IllegalStateException(getClass().getSimpleName() + " can only be used " + "with android:layout_width=\"match_parent\" (or fill_parent)"); } final int heightMode = MeasureSpec.getMode(heightMeasureSpec); if (heightMode == MeasureSpec.UNSPECIFIED) { throw new IllegalStateException(getClass().getSimpleName() + " can only be used " + "with android:layout_height=\"wrap_content\""); } final int contentWidth = MeasureSpec.getSize(widthMeasureSpec); int maxHeight = mContentHeight > 0 ? mContentHeight : MeasureSpec.getSize(heightMeasureSpec); final int verticalPadding = getPaddingTop() + getPaddingBottom(); int availableWidth = contentWidth - getPaddingLeft() - getPaddingRight(); final int height = maxHeight - verticalPadding; final int childSpecHeight = MeasureSpec.makeMeasureSpec(height, MeasureSpec.AT_MOST); if (mClose != null) { availableWidth = measureChildView(mClose, availableWidth, childSpecHeight, 0); MarginLayoutParams lp = (MarginLayoutParams) mClose.getLayoutParams(); availableWidth -= lp.leftMargin + lp.rightMargin; } if (mMenuView != null && mMenuView.getParent() == this) { availableWidth = measureChildView(mMenuView, availableWidth, childSpecHeight, 0); } if (mTitleLayout != null && mCustomView == null) { availableWidth = measureChildView(mTitleLayout, availableWidth, childSpecHeight, 0); } if (mCustomView != null) { ViewGroup.LayoutParams lp = mCustomView.getLayoutParams(); final int customWidthMode = lp.width != LayoutParams.WRAP_CONTENT ? MeasureSpec.EXACTLY : MeasureSpec.AT_MOST; final int customWidth = lp.width >= 0 ? Math.min(lp.width, availableWidth) : availableWidth; final int customHeightMode = lp.height != LayoutParams.WRAP_CONTENT ? MeasureSpec.EXACTLY : MeasureSpec.AT_MOST; final int customHeight = lp.height >= 0 ? Math.min(lp.height, height) : height; mCustomView.measure(MeasureSpec.makeMeasureSpec(customWidth, customWidthMode), MeasureSpec.makeMeasureSpec(customHeight, customHeightMode)); } if (mContentHeight <= 0) { int measuredHeight = 0; final int count = getChildCount(); for (int i = 0; i < count; i++) { View v = getChildAt(i); int paddedViewHeight = v.getMeasuredHeight() + verticalPadding; if (paddedViewHeight > measuredHeight) { measuredHeight = paddedViewHeight; } } setMeasuredDimension(contentWidth, measuredHeight); } else { setMeasuredDimension(contentWidth, maxHeight); } } private Animator makeInAnimation() { mClose.setTranslationX(-mClose.getWidth() - ((MarginLayoutParams) mClose.getLayoutParams()).leftMargin); ObjectAnimator buttonAnimator = ObjectAnimator.ofFloat(mClose, "translationX", 0); buttonAnimator.setDuration(200); buttonAnimator.addListener(this); buttonAnimator.setInterpolator(new DecelerateInterpolator()); AnimatorSet set = new AnimatorSet(); AnimatorSet.Builder b = set.play(buttonAnimator); if (mMenuView != null) { final int count = mMenuView.getChildCount(); if (count > 0) { for (int i = count - 1, j = 0; i >= 0; i--, j++) { AnimatorProxy child = AnimatorProxy.wrap(mMenuView.getChildAt(i)); child.setScaleY(0); ObjectAnimator a = ObjectAnimator.ofFloat(child, "scaleY", 0, 1); a.setDuration(100); a.setStartDelay(j * 70); b.with(a); } } } return set; } private Animator makeOutAnimation() { ObjectAnimator buttonAnimator = ObjectAnimator.ofFloat(mClose, "translationX", -mClose.getWidth() - ((MarginLayoutParams) mClose.getLayoutParams()).leftMargin); buttonAnimator.setDuration(200); buttonAnimator.addListener(this); buttonAnimator.setInterpolator(new DecelerateInterpolator()); AnimatorSet set = new AnimatorSet(); AnimatorSet.Builder b = set.play(buttonAnimator); if (mMenuView != null) { final int count = mMenuView.getChildCount(); if (count > 0) { for (int i = 0; i < 0; i++) { AnimatorProxy child = AnimatorProxy.wrap(mMenuView.getChildAt(i)); child.setScaleY(0); ObjectAnimator a = ObjectAnimator.ofFloat(child, "scaleY", 0); a.setDuration(100); a.setStartDelay(i * 70); b.with(a); } } } return set; } @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { int x = getPaddingLeft(); final int y = getPaddingTop(); final int contentHeight = b - t - getPaddingTop() - getPaddingBottom(); if (mClose != null && mClose.getVisibility() != GONE) { MarginLayoutParams lp = (MarginLayoutParams) mClose.getLayoutParams(); x += lp.leftMargin; x += positionChild(mClose, x, y, contentHeight); x += lp.rightMargin; if (mAnimateInOnLayout) { mAnimationMode = ANIMATE_IN; mCurrentAnimation = makeInAnimation(); mCurrentAnimation.start(); mAnimateInOnLayout = false; } } if (mTitleLayout != null && mCustomView == null) { x += positionChild(mTitleLayout, x, y, contentHeight); } if (mCustomView != null) { x += positionChild(mCustomView, x, y, contentHeight); } x = r - l - getPaddingRight(); if (mMenuView != null) { x -= positionChildInverse(mMenuView, x, y, contentHeight); } } @Override public void onAnimationStart(Animator animation) { } @Override public void onAnimationEnd(Animator animation) { if (mAnimationMode == ANIMATE_OUT) { killMode(); } mAnimationMode = ANIMATE_IDLE; } @Override public void onAnimationCancel(Animator animation) { } @Override public void onAnimationRepeat(Animator animation) { } @Override public boolean shouldDelayChildPressedState() { return false; } @Override public void onInitializeAccessibilityEvent(AccessibilityEvent event) { if (event.getEventType() == AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED) { // Action mode started //TODO event.setSource(this); event.setClassName(getClass().getName()); event.setPackageName(getContext().getPackageName()); event.setContentDescription(mTitle); } else { //TODO super.onInitializeAccessibilityEvent(event); } } }
Java
package com.actionbarsherlock.internal.widget; import static android.view.View.MeasureSpec.EXACTLY; import android.content.Context; import android.content.res.TypedArray; import android.util.AttributeSet; import android.util.DisplayMetrics; import android.util.TypedValue; import android.widget.LinearLayout; import com.actionbarsherlock.R; public class FakeDialogPhoneWindow extends LinearLayout { final TypedValue mMinWidthMajor = new TypedValue(); final TypedValue mMinWidthMinor = new TypedValue(); public FakeDialogPhoneWindow(Context context, AttributeSet attrs) { super(context, attrs); TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.SherlockTheme); a.getValue(R.styleable.SherlockTheme_windowMinWidthMajor, mMinWidthMajor); a.getValue(R.styleable.SherlockTheme_windowMinWidthMinor, mMinWidthMinor); a.recycle(); } /* Stolen from PhoneWindow */ @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { final DisplayMetrics metrics = getContext().getResources().getDisplayMetrics(); final boolean isPortrait = metrics.widthPixels < metrics.heightPixels; super.onMeasure(widthMeasureSpec, heightMeasureSpec); int width = getMeasuredWidth(); boolean measure = false; widthMeasureSpec = MeasureSpec.makeMeasureSpec(width, EXACTLY); final TypedValue tv = isPortrait ? mMinWidthMinor : mMinWidthMajor; if (tv.type != TypedValue.TYPE_NULL) { final int min; if (tv.type == TypedValue.TYPE_DIMENSION) { min = (int)tv.getDimension(metrics); } else if (tv.type == TypedValue.TYPE_FRACTION) { min = (int)tv.getFraction(metrics.widthPixels, metrics.widthPixels); } else { min = 0; } if (width < min) { widthMeasureSpec = MeasureSpec.makeMeasureSpec(min, EXACTLY); measure = true; } } // TODO: Support height? if (measure) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); } } }
Java
package com.actionbarsherlock.internal.widget; import android.view.View; final class IcsView { //No instances private IcsView() {} /** * Return only the state bits of {@link #getMeasuredWidthAndState()} * and {@link #getMeasuredHeightAndState()}, combined into one integer. * The width component is in the regular bits {@link #MEASURED_STATE_MASK} * and the height component is at the shifted bits * {@link #MEASURED_HEIGHT_STATE_SHIFT}>>{@link #MEASURED_STATE_MASK}. */ public static int getMeasuredStateInt(View child) { return (child.getMeasuredWidth()&View.MEASURED_STATE_MASK) | ((child.getMeasuredHeight()>>View.MEASURED_HEIGHT_STATE_SHIFT) & (View.MEASURED_STATE_MASK>>View.MEASURED_HEIGHT_STATE_SHIFT)); } }
Java
package com.actionbarsherlock.internal.widget; import java.util.Locale; import android.content.Context; import android.content.res.TypedArray; import android.os.Build; import android.util.AttributeSet; import android.widget.Button; public class CapitalizingButton extends Button { private static final boolean SANS_ICE_CREAM = Build.VERSION.SDK_INT < Build.VERSION_CODES.ICE_CREAM_SANDWICH; private static final boolean IS_GINGERBREAD = Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD; private static final int[] R_styleable_Button = new int[] { android.R.attr.textAllCaps }; private static final int R_styleable_Button_textAllCaps = 0; private boolean mAllCaps; public CapitalizingButton(Context context, AttributeSet attrs) { super(context, attrs); TypedArray a = context.obtainStyledAttributes(attrs, R_styleable_Button); mAllCaps = a.getBoolean(R_styleable_Button_textAllCaps, true); a.recycle(); } public void setTextCompat(CharSequence text) { if (SANS_ICE_CREAM && mAllCaps && text != null) { if (IS_GINGERBREAD) { setText(text.toString().toUpperCase(Locale.ROOT)); } else { setText(text.toString().toUpperCase()); } } else { setText(text); } } }
Java
/* * 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.internal.widget; import android.content.Context; import android.content.res.Configuration; import android.content.res.TypedArray; import android.os.Build; import android.util.AttributeSet; import android.view.View; import android.view.animation.DecelerateInterpolator; import android.view.animation.Interpolator; import com.actionbarsherlock.R; import com.actionbarsherlock.internal.nineoldandroids.animation.Animator; import com.actionbarsherlock.internal.nineoldandroids.animation.AnimatorSet; import com.actionbarsherlock.internal.nineoldandroids.animation.ObjectAnimator; import com.actionbarsherlock.internal.nineoldandroids.view.NineViewGroup; import com.actionbarsherlock.internal.view.menu.ActionMenuPresenter; import com.actionbarsherlock.internal.view.menu.ActionMenuView; import static com.actionbarsherlock.internal.ResourcesCompat.getResources_getBoolean; public abstract class AbsActionBarView extends NineViewGroup { protected ActionMenuView mMenuView; protected ActionMenuPresenter mActionMenuPresenter; protected ActionBarContainer mSplitView; protected boolean mSplitActionBar; protected boolean mSplitWhenNarrow; protected int mContentHeight; final Context mContext; protected Animator mVisibilityAnim; protected final VisibilityAnimListener mVisAnimListener = new VisibilityAnimListener(); private static final /*Time*/Interpolator sAlphaInterpolator = new DecelerateInterpolator(); private static final int FADE_DURATION = 200; public AbsActionBarView(Context context) { super(context); mContext = context; } public AbsActionBarView(Context context, AttributeSet attrs) { super(context, attrs); mContext = context; } public AbsActionBarView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); mContext = context; } /* * Must be public so we can dispatch pre-2.2 via ActionBarImpl. */ @Override public void onConfigurationChanged(Configuration newConfig) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO) { super.onConfigurationChanged(newConfig); } else if (mMenuView != null) { mMenuView.onConfigurationChanged(newConfig); } // Action bar can change size on configuration changes. // Reread the desired height from the theme-specified style. TypedArray a = getContext().obtainStyledAttributes(null, R.styleable.SherlockActionBar, R.attr.actionBarStyle, 0); setContentHeight(a.getLayoutDimension(R.styleable.SherlockActionBar_height, 0)); a.recycle(); if (mSplitWhenNarrow) { setSplitActionBar(getResources_getBoolean(getContext(), R.bool.abs__split_action_bar_is_narrow)); } if (mActionMenuPresenter != null) { mActionMenuPresenter.onConfigurationChanged(newConfig); } } /** * Sets whether the bar should be split right now, no questions asked. * @param split true if the bar should split */ public void setSplitActionBar(boolean split) { mSplitActionBar = split; } /** * Sets whether the bar should split if we enter a narrow screen configuration. * @param splitWhenNarrow true if the bar should check to split after a config change */ public void setSplitWhenNarrow(boolean splitWhenNarrow) { mSplitWhenNarrow = splitWhenNarrow; } public void setContentHeight(int height) { mContentHeight = height; requestLayout(); } public int getContentHeight() { return mContentHeight; } public void setSplitView(ActionBarContainer splitView) { mSplitView = splitView; } /** * @return Current visibility or if animating, the visibility being animated to. */ public int getAnimatedVisibility() { if (mVisibilityAnim != null) { return mVisAnimListener.mFinalVisibility; } return getVisibility(); } public void animateToVisibility(int visibility) { if (mVisibilityAnim != null) { mVisibilityAnim.cancel(); } if (visibility == VISIBLE) { if (getVisibility() != VISIBLE) { setAlpha(0); if (mSplitView != null && mMenuView != null) { mMenuView.setAlpha(0); } } ObjectAnimator anim = ObjectAnimator.ofFloat(this, "alpha", 1); anim.setDuration(FADE_DURATION); anim.setInterpolator(sAlphaInterpolator); if (mSplitView != null && mMenuView != null) { AnimatorSet set = new AnimatorSet(); ObjectAnimator splitAnim = ObjectAnimator.ofFloat(mMenuView, "alpha", 1); splitAnim.setDuration(FADE_DURATION); set.addListener(mVisAnimListener.withFinalVisibility(visibility)); set.play(anim).with(splitAnim); set.start(); } else { anim.addListener(mVisAnimListener.withFinalVisibility(visibility)); anim.start(); } } else { ObjectAnimator anim = ObjectAnimator.ofFloat(this, "alpha", 0); anim.setDuration(FADE_DURATION); anim.setInterpolator(sAlphaInterpolator); if (mSplitView != null && mMenuView != null) { AnimatorSet set = new AnimatorSet(); ObjectAnimator splitAnim = ObjectAnimator.ofFloat(mMenuView, "alpha", 0); splitAnim.setDuration(FADE_DURATION); set.addListener(mVisAnimListener.withFinalVisibility(visibility)); set.play(anim).with(splitAnim); set.start(); } else { anim.addListener(mVisAnimListener.withFinalVisibility(visibility)); anim.start(); } } } @Override public void setVisibility(int visibility) { if (mVisibilityAnim != null) { mVisibilityAnim.end(); } super.setVisibility(visibility); } public boolean showOverflowMenu() { if (mActionMenuPresenter != null) { return mActionMenuPresenter.showOverflowMenu(); } return false; } public void postShowOverflowMenu() { post(new Runnable() { public void run() { showOverflowMenu(); } }); } public boolean hideOverflowMenu() { if (mActionMenuPresenter != null) { return mActionMenuPresenter.hideOverflowMenu(); } return false; } public boolean isOverflowMenuShowing() { if (mActionMenuPresenter != null) { return mActionMenuPresenter.isOverflowMenuShowing(); } return false; } public boolean isOverflowReserved() { return mActionMenuPresenter != null && mActionMenuPresenter.isOverflowReserved(); } public void dismissPopupMenus() { if (mActionMenuPresenter != null) { mActionMenuPresenter.dismissPopupMenus(); } } protected int measureChildView(View child, int availableWidth, int childSpecHeight, int spacing) { child.measure(MeasureSpec.makeMeasureSpec(availableWidth, MeasureSpec.AT_MOST), childSpecHeight); availableWidth -= child.getMeasuredWidth(); availableWidth -= spacing; return Math.max(0, availableWidth); } protected int positionChild(View child, int x, int y, int contentHeight) { int childWidth = child.getMeasuredWidth(); int childHeight = child.getMeasuredHeight(); int childTop = y + (contentHeight - childHeight) / 2; child.layout(x, childTop, x + childWidth, childTop + childHeight); return childWidth; } protected int positionChildInverse(View child, int x, int y, int contentHeight) { int childWidth = child.getMeasuredWidth(); int childHeight = child.getMeasuredHeight(); int childTop = y + (contentHeight - childHeight) / 2; child.layout(x - childWidth, childTop, x, childTop + childHeight); return childWidth; } protected class VisibilityAnimListener implements Animator.AnimatorListener { private boolean mCanceled = false; int mFinalVisibility; public VisibilityAnimListener withFinalVisibility(int visibility) { mFinalVisibility = visibility; return this; } @Override public void onAnimationStart(Animator animation) { setVisibility(VISIBLE); mVisibilityAnim = animation; mCanceled = false; } @Override public void onAnimationEnd(Animator animation) { if (mCanceled) return; mVisibilityAnim = null; setVisibility(mFinalVisibility); if (mSplitView != null && mMenuView != null) { mMenuView.setVisibility(mFinalVisibility); } } @Override public void onAnimationCancel(Animator animation) { mCanceled = true; } @Override public void onAnimationRepeat(Animator animation) { } } }
Java
/* * Copyright (C) 2006 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.actionbarsherlock.internal.widget; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Bitmap; import android.graphics.BitmapShader; import android.graphics.Canvas; import android.graphics.Rect; import android.graphics.Shader; import android.graphics.drawable.Animatable; import android.graphics.drawable.AnimationDrawable; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.ClipDrawable; import android.graphics.drawable.Drawable; import android.graphics.drawable.LayerDrawable; import android.graphics.drawable.ShapeDrawable; import android.graphics.drawable.shapes.RoundRectShape; import android.graphics.drawable.shapes.Shape; import android.os.Build; import android.os.Parcel; import android.os.Parcelable; import android.os.SystemClock; import android.util.AttributeSet; import android.view.Gravity; import android.view.View; import android.view.ViewDebug; import android.view.accessibility.AccessibilityEvent; import android.view.accessibility.AccessibilityManager; import android.view.animation.AlphaAnimation; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.view.animation.Interpolator; import android.view.animation.LinearInterpolator; import android.view.animation.Transformation; import android.widget.RemoteViews.RemoteView; /** * <p> * Visual indicator of progress in some operation. Displays a bar to the user * representing how far the operation has progressed; the application can * change the amount of progress (modifying the length of the bar) as it moves * forward. There is also a secondary progress displayable on a progress bar * which is useful for displaying intermediate progress, such as the buffer * level during a streaming playback progress bar. * </p> * * <p> * A progress bar can also be made indeterminate. In indeterminate mode, the * progress bar shows a cyclic animation without an indication of progress. This mode is used by * applications when the length of the task is unknown. The indeterminate progress bar can be either * a spinning wheel or a horizontal bar. * </p> * * <p>The following code example shows how a progress bar can be used from * a worker thread to update the user interface to notify the user of progress: * </p> * * <pre> * public class MyActivity extends Activity { * private static final int PROGRESS = 0x1; * * private ProgressBar mProgress; * private int mProgressStatus = 0; * * private Handler mHandler = new Handler(); * * protected void onCreate(Bundle icicle) { * super.onCreate(icicle); * * setContentView(R.layout.progressbar_activity); * * mProgress = (ProgressBar) findViewById(R.id.progress_bar); * * // Start lengthy operation in a background thread * new Thread(new Runnable() { * public void run() { * while (mProgressStatus &lt; 100) { * mProgressStatus = doWork(); * * // Update the progress bar * mHandler.post(new Runnable() { * public void run() { * mProgress.setProgress(mProgressStatus); * } * }); * } * } * }).start(); * } * }</pre> * * <p>To add a progress bar to a layout file, you can use the {@code &lt;ProgressBar&gt;} element. * By default, the progress bar is a spinning wheel (an indeterminate indicator). To change to a * horizontal progress bar, apply the {@link android.R.style#Widget_ProgressBar_Horizontal * Widget.ProgressBar.Horizontal} style, like so:</p> * * <pre> * &lt;ProgressBar * style="@android:style/Widget.ProgressBar.Horizontal" * ... /&gt;</pre> * * <p>If you will use the progress bar to show real progress, you must use the horizontal bar. You * can then increment the progress with {@link #incrementProgressBy incrementProgressBy()} or * {@link #setProgress setProgress()}. By default, the progress bar is full when it reaches 100. If * necessary, you can adjust the maximum value (the value for a full bar) using the {@link * android.R.styleable#ProgressBar_max android:max} attribute. Other attributes available are listed * below.</p> * * <p>Another common style to apply to the progress bar is {@link * android.R.style#Widget_ProgressBar_Small Widget.ProgressBar.Small}, which shows a smaller * version of the spinning wheel&mdash;useful when waiting for content to load. * For example, you can insert this kind of progress bar into your default layout for * a view that will be populated by some content fetched from the Internet&mdash;the spinning wheel * appears immediately and when your application receives the content, it replaces the progress bar * with the loaded content. For example:</p> * * <pre> * &lt;LinearLayout * android:orientation="horizontal" * ... &gt; * &lt;ProgressBar * android:layout_width="wrap_content" * android:layout_height="wrap_content" * style="@android:style/Widget.ProgressBar.Small" * android:layout_marginRight="5dp" /&gt; * &lt;TextView * android:layout_width="wrap_content" * android:layout_height="wrap_content" * android:text="@string/loading" /&gt; * &lt;/LinearLayout&gt;</pre> * * <p>Other progress bar styles provided by the system include:</p> * <ul> * <li>{@link android.R.style#Widget_ProgressBar_Horizontal Widget.ProgressBar.Horizontal}</li> * <li>{@link android.R.style#Widget_ProgressBar_Small Widget.ProgressBar.Small}</li> * <li>{@link android.R.style#Widget_ProgressBar_Large Widget.ProgressBar.Large}</li> * <li>{@link android.R.style#Widget_ProgressBar_Inverse Widget.ProgressBar.Inverse}</li> * <li>{@link android.R.style#Widget_ProgressBar_Small_Inverse * Widget.ProgressBar.Small.Inverse}</li> * <li>{@link android.R.style#Widget_ProgressBar_Large_Inverse * Widget.ProgressBar.Large.Inverse}</li> * </ul> * <p>The "inverse" styles provide an inverse color scheme for the spinner, which may be necessary * if your application uses a light colored theme (a white background).</p> * * <p><strong>XML attributes</b></strong> * <p> * See {@link android.R.styleable#ProgressBar ProgressBar Attributes}, * {@link android.R.styleable#View View Attributes} * </p> * * @attr ref android.R.styleable#ProgressBar_animationResolution * @attr ref android.R.styleable#ProgressBar_indeterminate * @attr ref android.R.styleable#ProgressBar_indeterminateBehavior * @attr ref android.R.styleable#ProgressBar_indeterminateDrawable * @attr ref android.R.styleable#ProgressBar_indeterminateDuration * @attr ref android.R.styleable#ProgressBar_indeterminateOnly * @attr ref android.R.styleable#ProgressBar_interpolator * @attr ref android.R.styleable#ProgressBar_max * @attr ref android.R.styleable#ProgressBar_maxHeight * @attr ref android.R.styleable#ProgressBar_maxWidth * @attr ref android.R.styleable#ProgressBar_minHeight * @attr ref android.R.styleable#ProgressBar_minWidth * @attr ref android.R.styleable#ProgressBar_progress * @attr ref android.R.styleable#ProgressBar_progressDrawable * @attr ref android.R.styleable#ProgressBar_secondaryProgress */ @RemoteView public class IcsProgressBar extends View { private static final boolean IS_HONEYCOMB = Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB; private static final int MAX_LEVEL = 10000; private static final int ANIMATION_RESOLUTION = 200; private static final int TIMEOUT_SEND_ACCESSIBILITY_EVENT = 200; private static final int[] ProgressBar = new int[] { android.R.attr.maxWidth, android.R.attr.maxHeight, android.R.attr.max, android.R.attr.progress, android.R.attr.secondaryProgress, android.R.attr.indeterminate, android.R.attr.indeterminateOnly, android.R.attr.indeterminateDrawable, android.R.attr.progressDrawable, android.R.attr.indeterminateDuration, android.R.attr.indeterminateBehavior, android.R.attr.minWidth, android.R.attr.minHeight, android.R.attr.interpolator, android.R.attr.animationResolution, }; private static final int ProgressBar_maxWidth = 0; private static final int ProgressBar_maxHeight = 1; private static final int ProgressBar_max = 2; private static final int ProgressBar_progress = 3; private static final int ProgressBar_secondaryProgress = 4; private static final int ProgressBar_indeterminate = 5; private static final int ProgressBar_indeterminateOnly = 6; private static final int ProgressBar_indeterminateDrawable = 7; private static final int ProgressBar_progressDrawable = 8; private static final int ProgressBar_indeterminateDuration = 9; private static final int ProgressBar_indeterminateBehavior = 10; private static final int ProgressBar_minWidth = 11; private static final int ProgressBar_minHeight = 12; private static final int ProgressBar_interpolator = 13; private static final int ProgressBar_animationResolution = 14; int mMinWidth; int mMaxWidth; int mMinHeight; int mMaxHeight; private int mProgress; private int mSecondaryProgress; private int mMax; private int mBehavior; private int mDuration; private boolean mIndeterminate; private boolean mOnlyIndeterminate; private Transformation mTransformation; private AlphaAnimation mAnimation; private Drawable mIndeterminateDrawable; private int mIndeterminateRealLeft; private int mIndeterminateRealTop; private Drawable mProgressDrawable; private Drawable mCurrentDrawable; Bitmap mSampleTile; private boolean mNoInvalidate; private Interpolator mInterpolator; private RefreshProgressRunnable mRefreshProgressRunnable; private long mUiThreadId; private boolean mShouldStartAnimationDrawable; private long mLastDrawTime; private boolean mInDrawing; private int mAnimationResolution; private AccessibilityManager mAccessibilityManager; private AccessibilityEventSender mAccessibilityEventSender; /** * Create a new progress bar with range 0...100 and initial progress of 0. * @param context the application environment */ public IcsProgressBar(Context context) { this(context, null); } public IcsProgressBar(Context context, AttributeSet attrs) { this(context, attrs, android.R.attr.progressBarStyle); } public IcsProgressBar(Context context, AttributeSet attrs, int defStyle) { this(context, attrs, defStyle, 0); } /** * @hide */ public IcsProgressBar(Context context, AttributeSet attrs, int defStyle, int styleRes) { super(context, attrs, defStyle); mUiThreadId = Thread.currentThread().getId(); initProgressBar(); TypedArray a = context.obtainStyledAttributes(attrs, /*R.styleable.*/ProgressBar, defStyle, styleRes); mNoInvalidate = true; Drawable drawable = a.getDrawable(/*R.styleable.*/ProgressBar_progressDrawable); if (drawable != null) { drawable = tileify(drawable, false); // Calling this method can set mMaxHeight, make sure the corresponding // XML attribute for mMaxHeight is read after calling this method setProgressDrawable(drawable); } mDuration = a.getInt(/*R.styleable.*/ProgressBar_indeterminateDuration, mDuration); mMinWidth = a.getDimensionPixelSize(/*R.styleable.*/ProgressBar_minWidth, mMinWidth); mMaxWidth = a.getDimensionPixelSize(/*R.styleable.*/ProgressBar_maxWidth, mMaxWidth); mMinHeight = a.getDimensionPixelSize(/*R.styleable.*/ProgressBar_minHeight, mMinHeight); mMaxHeight = a.getDimensionPixelSize(/*R.styleable.*/ProgressBar_maxHeight, mMaxHeight); mBehavior = a.getInt(/*R.styleable.*/ProgressBar_indeterminateBehavior, mBehavior); final int resID = a.getResourceId( /*com.android.internal.R.styleable.*/ProgressBar_interpolator, android.R.anim.linear_interpolator); // default to linear interpolator if (resID > 0) { setInterpolator(context, resID); } setMax(a.getInt(/*R.styleable.*/ProgressBar_max, mMax)); setProgress(a.getInt(/*R.styleable.*/ProgressBar_progress, mProgress)); setSecondaryProgress( a.getInt(/*R.styleable.*/ProgressBar_secondaryProgress, mSecondaryProgress)); drawable = a.getDrawable(/*R.styleable.*/ProgressBar_indeterminateDrawable); if (drawable != null) { drawable = tileifyIndeterminate(drawable); setIndeterminateDrawable(drawable); } mOnlyIndeterminate = a.getBoolean( /*R.styleable.*/ProgressBar_indeterminateOnly, mOnlyIndeterminate); mNoInvalidate = false; setIndeterminate(mOnlyIndeterminate || a.getBoolean( /*R.styleable.*/ProgressBar_indeterminate, mIndeterminate)); mAnimationResolution = a.getInteger(/*R.styleable.*/ProgressBar_animationResolution, ANIMATION_RESOLUTION); a.recycle(); mAccessibilityManager = (AccessibilityManager)context.getSystemService(Context.ACCESSIBILITY_SERVICE); } /** * Converts a drawable to a tiled version of itself. It will recursively * traverse layer and state list drawables. */ private Drawable tileify(Drawable drawable, boolean clip) { if (drawable instanceof LayerDrawable) { LayerDrawable background = (LayerDrawable) drawable; final int N = background.getNumberOfLayers(); Drawable[] outDrawables = new Drawable[N]; for (int i = 0; i < N; i++) { int id = background.getId(i); outDrawables[i] = tileify(background.getDrawable(i), (id == android.R.id.progress || id == android.R.id.secondaryProgress)); } LayerDrawable newBg = new LayerDrawable(outDrawables); for (int i = 0; i < N; i++) { newBg.setId(i, background.getId(i)); } return newBg; }/* else if (drawable instanceof StateListDrawable) { StateListDrawable in = (StateListDrawable) drawable; StateListDrawable out = new StateListDrawable(); int numStates = in.getStateCount(); for (int i = 0; i < numStates; i++) { out.addState(in.getStateSet(i), tileify(in.getStateDrawable(i), clip)); } return out; }*/ else if (drawable instanceof BitmapDrawable) { final Bitmap tileBitmap = ((BitmapDrawable) drawable).getBitmap(); if (mSampleTile == null) { mSampleTile = tileBitmap; } final ShapeDrawable shapeDrawable = new ShapeDrawable(getDrawableShape()); final BitmapShader bitmapShader = new BitmapShader(tileBitmap, Shader.TileMode.REPEAT, Shader.TileMode.CLAMP); shapeDrawable.getPaint().setShader(bitmapShader); return (clip) ? new ClipDrawable(shapeDrawable, Gravity.LEFT, ClipDrawable.HORIZONTAL) : shapeDrawable; } return drawable; } Shape getDrawableShape() { final float[] roundedCorners = new float[] { 5, 5, 5, 5, 5, 5, 5, 5 }; return new RoundRectShape(roundedCorners, null, null); } /** * Convert a AnimationDrawable for use as a barberpole animation. * Each frame of the animation is wrapped in a ClipDrawable and * given a tiling BitmapShader. */ private Drawable tileifyIndeterminate(Drawable drawable) { if (drawable instanceof AnimationDrawable) { AnimationDrawable background = (AnimationDrawable) drawable; final int N = background.getNumberOfFrames(); AnimationDrawable newBg = new AnimationDrawable(); newBg.setOneShot(background.isOneShot()); for (int i = 0; i < N; i++) { Drawable frame = tileify(background.getFrame(i), true); frame.setLevel(10000); newBg.addFrame(frame, background.getDuration(i)); } newBg.setLevel(10000); drawable = newBg; } return drawable; } /** * <p> * Initialize the progress bar's default values: * </p> * <ul> * <li>progress = 0</li> * <li>max = 100</li> * <li>animation duration = 4000 ms</li> * <li>indeterminate = false</li> * <li>behavior = repeat</li> * </ul> */ private void initProgressBar() { mMax = 100; mProgress = 0; mSecondaryProgress = 0; mIndeterminate = false; mOnlyIndeterminate = false; mDuration = 4000; mBehavior = AlphaAnimation.RESTART; mMinWidth = 24; mMaxWidth = 48; mMinHeight = 24; mMaxHeight = 48; } /** * <p>Indicate whether this progress bar is in indeterminate mode.</p> * * @return true if the progress bar is in indeterminate mode */ @ViewDebug.ExportedProperty(category = "progress") public synchronized boolean isIndeterminate() { return mIndeterminate; } /** * <p>Change the indeterminate mode for this progress bar. In indeterminate * mode, the progress is ignored and the progress bar shows an infinite * animation instead.</p> * * If this progress bar's style only supports indeterminate mode (such as the circular * progress bars), then this will be ignored. * * @param indeterminate true to enable the indeterminate mode */ public synchronized void setIndeterminate(boolean indeterminate) { if ((!mOnlyIndeterminate || !mIndeterminate) && indeterminate != mIndeterminate) { mIndeterminate = indeterminate; if (indeterminate) { // swap between indeterminate and regular backgrounds mCurrentDrawable = mIndeterminateDrawable; startAnimation(); } else { mCurrentDrawable = mProgressDrawable; stopAnimation(); } } } /** * <p>Get the drawable used to draw the progress bar in * indeterminate mode.</p> * * @return a {@link android.graphics.drawable.Drawable} instance * * @see #setIndeterminateDrawable(android.graphics.drawable.Drawable) * @see #setIndeterminate(boolean) */ public Drawable getIndeterminateDrawable() { return mIndeterminateDrawable; } /** * <p>Define the drawable used to draw the progress bar in * indeterminate mode.</p> * * @param d the new drawable * * @see #getIndeterminateDrawable() * @see #setIndeterminate(boolean) */ public void setIndeterminateDrawable(Drawable d) { if (d != null) { d.setCallback(this); } mIndeterminateDrawable = d; if (mIndeterminate) { mCurrentDrawable = d; postInvalidate(); } } /** * <p>Get the drawable used to draw the progress bar in * progress mode.</p> * * @return a {@link android.graphics.drawable.Drawable} instance * * @see #setProgressDrawable(android.graphics.drawable.Drawable) * @see #setIndeterminate(boolean) */ public Drawable getProgressDrawable() { return mProgressDrawable; } /** * <p>Define the drawable used to draw the progress bar in * progress mode.</p> * * @param d the new drawable * * @see #getProgressDrawable() * @see #setIndeterminate(boolean) */ public void setProgressDrawable(Drawable d) { boolean needUpdate; if (mProgressDrawable != null && d != mProgressDrawable) { mProgressDrawable.setCallback(null); needUpdate = true; } else { needUpdate = false; } if (d != null) { d.setCallback(this); // Make sure the ProgressBar is always tall enough int drawableHeight = d.getMinimumHeight(); if (mMaxHeight < drawableHeight) { mMaxHeight = drawableHeight; requestLayout(); } } mProgressDrawable = d; if (!mIndeterminate) { mCurrentDrawable = d; postInvalidate(); } if (needUpdate) { updateDrawableBounds(getWidth(), getHeight()); updateDrawableState(); doRefreshProgress(android.R.id.progress, mProgress, false, false); doRefreshProgress(android.R.id.secondaryProgress, mSecondaryProgress, false, false); } } /** * @return The drawable currently used to draw the progress bar */ Drawable getCurrentDrawable() { return mCurrentDrawable; } @Override protected boolean verifyDrawable(Drawable who) { return who == mProgressDrawable || who == mIndeterminateDrawable || super.verifyDrawable(who); } @Override public void jumpDrawablesToCurrentState() { super.jumpDrawablesToCurrentState(); if (mProgressDrawable != null) mProgressDrawable.jumpToCurrentState(); if (mIndeterminateDrawable != null) mIndeterminateDrawable.jumpToCurrentState(); } @Override public void postInvalidate() { if (!mNoInvalidate) { super.postInvalidate(); } } private class RefreshProgressRunnable implements Runnable { private int mId; private int mProgress; private boolean mFromUser; RefreshProgressRunnable(int id, int progress, boolean fromUser) { mId = id; mProgress = progress; mFromUser = fromUser; } public void run() { doRefreshProgress(mId, mProgress, mFromUser, true); // Put ourselves back in the cache when we are done mRefreshProgressRunnable = this; } public void setup(int id, int progress, boolean fromUser) { mId = id; mProgress = progress; mFromUser = fromUser; } } private synchronized void doRefreshProgress(int id, int progress, boolean fromUser, boolean callBackToApp) { float scale = mMax > 0 ? (float) progress / (float) mMax : 0; final Drawable d = mCurrentDrawable; if (d != null) { Drawable progressDrawable = null; if (d instanceof LayerDrawable) { progressDrawable = ((LayerDrawable) d).findDrawableByLayerId(id); } final int level = (int) (scale * MAX_LEVEL); (progressDrawable != null ? progressDrawable : d).setLevel(level); } else { invalidate(); } if (callBackToApp && id == android.R.id.progress) { onProgressRefresh(scale, fromUser); } } void onProgressRefresh(float scale, boolean fromUser) { if (mAccessibilityManager.isEnabled()) { scheduleAccessibilityEventSender(); } } private synchronized void refreshProgress(int id, int progress, boolean fromUser) { if (mUiThreadId == Thread.currentThread().getId()) { doRefreshProgress(id, progress, fromUser, true); } else { RefreshProgressRunnable r; if (mRefreshProgressRunnable != null) { // Use cached RefreshProgressRunnable if available r = mRefreshProgressRunnable; // Uncache it mRefreshProgressRunnable = null; r.setup(id, progress, fromUser); } else { // Make a new one r = new RefreshProgressRunnable(id, progress, fromUser); } post(r); } } /** * <p>Set the current progress to the specified value. Does not do anything * if the progress bar is in indeterminate mode.</p> * * @param progress the new progress, between 0 and {@link #getMax()} * * @see #setIndeterminate(boolean) * @see #isIndeterminate() * @see #getProgress() * @see #incrementProgressBy(int) */ public synchronized void setProgress(int progress) { setProgress(progress, false); } synchronized void setProgress(int progress, boolean fromUser) { if (mIndeterminate) { return; } if (progress < 0) { progress = 0; } if (progress > mMax) { progress = mMax; } if (progress != mProgress) { mProgress = progress; refreshProgress(android.R.id.progress, mProgress, fromUser); } } /** * <p> * Set the current secondary progress to the specified value. Does not do * anything if the progress bar is in indeterminate mode. * </p> * * @param secondaryProgress the new secondary progress, between 0 and {@link #getMax()} * @see #setIndeterminate(boolean) * @see #isIndeterminate() * @see #getSecondaryProgress() * @see #incrementSecondaryProgressBy(int) */ public synchronized void setSecondaryProgress(int secondaryProgress) { if (mIndeterminate) { return; } if (secondaryProgress < 0) { secondaryProgress = 0; } if (secondaryProgress > mMax) { secondaryProgress = mMax; } if (secondaryProgress != mSecondaryProgress) { mSecondaryProgress = secondaryProgress; refreshProgress(android.R.id.secondaryProgress, mSecondaryProgress, false); } } /** * <p>Get the progress bar's current level of progress. Return 0 when the * progress bar is in indeterminate mode.</p> * * @return the current progress, between 0 and {@link #getMax()} * * @see #setIndeterminate(boolean) * @see #isIndeterminate() * @see #setProgress(int) * @see #setMax(int) * @see #getMax() */ @ViewDebug.ExportedProperty(category = "progress") public synchronized int getProgress() { return mIndeterminate ? 0 : mProgress; } /** * <p>Get the progress bar's current level of secondary progress. Return 0 when the * progress bar is in indeterminate mode.</p> * * @return the current secondary progress, between 0 and {@link #getMax()} * * @see #setIndeterminate(boolean) * @see #isIndeterminate() * @see #setSecondaryProgress(int) * @see #setMax(int) * @see #getMax() */ @ViewDebug.ExportedProperty(category = "progress") public synchronized int getSecondaryProgress() { return mIndeterminate ? 0 : mSecondaryProgress; } /** * <p>Return the upper limit of this progress bar's range.</p> * * @return a positive integer * * @see #setMax(int) * @see #getProgress() * @see #getSecondaryProgress() */ @ViewDebug.ExportedProperty(category = "progress") public synchronized int getMax() { return mMax; } /** * <p>Set the range of the progress bar to 0...<tt>max</tt>.</p> * * @param max the upper range of this progress bar * * @see #getMax() * @see #setProgress(int) * @see #setSecondaryProgress(int) */ public synchronized void setMax(int max) { if (max < 0) { max = 0; } if (max != mMax) { mMax = max; postInvalidate(); if (mProgress > max) { mProgress = max; } refreshProgress(android.R.id.progress, mProgress, false); } } /** * <p>Increase the progress bar's progress by the specified amount.</p> * * @param diff the amount by which the progress must be increased * * @see #setProgress(int) */ public synchronized final void incrementProgressBy(int diff) { setProgress(mProgress + diff); } /** * <p>Increase the progress bar's secondary progress by the specified amount.</p> * * @param diff the amount by which the secondary progress must be increased * * @see #setSecondaryProgress(int) */ public synchronized final void incrementSecondaryProgressBy(int diff) { setSecondaryProgress(mSecondaryProgress + diff); } /** * <p>Start the indeterminate progress animation.</p> */ void startAnimation() { if (getVisibility() != VISIBLE) { return; } if (mIndeterminateDrawable instanceof Animatable) { mShouldStartAnimationDrawable = true; mAnimation = null; } else { if (mInterpolator == null) { mInterpolator = new LinearInterpolator(); } mTransformation = new Transformation(); mAnimation = new AlphaAnimation(0.0f, 1.0f); mAnimation.setRepeatMode(mBehavior); mAnimation.setRepeatCount(Animation.INFINITE); mAnimation.setDuration(mDuration); mAnimation.setInterpolator(mInterpolator); mAnimation.setStartTime(Animation.START_ON_FIRST_FRAME); } postInvalidate(); } /** * <p>Stop the indeterminate progress animation.</p> */ void stopAnimation() { mAnimation = null; mTransformation = null; if (mIndeterminateDrawable instanceof Animatable) { ((Animatable) mIndeterminateDrawable).stop(); mShouldStartAnimationDrawable = false; } postInvalidate(); } /** * Sets the acceleration curve for the indeterminate animation. * The interpolator is loaded as a resource from the specified context. * * @param context The application environment * @param resID The resource identifier of the interpolator to load */ public void setInterpolator(Context context, int resID) { setInterpolator(AnimationUtils.loadInterpolator(context, resID)); } /** * Sets the acceleration curve for the indeterminate animation. * Defaults to a linear interpolation. * * @param interpolator The interpolator which defines the acceleration curve */ public void setInterpolator(Interpolator interpolator) { mInterpolator = interpolator; } /** * Gets the acceleration curve type for the indeterminate animation. * * @return the {@link Interpolator} associated to this animation */ public Interpolator getInterpolator() { return mInterpolator; } @Override public void setVisibility(int v) { if (getVisibility() != v) { super.setVisibility(v); if (mIndeterminate) { // let's be nice with the UI thread if (v == GONE || v == INVISIBLE) { stopAnimation(); } else { startAnimation(); } } } } @Override protected void onVisibilityChanged(View changedView, int visibility) { super.onVisibilityChanged(changedView, visibility); if (mIndeterminate) { // let's be nice with the UI thread if (visibility == GONE || visibility == INVISIBLE) { stopAnimation(); } else { startAnimation(); } } } @Override public void invalidateDrawable(Drawable dr) { if (!mInDrawing) { if (verifyDrawable(dr)) { final Rect dirty = dr.getBounds(); final int scrollX = getScrollX() + getPaddingLeft(); final int scrollY = getScrollY() + getPaddingTop(); invalidate(dirty.left + scrollX, dirty.top + scrollY, dirty.right + scrollX, dirty.bottom + scrollY); } else { super.invalidateDrawable(dr); } } } /** * @hide * @Override public int getResolvedLayoutDirection(Drawable who) { return (who == mProgressDrawable || who == mIndeterminateDrawable) ? getResolvedLayoutDirection() : super.getResolvedLayoutDirection(who); } */ @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { updateDrawableBounds(w, h); } private void updateDrawableBounds(int w, int h) { // onDraw will translate the canvas so we draw starting at 0,0 int right = w - getPaddingRight() - getPaddingLeft(); int bottom = h - getPaddingBottom() - getPaddingTop(); int top = 0; int left = 0; if (mIndeterminateDrawable != null) { // Aspect ratio logic does not apply to AnimationDrawables if (mOnlyIndeterminate && !(mIndeterminateDrawable instanceof AnimationDrawable)) { // Maintain aspect ratio. Certain kinds of animated drawables // get very confused otherwise. final int intrinsicWidth = mIndeterminateDrawable.getIntrinsicWidth(); final int intrinsicHeight = mIndeterminateDrawable.getIntrinsicHeight(); final float intrinsicAspect = (float) intrinsicWidth / intrinsicHeight; final float boundAspect = (float) w / h; if (intrinsicAspect != boundAspect) { if (boundAspect > intrinsicAspect) { // New width is larger. Make it smaller to match height. final int width = (int) (h * intrinsicAspect); left = (w - width) / 2; right = left + width; } else { // New height is larger. Make it smaller to match width. final int height = (int) (w * (1 / intrinsicAspect)); top = (h - height) / 2; bottom = top + height; } } } mIndeterminateDrawable.setBounds(0, 0, right - left, bottom - top); mIndeterminateRealLeft = left; mIndeterminateRealTop = top; } if (mProgressDrawable != null) { mProgressDrawable.setBounds(0, 0, right, bottom); } } @Override protected synchronized void onDraw(Canvas canvas) { super.onDraw(canvas); Drawable d = mCurrentDrawable; if (d != null) { // Translate canvas so a indeterminate circular progress bar with padding // rotates properly in its animation canvas.save(); canvas.translate(getPaddingLeft() + mIndeterminateRealLeft, getPaddingTop() + mIndeterminateRealTop); long time = getDrawingTime(); if (mAnimation != null) { mAnimation.getTransformation(time, mTransformation); float scale = mTransformation.getAlpha(); try { mInDrawing = true; d.setLevel((int) (scale * MAX_LEVEL)); } finally { mInDrawing = false; } if (SystemClock.uptimeMillis() - mLastDrawTime >= mAnimationResolution) { mLastDrawTime = SystemClock.uptimeMillis(); postInvalidateDelayed(mAnimationResolution); } } d.draw(canvas); canvas.restore(); if (mShouldStartAnimationDrawable && d instanceof Animatable) { ((Animatable) d).start(); mShouldStartAnimationDrawable = false; } } } @Override protected synchronized void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { Drawable d = mCurrentDrawable; int dw = 0; int dh = 0; if (d != null) { dw = Math.max(mMinWidth, Math.min(mMaxWidth, d.getIntrinsicWidth())); dh = Math.max(mMinHeight, Math.min(mMaxHeight, d.getIntrinsicHeight())); } updateDrawableState(); dw += getPaddingLeft() + getPaddingRight(); dh += getPaddingTop() + getPaddingBottom(); if (IS_HONEYCOMB) { setMeasuredDimension(View.resolveSizeAndState(dw, widthMeasureSpec, 0), View.resolveSizeAndState(dh, heightMeasureSpec, 0)); } else { setMeasuredDimension(View.resolveSize(dw, widthMeasureSpec), View.resolveSize(dh, heightMeasureSpec)); } } @Override protected void drawableStateChanged() { super.drawableStateChanged(); updateDrawableState(); } private void updateDrawableState() { int[] state = getDrawableState(); if (mProgressDrawable != null && mProgressDrawable.isStateful()) { mProgressDrawable.setState(state); } if (mIndeterminateDrawable != null && mIndeterminateDrawable.isStateful()) { mIndeterminateDrawable.setState(state); } } static class SavedState extends BaseSavedState { int progress; int secondaryProgress; /** * Constructor called from {@link IcsProgressBar#onSaveInstanceState()} */ SavedState(Parcelable superState) { super(superState); } /** * Constructor called from {@link #CREATOR} */ private SavedState(Parcel in) { super(in); progress = in.readInt(); secondaryProgress = in.readInt(); } @Override public void writeToParcel(Parcel out, int flags) { super.writeToParcel(out, flags); out.writeInt(progress); out.writeInt(secondaryProgress); } public static final Parcelable.Creator<SavedState> CREATOR = new Parcelable.Creator<SavedState>() { public SavedState createFromParcel(Parcel in) { return new SavedState(in); } public SavedState[] newArray(int size) { return new SavedState[size]; } }; } @Override public Parcelable onSaveInstanceState() { // Force our ancestor class to save its state Parcelable superState = super.onSaveInstanceState(); SavedState ss = new SavedState(superState); ss.progress = mProgress; ss.secondaryProgress = mSecondaryProgress; return ss; } @Override public void onRestoreInstanceState(Parcelable state) { SavedState ss = (SavedState) state; super.onRestoreInstanceState(ss.getSuperState()); setProgress(ss.progress); setSecondaryProgress(ss.secondaryProgress); } @Override protected void onAttachedToWindow() { super.onAttachedToWindow(); if (mIndeterminate) { startAnimation(); } } @Override protected void onDetachedFromWindow() { if (mIndeterminate) { stopAnimation(); } if(mRefreshProgressRunnable != null) { removeCallbacks(mRefreshProgressRunnable); } if (mAccessibilityEventSender != null) { removeCallbacks(mAccessibilityEventSender); } // This should come after stopAnimation(), otherwise an invalidate message remains in the // queue, which can prevent the entire view hierarchy from being GC'ed during a rotation super.onDetachedFromWindow(); } @Override public void onInitializeAccessibilityEvent(AccessibilityEvent event) { super.onInitializeAccessibilityEvent(event); event.setItemCount(mMax); event.setCurrentItemIndex(mProgress); } /** * Schedule a command for sending an accessibility event. * </br> * Note: A command is used to ensure that accessibility events * are sent at most one in a given time frame to save * system resources while the progress changes quickly. */ private void scheduleAccessibilityEventSender() { if (mAccessibilityEventSender == null) { mAccessibilityEventSender = new AccessibilityEventSender(); } else { removeCallbacks(mAccessibilityEventSender); } postDelayed(mAccessibilityEventSender, TIMEOUT_SEND_ACCESSIBILITY_EVENT); } /** * Command for sending an accessibility event. */ private class AccessibilityEventSender implements Runnable { public void run() { sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SELECTED); } } }
Java
package com.actionbarsherlock.internal.view; import android.view.View; public interface View_OnAttachStateChangeListener { void onViewAttachedToWindow(View v); void onViewDetachedFromWindow(View v); }
Java
/* * Copyright (C) 2010 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.internal.view.menu; import java.util.ArrayList; import android.content.Context; import android.content.res.Resources; import android.database.DataSetObserver; import android.os.Parcelable; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.View; import android.view.View.MeasureSpec; import android.view.ViewGroup; import android.view.ViewTreeObserver; import android.widget.AdapterView; import android.widget.BaseAdapter; import android.widget.FrameLayout; import android.widget.ListAdapter; import android.widget.PopupWindow; import com.actionbarsherlock.R; import com.actionbarsherlock.internal.view.View_HasStateListenerSupport; import com.actionbarsherlock.internal.view.View_OnAttachStateChangeListener; import com.actionbarsherlock.internal.widget.IcsListPopupWindow; import com.actionbarsherlock.view.MenuItem; /** * Presents a menu as a small, simple popup anchored to another view. * @hide */ public class MenuPopupHelper implements AdapterView.OnItemClickListener, View.OnKeyListener, ViewTreeObserver.OnGlobalLayoutListener, PopupWindow.OnDismissListener, View_OnAttachStateChangeListener, MenuPresenter { //UNUSED private static final String TAG = "MenuPopupHelper"; static final int ITEM_LAYOUT = R.layout.abs__popup_menu_item_layout; private Context mContext; private LayoutInflater mInflater; private IcsListPopupWindow mPopup; private MenuBuilder mMenu; private int mPopupMaxWidth; private View mAnchorView; private boolean mOverflowOnly; private ViewTreeObserver mTreeObserver; private MenuAdapter mAdapter; private Callback mPresenterCallback; boolean mForceShowIcon; private ViewGroup mMeasureParent; public MenuPopupHelper(Context context, MenuBuilder menu) { this(context, menu, null, false); } public MenuPopupHelper(Context context, MenuBuilder menu, View anchorView) { this(context, menu, anchorView, false); } public MenuPopupHelper(Context context, MenuBuilder menu, View anchorView, boolean overflowOnly) { mContext = context; mInflater = LayoutInflater.from(context); mMenu = menu; mOverflowOnly = overflowOnly; final Resources res = context.getResources(); mPopupMaxWidth = Math.max(res.getDisplayMetrics().widthPixels / 2, res.getDimensionPixelSize(R.dimen.abs__config_prefDialogWidth)); mAnchorView = anchorView; menu.addMenuPresenter(this); } public void setAnchorView(View anchor) { mAnchorView = anchor; } public void setForceShowIcon(boolean forceShow) { mForceShowIcon = forceShow; } public void show() { if (!tryShow()) { throw new IllegalStateException("MenuPopupHelper cannot be used without an anchor"); } } public boolean tryShow() { mPopup = new IcsListPopupWindow(mContext, null, R.attr.popupMenuStyle); mPopup.setOnDismissListener(this); mPopup.setOnItemClickListener(this); mAdapter = new MenuAdapter(mMenu); mPopup.setAdapter(mAdapter); mPopup.setModal(true); View anchor = mAnchorView; if (anchor != null) { final boolean addGlobalListener = mTreeObserver == null; mTreeObserver = anchor.getViewTreeObserver(); // Refresh to latest if (addGlobalListener) mTreeObserver.addOnGlobalLayoutListener(this); ((View_HasStateListenerSupport)anchor).addOnAttachStateChangeListener(this); mPopup.setAnchorView(anchor); } else { return false; } mPopup.setContentWidth(Math.min(measureContentWidth(mAdapter), mPopupMaxWidth)); mPopup.setInputMethodMode(PopupWindow.INPUT_METHOD_NOT_NEEDED); mPopup.show(); mPopup.getListView().setOnKeyListener(this); return true; } public void dismiss() { if (isShowing()) { mPopup.dismiss(); } } public void onDismiss() { mPopup = null; mMenu.close(); if (mTreeObserver != null) { if (!mTreeObserver.isAlive()) mTreeObserver = mAnchorView.getViewTreeObserver(); mTreeObserver.removeGlobalOnLayoutListener(this); mTreeObserver = null; } ((View_HasStateListenerSupport)mAnchorView).removeOnAttachStateChangeListener(this); } public boolean isShowing() { return mPopup != null && mPopup.isShowing(); } @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { MenuAdapter adapter = mAdapter; adapter.mAdapterMenu.performItemAction(adapter.getItem(position), 0); } public boolean onKey(View v, int keyCode, KeyEvent event) { if (event.getAction() == KeyEvent.ACTION_UP && keyCode == KeyEvent.KEYCODE_MENU) { dismiss(); return true; } return false; } private int measureContentWidth(ListAdapter adapter) { // Menus don't tend to be long, so this is more sane than it looks. 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); final int count = adapter.getCount(); for (int i = 0; i < count; i++) { final int positionType = adapter.getItemViewType(i); if (positionType != itemType) { itemType = positionType; itemView = null; } if (mMeasureParent == null) { mMeasureParent = new FrameLayout(mContext); } itemView = adapter.getView(i, itemView, mMeasureParent); itemView.measure(widthMeasureSpec, heightMeasureSpec); width = Math.max(width, itemView.getMeasuredWidth()); } return width; } @Override public void onGlobalLayout() { if (isShowing()) { final View anchor = mAnchorView; if (anchor == null || !anchor.isShown()) { dismiss(); } else if (isShowing()) { // Recompute window size and position mPopup.show(); } } } @Override public void onViewAttachedToWindow(View v) { } @Override public void onViewDetachedFromWindow(View v) { if (mTreeObserver != null) { if (!mTreeObserver.isAlive()) mTreeObserver = v.getViewTreeObserver(); mTreeObserver.removeGlobalOnLayoutListener(this); } ((View_HasStateListenerSupport)v).removeOnAttachStateChangeListener(this); } @Override public void initForMenu(Context context, MenuBuilder menu) { // Don't need to do anything; we added as a presenter in the constructor. } @Override public MenuView getMenuView(ViewGroup root) { throw new UnsupportedOperationException("MenuPopupHelpers manage their own views"); } @Override public void updateMenuView(boolean cleared) { if (mAdapter != null) mAdapter.notifyDataSetChanged(); } @Override public void setCallback(Callback cb) { mPresenterCallback = cb; } @Override public boolean onSubMenuSelected(SubMenuBuilder subMenu) { if (subMenu.hasVisibleItems()) { MenuPopupHelper subPopup = new MenuPopupHelper(mContext, subMenu, mAnchorView, false); subPopup.setCallback(mPresenterCallback); boolean preserveIconSpacing = false; final int count = subMenu.size(); for (int i = 0; i < count; i++) { MenuItem childItem = subMenu.getItem(i); if (childItem.isVisible() && childItem.getIcon() != null) { preserveIconSpacing = true; break; } } subPopup.setForceShowIcon(preserveIconSpacing); if (subPopup.tryShow()) { if (mPresenterCallback != null) { mPresenterCallback.onOpenSubMenu(subMenu); } return true; } } return false; } @Override public void onCloseMenu(MenuBuilder menu, boolean allMenusAreClosing) { // Only care about the (sub)menu we're presenting. if (menu != mMenu) return; dismiss(); if (mPresenterCallback != null) { mPresenterCallback.onCloseMenu(menu, allMenusAreClosing); } } @Override public boolean flagActionItems() { return false; } public boolean expandItemActionView(MenuBuilder menu, MenuItemImpl item) { return false; } public boolean collapseItemActionView(MenuBuilder menu, MenuItemImpl item) { return false; } @Override public int getId() { return 0; } @Override public Parcelable onSaveInstanceState() { return null; } @Override public void onRestoreInstanceState(Parcelable state) { } private class MenuAdapter extends BaseAdapter { private MenuBuilder mAdapterMenu; private int mExpandedIndex = -1; public MenuAdapter(MenuBuilder menu) { mAdapterMenu = menu; registerDataSetObserver(new ExpandedIndexObserver()); findExpandedIndex(); } public int getCount() { ArrayList<MenuItemImpl> items = mOverflowOnly ? mAdapterMenu.getNonActionItems() : mAdapterMenu.getVisibleItems(); if (mExpandedIndex < 0) { return items.size(); } return items.size() - 1; } public MenuItemImpl getItem(int position) { ArrayList<MenuItemImpl> items = mOverflowOnly ? mAdapterMenu.getNonActionItems() : mAdapterMenu.getVisibleItems(); if (mExpandedIndex >= 0 && position >= mExpandedIndex) { position++; } return items.get(position); } public long getItemId(int position) { // Since a menu item's ID is optional, we'll use the position as an // ID for the item in the AdapterView return position; } public View getView(int position, View convertView, ViewGroup parent) { if (convertView == null) { convertView = mInflater.inflate(ITEM_LAYOUT, parent, false); } MenuView.ItemView itemView = (MenuView.ItemView) convertView; if (mForceShowIcon) { ((ListMenuItemView) convertView).setForceShowIcon(true); } itemView.initialize(getItem(position), 0); return convertView; } void findExpandedIndex() { final MenuItemImpl expandedItem = mMenu.getExpandedItem(); if (expandedItem != null) { final ArrayList<MenuItemImpl> items = mMenu.getNonActionItems(); final int count = items.size(); for (int i = 0; i < count; i++) { final MenuItemImpl item = items.get(i); if (item == expandedItem) { mExpandedIndex = i; return; } } } mExpandedIndex = -1; } } private class ExpandedIndexObserver extends DataSetObserver { @Override public void onChanged() { mAdapter.findExpandedIndex(); } } }
Java
/* * Copyright (C) 2006 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.actionbarsherlock.internal.view.menu; import com.actionbarsherlock.R; import android.content.Context; import android.content.res.TypedArray; import android.graphics.drawable.Drawable; import android.util.AttributeSet; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RadioButton; import android.widget.TextView; /** * The item view for each item in the ListView-based MenuViews. */ public class ListMenuItemView extends LinearLayout implements MenuView.ItemView { private MenuItemImpl mItemData; private ImageView mIconView; private RadioButton mRadioButton; private TextView mTitleView; private CheckBox mCheckBox; private TextView mShortcutView; private Drawable mBackground; private int mTextAppearance; private Context mTextAppearanceContext; private boolean mPreserveIconSpacing; //UNUSED private int mMenuType; private LayoutInflater mInflater; private boolean mForceShowIcon; final Context mContext; public ListMenuItemView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs); mContext = context; TypedArray a = context.obtainStyledAttributes( attrs, R.styleable.SherlockMenuView, defStyle, 0); mBackground = a.getDrawable(R.styleable.SherlockMenuView_itemBackground); mTextAppearance = a.getResourceId(R.styleable. SherlockMenuView_itemTextAppearance, -1); mPreserveIconSpacing = a.getBoolean( R.styleable.SherlockMenuView_preserveIconSpacing, false); mTextAppearanceContext = context; a.recycle(); } public ListMenuItemView(Context context, AttributeSet attrs) { this(context, attrs, 0); } @Override protected void onFinishInflate() { super.onFinishInflate(); setBackgroundDrawable(mBackground); mTitleView = (TextView) findViewById(R.id.abs__title); if (mTextAppearance != -1) { mTitleView.setTextAppearance(mTextAppearanceContext, mTextAppearance); } mShortcutView = (TextView) findViewById(R.id.abs__shortcut); } public void initialize(MenuItemImpl itemData, int menuType) { mItemData = itemData; //UNUSED mMenuType = menuType; setVisibility(itemData.isVisible() ? View.VISIBLE : View.GONE); setTitle(itemData.getTitleForItemView(this)); setCheckable(itemData.isCheckable()); setShortcut(itemData.shouldShowShortcut(), itemData.getShortcut()); setIcon(itemData.getIcon()); setEnabled(itemData.isEnabled()); } public void setForceShowIcon(boolean forceShow) { mPreserveIconSpacing = mForceShowIcon = forceShow; } public void setTitle(CharSequence title) { if (title != null) { mTitleView.setText(title); if (mTitleView.getVisibility() != VISIBLE) mTitleView.setVisibility(VISIBLE); } else { if (mTitleView.getVisibility() != GONE) mTitleView.setVisibility(GONE); } } public MenuItemImpl getItemData() { return mItemData; } public void setCheckable(boolean checkable) { if (!checkable && mRadioButton == null && mCheckBox == null) { return; } if (mRadioButton == null) { insertRadioButton(); } if (mCheckBox == null) { insertCheckBox(); } // Depending on whether its exclusive check or not, the checkbox or // radio button will be the one in use (and the other will be otherCompoundButton) final CompoundButton compoundButton; final CompoundButton otherCompoundButton; if (mItemData.isExclusiveCheckable()) { compoundButton = mRadioButton; otherCompoundButton = mCheckBox; } else { compoundButton = mCheckBox; otherCompoundButton = mRadioButton; } if (checkable) { compoundButton.setChecked(mItemData.isChecked()); final int newVisibility = checkable ? VISIBLE : GONE; if (compoundButton.getVisibility() != newVisibility) { compoundButton.setVisibility(newVisibility); } // Make sure the other compound button isn't visible if (otherCompoundButton.getVisibility() != GONE) { otherCompoundButton.setVisibility(GONE); } } else { mCheckBox.setVisibility(GONE); mRadioButton.setVisibility(GONE); } } public void setChecked(boolean checked) { CompoundButton compoundButton; if (mItemData.isExclusiveCheckable()) { if (mRadioButton == null) { insertRadioButton(); } compoundButton = mRadioButton; } else { if (mCheckBox == null) { insertCheckBox(); } compoundButton = mCheckBox; } compoundButton.setChecked(checked); } public void setShortcut(boolean showShortcut, char shortcutKey) { final int newVisibility = (showShortcut && mItemData.shouldShowShortcut()) ? VISIBLE : GONE; if (newVisibility == VISIBLE) { mShortcutView.setText(mItemData.getShortcutLabel()); } if (mShortcutView.getVisibility() != newVisibility) { mShortcutView.setVisibility(newVisibility); } } public void setIcon(Drawable icon) { final boolean showIcon = mItemData.shouldShowIcon() || mForceShowIcon; if (!showIcon && !mPreserveIconSpacing) { return; } if (mIconView == null && icon == null && !mPreserveIconSpacing) { return; } if (mIconView == null) { insertIconView(); } if (icon != null || mPreserveIconSpacing) { mIconView.setImageDrawable(showIcon ? icon : null); if (mIconView.getVisibility() != VISIBLE) { mIconView.setVisibility(VISIBLE); } } else { mIconView.setVisibility(GONE); } } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { if (mIconView != null && mPreserveIconSpacing) { // Enforce minimum icon spacing ViewGroup.LayoutParams lp = getLayoutParams(); LayoutParams iconLp = (LayoutParams) mIconView.getLayoutParams(); if (lp.height > 0 && iconLp.width <= 0) { iconLp.width = lp.height; } } super.onMeasure(widthMeasureSpec, heightMeasureSpec); } private void insertIconView() { LayoutInflater inflater = getInflater(); mIconView = (ImageView) inflater.inflate(R.layout.abs__list_menu_item_icon, this, false); addView(mIconView, 0); } private void insertRadioButton() { LayoutInflater inflater = getInflater(); mRadioButton = (RadioButton) inflater.inflate(R.layout.abs__list_menu_item_radio, this, false); addView(mRadioButton); } private void insertCheckBox() { LayoutInflater inflater = getInflater(); mCheckBox = (CheckBox) inflater.inflate(R.layout.abs__list_menu_item_checkbox, this, false); addView(mCheckBox); } public boolean prefersCondensedTitle() { return false; } public boolean showsIcon() { return mForceShowIcon; } private LayoutInflater getInflater() { if (mInflater == null) { mInflater = LayoutInflater.from(mContext); } return mInflater; } }
Java
/* * Copyright (C) 2006 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.actionbarsherlock.internal.view.menu; import android.graphics.drawable.Drawable; /** * Minimal interface for a menu view. {@link #initialize(MenuBuilder)} must be called for the * menu to be functional. * * @hide */ public interface MenuView { /** * Initializes the menu to the given menu. This should be called after the * view is inflated. * * @param menu The menu that this MenuView should display. */ public void initialize(MenuBuilder menu); /** * Returns the default animations to be used for this menu when entering/exiting. * @return A resource ID for the default animations to be used for this menu. */ public int getWindowAnimations(); /** * Minimal interface for a menu item view. {@link #initialize(MenuItemImpl, int)} must be called * for the item to be functional. */ public interface ItemView { /** * Initializes with the provided MenuItemData. This should be called after the view is * inflated. * @param itemData The item that this ItemView should display. * @param menuType The type of this menu, one of * {@link MenuBuilder#TYPE_ICON}, {@link MenuBuilder#TYPE_EXPANDED}, * {@link MenuBuilder#TYPE_DIALOG}). */ public void initialize(MenuItemImpl itemData, int menuType); /** * Gets the item data that this view is displaying. * @return the item data, or null if there is not one */ public MenuItemImpl getItemData(); /** * Sets the title of the item view. * @param title The title to set. */ public void setTitle(CharSequence title); /** * Sets the enabled state of the item view. * @param enabled Whether the item view should be enabled. */ public void setEnabled(boolean enabled); /** * Displays the checkbox for the item view. This does not ensure the item view will be * checked, for that use {@link #setChecked}. * @param checkable Whether to display the checkbox or to hide it */ public void setCheckable(boolean checkable); /** * Checks the checkbox for the item view. If the checkbox is hidden, it will NOT be * made visible, call {@link #setCheckable(boolean)} for that. * @param checked Whether the checkbox should be checked */ public void setChecked(boolean checked); /** * Sets the shortcut for the item. * @param showShortcut Whether a shortcut should be shown(if false, the value of * shortcutKey should be ignored). * @param shortcutKey The shortcut key that should be shown on the ItemView. */ public void setShortcut(boolean showShortcut, char shortcutKey); /** * Set the icon of this item view. * @param icon The icon of this item. null to hide the icon. */ public void setIcon(Drawable icon); /** * Whether this item view prefers displaying the condensed title rather * than the normal title. If a condensed title is not available, the * normal title will be used. * * @return Whether this item view prefers displaying the condensed * title. */ public boolean prefersCondensedTitle(); /** * Whether this item view shows an icon. * * @return Whether this item view shows an icon. */ public boolean showsIcon(); } }
Java
/* * Copyright (C) 2010 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.internal.view.menu; import android.content.Context; import android.content.Intent; import android.graphics.drawable.Drawable; import android.view.ContextMenu.ContextMenuInfo; import android.view.View; import com.actionbarsherlock.view.ActionProvider; import com.actionbarsherlock.view.MenuItem; import com.actionbarsherlock.view.SubMenu; /** * @hide */ public class ActionMenuItem implements MenuItem { private final int mId; private final int mGroup; //UNUSED private final int mCategoryOrder; private final int mOrdering; private CharSequence mTitle; private CharSequence mTitleCondensed; private Intent mIntent; private char mShortcutNumericChar; private char mShortcutAlphabeticChar; private Drawable mIconDrawable; //UNUSED private int mIconResId = NO_ICON; private Context mContext; private MenuItem.OnMenuItemClickListener mClickListener; //UNUSED private static final int NO_ICON = 0; private int mFlags = ENABLED; private static final int CHECKABLE = 0x00000001; private static final int CHECKED = 0x00000002; private static final int EXCLUSIVE = 0x00000004; private static final int HIDDEN = 0x00000008; private static final int ENABLED = 0x00000010; public ActionMenuItem(Context context, int group, int id, int categoryOrder, int ordering, CharSequence title) { mContext = context; mId = id; mGroup = group; //UNUSED mCategoryOrder = categoryOrder; mOrdering = ordering; mTitle = title; } public char getAlphabeticShortcut() { return mShortcutAlphabeticChar; } public int getGroupId() { return mGroup; } public Drawable getIcon() { return mIconDrawable; } public Intent getIntent() { return mIntent; } public int getItemId() { return mId; } public ContextMenuInfo getMenuInfo() { return null; } public char getNumericShortcut() { return mShortcutNumericChar; } public int getOrder() { return mOrdering; } public SubMenu getSubMenu() { return null; } public CharSequence getTitle() { return mTitle; } public CharSequence getTitleCondensed() { return mTitleCondensed; } public boolean hasSubMenu() { return false; } public boolean isCheckable() { return (mFlags & CHECKABLE) != 0; } public boolean isChecked() { return (mFlags & CHECKED) != 0; } public boolean isEnabled() { return (mFlags & ENABLED) != 0; } public boolean isVisible() { return (mFlags & HIDDEN) == 0; } public MenuItem setAlphabeticShortcut(char alphaChar) { mShortcutAlphabeticChar = alphaChar; return this; } public MenuItem setCheckable(boolean checkable) { mFlags = (mFlags & ~CHECKABLE) | (checkable ? CHECKABLE : 0); return this; } public ActionMenuItem setExclusiveCheckable(boolean exclusive) { mFlags = (mFlags & ~EXCLUSIVE) | (exclusive ? EXCLUSIVE : 0); return this; } public MenuItem setChecked(boolean checked) { mFlags = (mFlags & ~CHECKED) | (checked ? CHECKED : 0); return this; } public MenuItem setEnabled(boolean enabled) { mFlags = (mFlags & ~ENABLED) | (enabled ? ENABLED : 0); return this; } public MenuItem setIcon(Drawable icon) { mIconDrawable = icon; //UNUSED mIconResId = NO_ICON; return this; } public MenuItem setIcon(int iconRes) { //UNUSED mIconResId = iconRes; mIconDrawable = mContext.getResources().getDrawable(iconRes); return this; } public MenuItem setIntent(Intent intent) { mIntent = intent; return this; } public MenuItem setNumericShortcut(char numericChar) { mShortcutNumericChar = numericChar; return this; } public MenuItem setOnMenuItemClickListener(OnMenuItemClickListener menuItemClickListener) { mClickListener = menuItemClickListener; return this; } public MenuItem setShortcut(char numericChar, char alphaChar) { mShortcutNumericChar = numericChar; mShortcutAlphabeticChar = alphaChar; return this; } public MenuItem setTitle(CharSequence title) { mTitle = title; return this; } public MenuItem setTitle(int title) { mTitle = mContext.getResources().getString(title); return this; } public MenuItem setTitleCondensed(CharSequence title) { mTitleCondensed = title; return this; } public MenuItem setVisible(boolean visible) { mFlags = (mFlags & HIDDEN) | (visible ? 0 : HIDDEN); return this; } public boolean invoke() { if (mClickListener != null && mClickListener.onMenuItemClick(this)) { return true; } if (mIntent != null) { mContext.startActivity(mIntent); return true; } return false; } public void setShowAsAction(int show) { // Do nothing. ActionMenuItems always show as action buttons. } public MenuItem setActionView(View actionView) { throw new UnsupportedOperationException(); } public View getActionView() { return null; } @Override public MenuItem setActionView(int resId) { throw new UnsupportedOperationException(); } @Override public ActionProvider getActionProvider() { return null; } @Override public MenuItem setActionProvider(ActionProvider actionProvider) { throw new UnsupportedOperationException(); } @Override public MenuItem setShowAsActionFlags(int actionEnum) { setShowAsAction(actionEnum); return this; } @Override public boolean expandActionView() { return false; } @Override public boolean collapseActionView() { return false; } @Override public boolean isActionViewExpanded() { return false; } @Override public MenuItem setOnActionExpandListener(OnActionExpandListener listener) { // No need to save the listener; ActionMenuItem does not support collapsing items. return this; } }
Java
/* * 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.internal.view.menu; import java.util.ArrayList; import android.content.Context; import android.os.Build; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; /** * Base class for MenuPresenters that have a consistent container view and item * views. Behaves similarly to an AdapterView in that existing item views will * be reused if possible when items change. */ public abstract class BaseMenuPresenter implements MenuPresenter { private static final boolean IS_HONEYCOMB = Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB; protected Context mSystemContext; protected Context mContext; protected MenuBuilder mMenu; protected LayoutInflater mSystemInflater; protected LayoutInflater mInflater; private Callback mCallback; private int mMenuLayoutRes; private int mItemLayoutRes; protected MenuView mMenuView; private int mId; /** * Construct a new BaseMenuPresenter. * * @param context Context for generating system-supplied views * @param menuLayoutRes Layout resource ID for the menu container view * @param itemLayoutRes Layout resource ID for a single item view */ public BaseMenuPresenter(Context context, int menuLayoutRes, int itemLayoutRes) { mSystemContext = context; mSystemInflater = LayoutInflater.from(context); mMenuLayoutRes = menuLayoutRes; mItemLayoutRes = itemLayoutRes; } @Override public void initForMenu(Context context, MenuBuilder menu) { mContext = context; mInflater = LayoutInflater.from(mContext); mMenu = menu; } @Override public MenuView getMenuView(ViewGroup root) { if (mMenuView == null) { mMenuView = (MenuView) mSystemInflater.inflate(mMenuLayoutRes, root, false); mMenuView.initialize(mMenu); updateMenuView(true); } return mMenuView; } /** * Reuses item views when it can */ public void updateMenuView(boolean cleared) { final ViewGroup parent = (ViewGroup) mMenuView; if (parent == null) return; int childIndex = 0; if (mMenu != null) { mMenu.flagActionItems(); ArrayList<MenuItemImpl> visibleItems = mMenu.getVisibleItems(); final int itemCount = visibleItems.size(); for (int i = 0; i < itemCount; i++) { MenuItemImpl item = visibleItems.get(i); if (shouldIncludeItem(childIndex, item)) { final View convertView = parent.getChildAt(childIndex); final MenuItemImpl oldItem = convertView instanceof MenuView.ItemView ? ((MenuView.ItemView) convertView).getItemData() : null; final View itemView = getItemView(item, convertView, parent); if (item != oldItem) { // Don't let old states linger with new data. itemView.setPressed(false); if (IS_HONEYCOMB) itemView.jumpDrawablesToCurrentState(); } if (itemView != convertView) { addItemView(itemView, childIndex); } childIndex++; } } } // Remove leftover views. while (childIndex < parent.getChildCount()) { if (!filterLeftoverView(parent, childIndex)) { childIndex++; } } } /** * Add an item view at the given index. * * @param itemView View to add * @param childIndex Index within the parent to insert at */ protected void addItemView(View itemView, int childIndex) { final ViewGroup currentParent = (ViewGroup) itemView.getParent(); if (currentParent != null) { currentParent.removeView(itemView); } ((ViewGroup) mMenuView).addView(itemView, childIndex); } /** * Filter the child view at index and remove it if appropriate. * @param parent Parent to filter from * @param childIndex Index to filter * @return true if the child view at index was removed */ protected boolean filterLeftoverView(ViewGroup parent, int childIndex) { parent.removeViewAt(childIndex); return true; } public void setCallback(Callback cb) { mCallback = cb; } /** * Create a new item view that can be re-bound to other item data later. * * @return The new item view */ public MenuView.ItemView createItemView(ViewGroup parent) { return (MenuView.ItemView) mSystemInflater.inflate(mItemLayoutRes, parent, false); } /** * Prepare an item view for use. See AdapterView for the basic idea at work here. * This may require creating a new item view, but well-behaved implementations will * re-use the view passed as convertView if present. The returned view will be populated * with data from the item parameter. * * @param item Item to present * @param convertView Existing view to reuse * @param parent Intended parent view - use for inflation. * @return View that presents the requested menu item */ public View getItemView(MenuItemImpl item, View convertView, ViewGroup parent) { MenuView.ItemView itemView; if (convertView instanceof MenuView.ItemView) { itemView = (MenuView.ItemView) convertView; } else { itemView = createItemView(parent); } bindItemView(item, itemView); return (View) itemView; } /** * Bind item data to an existing item view. * * @param item Item to bind * @param itemView View to populate with item data */ public abstract void bindItemView(MenuItemImpl item, MenuView.ItemView itemView); /** * Filter item by child index and item data. * * @param childIndex Indended presentation index of this item * @param item Item to present * @return true if this item should be included in this menu presentation; false otherwise */ public boolean shouldIncludeItem(int childIndex, MenuItemImpl item) { return true; } public void onCloseMenu(MenuBuilder menu, boolean allMenusAreClosing) { if (mCallback != null) { mCallback.onCloseMenu(menu, allMenusAreClosing); } } public boolean onSubMenuSelected(SubMenuBuilder menu) { if (mCallback != null) { return mCallback.onOpenSubMenu(menu); } return false; } public boolean flagActionItems() { return false; } public boolean expandItemActionView(MenuBuilder menu, MenuItemImpl item) { return false; } public boolean collapseItemActionView(MenuBuilder menu, MenuItemImpl item) { return false; } public int getId() { return mId; } public void setId(int id) { mId = id; } }
Java
/* * Copyright (C) 2006 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.actionbarsherlock.internal.view.menu; import android.content.ActivityNotFoundException; import android.content.Context; import android.content.Intent; import android.graphics.drawable.Drawable; import android.util.Log; import android.view.ContextMenu.ContextMenuInfo; import android.view.LayoutInflater; import android.view.View; import android.view.ViewDebug; import android.widget.LinearLayout; import com.actionbarsherlock.view.ActionProvider; import com.actionbarsherlock.view.MenuItem; import com.actionbarsherlock.view.SubMenu; /** * @hide */ public final class MenuItemImpl implements MenuItem { private static final String TAG = "MenuItemImpl"; private static final int SHOW_AS_ACTION_MASK = SHOW_AS_ACTION_NEVER | SHOW_AS_ACTION_IF_ROOM | SHOW_AS_ACTION_ALWAYS; private final int mId; private final int mGroup; private final int mCategoryOrder; private final int mOrdering; private CharSequence mTitle; private CharSequence mTitleCondensed; private Intent mIntent; private char mShortcutNumericChar; private char mShortcutAlphabeticChar; /** The icon's drawable which is only created as needed */ private Drawable mIconDrawable; /** * The icon's resource ID which is used to get the Drawable when it is * needed (if the Drawable isn't already obtained--only one of the two is * needed). */ private int mIconResId = NO_ICON; /** The menu to which this item belongs */ private MenuBuilder mMenu; /** If this item should launch a sub menu, this is the sub menu to launch */ private SubMenuBuilder mSubMenu; private Runnable mItemCallback; private MenuItem.OnMenuItemClickListener mClickListener; private int mFlags = ENABLED; private static final int CHECKABLE = 0x00000001; private static final int CHECKED = 0x00000002; private static final int EXCLUSIVE = 0x00000004; private static final int HIDDEN = 0x00000008; private static final int ENABLED = 0x00000010; private static final int IS_ACTION = 0x00000020; private int mShowAsAction = SHOW_AS_ACTION_NEVER; private View mActionView; private ActionProvider mActionProvider; private OnActionExpandListener mOnActionExpandListener; private boolean mIsActionViewExpanded = false; /** Used for the icon resource ID if this item does not have an icon */ static final int NO_ICON = 0; /** * Current use case is for context menu: Extra information linked to the * View that added this item to the context menu. */ private ContextMenuInfo mMenuInfo; private static String sPrependShortcutLabel; private static String sEnterShortcutLabel; private static String sDeleteShortcutLabel; private static String sSpaceShortcutLabel; /** * Instantiates this menu item. * * @param menu * @param group Item ordering grouping control. The item will be added after * all other items whose order is <= this number, and before any * that are larger than it. This can also be used to define * groups of items for batch state changes. Normally use 0. * @param id Unique item ID. Use 0 if you do not need a unique ID. * @param categoryOrder The ordering for this item. * @param title The text to display for the item. */ MenuItemImpl(MenuBuilder menu, int group, int id, int categoryOrder, int ordering, CharSequence title, int showAsAction) { /* TODO if (sPrependShortcutLabel == null) { // This is instantiated from the UI thread, so no chance of sync issues sPrependShortcutLabel = menu.getContext().getResources().getString( com.android.internal.R.string.prepend_shortcut_label); sEnterShortcutLabel = menu.getContext().getResources().getString( com.android.internal.R.string.menu_enter_shortcut_label); sDeleteShortcutLabel = menu.getContext().getResources().getString( com.android.internal.R.string.menu_delete_shortcut_label); sSpaceShortcutLabel = menu.getContext().getResources().getString( com.android.internal.R.string.menu_space_shortcut_label); }*/ mMenu = menu; mId = id; mGroup = group; mCategoryOrder = categoryOrder; mOrdering = ordering; mTitle = title; mShowAsAction = showAsAction; } /** * Invokes the item by calling various listeners or callbacks. * * @return true if the invocation was handled, false otherwise */ public boolean invoke() { if (mClickListener != null && mClickListener.onMenuItemClick(this)) { return true; } if (mMenu.dispatchMenuItemSelected(mMenu.getRootMenu(), this)) { return true; } if (mItemCallback != null) { mItemCallback.run(); return true; } if (mIntent != null) { try { mMenu.getContext().startActivity(mIntent); return true; } catch (ActivityNotFoundException e) { Log.e(TAG, "Can't find activity to handle intent; ignoring", e); } } if (mActionProvider != null && mActionProvider.onPerformDefaultAction()) { return true; } return false; } public boolean isEnabled() { return (mFlags & ENABLED) != 0; } public MenuItem setEnabled(boolean enabled) { if (enabled) { mFlags |= ENABLED; } else { mFlags &= ~ENABLED; } mMenu.onItemsChanged(false); return this; } public int getGroupId() { return mGroup; } @ViewDebug.CapturedViewProperty public int getItemId() { return mId; } public int getOrder() { return mCategoryOrder; } public int getOrdering() { return mOrdering; } public Intent getIntent() { return mIntent; } public MenuItem setIntent(Intent intent) { mIntent = intent; return this; } Runnable getCallback() { return mItemCallback; } public MenuItem setCallback(Runnable callback) { mItemCallback = callback; return this; } public char getAlphabeticShortcut() { return mShortcutAlphabeticChar; } public MenuItem setAlphabeticShortcut(char alphaChar) { if (mShortcutAlphabeticChar == alphaChar) return this; mShortcutAlphabeticChar = Character.toLowerCase(alphaChar); mMenu.onItemsChanged(false); return this; } public char getNumericShortcut() { return mShortcutNumericChar; } public MenuItem setNumericShortcut(char numericChar) { if (mShortcutNumericChar == numericChar) return this; mShortcutNumericChar = numericChar; mMenu.onItemsChanged(false); return this; } public MenuItem setShortcut(char numericChar, char alphaChar) { mShortcutNumericChar = numericChar; mShortcutAlphabeticChar = Character.toLowerCase(alphaChar); mMenu.onItemsChanged(false); return this; } /** * @return The active shortcut (based on QWERTY-mode of the menu). */ char getShortcut() { return (mMenu.isQwertyMode() ? mShortcutAlphabeticChar : mShortcutNumericChar); } /** * @return The label to show for the shortcut. This includes the chording * key (for example 'Menu+a'). Also, any non-human readable * characters should be human readable (for example 'Menu+enter'). */ String getShortcutLabel() { char shortcut = getShortcut(); if (shortcut == 0) { return ""; } StringBuilder sb = new StringBuilder(sPrependShortcutLabel); switch (shortcut) { case '\n': sb.append(sEnterShortcutLabel); break; case '\b': sb.append(sDeleteShortcutLabel); break; case ' ': sb.append(sSpaceShortcutLabel); break; default: sb.append(shortcut); break; } return sb.toString(); } /** * @return Whether this menu item should be showing shortcuts (depends on * whether the menu should show shortcuts and whether this item has * a shortcut defined) */ boolean shouldShowShortcut() { // Show shortcuts if the menu is supposed to show shortcuts AND this item has a shortcut return mMenu.isShortcutsVisible() && (getShortcut() != 0); } public SubMenu getSubMenu() { return mSubMenu; } public boolean hasSubMenu() { return mSubMenu != null; } void setSubMenu(SubMenuBuilder subMenu) { mSubMenu = subMenu; subMenu.setHeaderTitle(getTitle()); } @ViewDebug.CapturedViewProperty public CharSequence getTitle() { return mTitle; } /** * Gets the title for a particular {@link ItemView} * * @param itemView The ItemView that is receiving the title * @return Either the title or condensed title based on what the ItemView * prefers */ CharSequence getTitleForItemView(MenuView.ItemView itemView) { return ((itemView != null) && itemView.prefersCondensedTitle()) ? getTitleCondensed() : getTitle(); } public MenuItem setTitle(CharSequence title) { mTitle = title; mMenu.onItemsChanged(false); if (mSubMenu != null) { mSubMenu.setHeaderTitle(title); } return this; } public MenuItem setTitle(int title) { return setTitle(mMenu.getContext().getString(title)); } public CharSequence getTitleCondensed() { return mTitleCondensed != null ? mTitleCondensed : mTitle; } public MenuItem setTitleCondensed(CharSequence title) { mTitleCondensed = title; // Could use getTitle() in the loop below, but just cache what it would do here if (title == null) { title = mTitle; } mMenu.onItemsChanged(false); return this; } public Drawable getIcon() { if (mIconDrawable != null) { return mIconDrawable; } if (mIconResId != NO_ICON) { return mMenu.getResources().getDrawable(mIconResId); } return null; } public MenuItem setIcon(Drawable icon) { mIconResId = NO_ICON; mIconDrawable = icon; mMenu.onItemsChanged(false); return this; } public MenuItem setIcon(int iconResId) { mIconDrawable = null; mIconResId = iconResId; // If we have a view, we need to push the Drawable to them mMenu.onItemsChanged(false); return this; } public boolean isCheckable() { return (mFlags & CHECKABLE) == CHECKABLE; } public MenuItem setCheckable(boolean checkable) { final int oldFlags = mFlags; mFlags = (mFlags & ~CHECKABLE) | (checkable ? CHECKABLE : 0); if (oldFlags != mFlags) { mMenu.onItemsChanged(false); } return this; } public void setExclusiveCheckable(boolean exclusive) { mFlags = (mFlags & ~EXCLUSIVE) | (exclusive ? EXCLUSIVE : 0); } public boolean isExclusiveCheckable() { return (mFlags & EXCLUSIVE) != 0; } public boolean isChecked() { return (mFlags & CHECKED) == CHECKED; } public MenuItem setChecked(boolean checked) { if ((mFlags & EXCLUSIVE) != 0) { // Call the method on the Menu since it knows about the others in this // exclusive checkable group mMenu.setExclusiveItemChecked(this); } else { setCheckedInt(checked); } return this; } void setCheckedInt(boolean checked) { final int oldFlags = mFlags; mFlags = (mFlags & ~CHECKED) | (checked ? CHECKED : 0); if (oldFlags != mFlags) { mMenu.onItemsChanged(false); } } public boolean isVisible() { return (mFlags & HIDDEN) == 0; } /** * Changes the visibility of the item. This method DOES NOT notify the * parent menu of a change in this item, so this should only be called from * methods that will eventually trigger this change. If unsure, use {@link #setVisible(boolean)} * instead. * * @param shown Whether to show (true) or hide (false). * @return Whether the item's shown state was changed */ boolean setVisibleInt(boolean shown) { final int oldFlags = mFlags; mFlags = (mFlags & ~HIDDEN) | (shown ? 0 : HIDDEN); return oldFlags != mFlags; } public MenuItem setVisible(boolean shown) { // Try to set the shown state to the given state. If the shown state was changed // (i.e. the previous state isn't the same as given state), notify the parent menu that // the shown state has changed for this item if (setVisibleInt(shown)) mMenu.onItemVisibleChanged(this); return this; } public MenuItem setOnMenuItemClickListener(MenuItem.OnMenuItemClickListener clickListener) { mClickListener = clickListener; return this; } @Override public String toString() { return mTitle.toString(); } void setMenuInfo(ContextMenuInfo menuInfo) { mMenuInfo = menuInfo; } public ContextMenuInfo getMenuInfo() { return mMenuInfo; } public void actionFormatChanged() { mMenu.onItemActionRequestChanged(this); } /** * @return Whether the menu should show icons for menu items. */ public boolean shouldShowIcon() { return mMenu.getOptionalIconsVisible(); } public boolean isActionButton() { return (mFlags & IS_ACTION) == IS_ACTION; } public boolean requestsActionButton() { return (mShowAsAction & SHOW_AS_ACTION_IF_ROOM) == SHOW_AS_ACTION_IF_ROOM; } public boolean requiresActionButton() { return (mShowAsAction & SHOW_AS_ACTION_ALWAYS) == SHOW_AS_ACTION_ALWAYS; } public void setIsActionButton(boolean isActionButton) { if (isActionButton) { mFlags |= IS_ACTION; } else { mFlags &= ~IS_ACTION; } } public boolean showsTextAsAction() { return (mShowAsAction & SHOW_AS_ACTION_WITH_TEXT) == SHOW_AS_ACTION_WITH_TEXT; } public void setShowAsAction(int actionEnum) { switch (actionEnum & SHOW_AS_ACTION_MASK) { case SHOW_AS_ACTION_ALWAYS: case SHOW_AS_ACTION_IF_ROOM: case SHOW_AS_ACTION_NEVER: // Looks good! break; default: // Mutually exclusive options selected! throw new IllegalArgumentException("SHOW_AS_ACTION_ALWAYS, SHOW_AS_ACTION_IF_ROOM," + " and SHOW_AS_ACTION_NEVER are mutually exclusive."); } mShowAsAction = actionEnum; mMenu.onItemActionRequestChanged(this); } public MenuItem setActionView(View view) { mActionView = view; mActionProvider = null; if (view != null && view.getId() == View.NO_ID && mId > 0) { view.setId(mId); } mMenu.onItemActionRequestChanged(this); return this; } public MenuItem setActionView(int resId) { final Context context = mMenu.getContext(); final LayoutInflater inflater = LayoutInflater.from(context); setActionView(inflater.inflate(resId, new LinearLayout(context), false)); return this; } public View getActionView() { if (mActionView != null) { return mActionView; } else if (mActionProvider != null) { mActionView = mActionProvider.onCreateActionView(); return mActionView; } else { return null; } } public ActionProvider getActionProvider() { return mActionProvider; } public MenuItem setActionProvider(ActionProvider actionProvider) { mActionView = null; mActionProvider = actionProvider; mMenu.onItemsChanged(true); // Measurement can be changed return this; } @Override public MenuItem setShowAsActionFlags(int actionEnum) { setShowAsAction(actionEnum); return this; } @Override public boolean expandActionView() { if ((mShowAsAction & SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW) == 0 || mActionView == null) { return false; } if (mOnActionExpandListener == null || mOnActionExpandListener.onMenuItemActionExpand(this)) { return mMenu.expandItemActionView(this); } return false; } @Override public boolean collapseActionView() { if ((mShowAsAction & SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW) == 0) { return false; } if (mActionView == null) { // We're already collapsed if we have no action view. return true; } if (mOnActionExpandListener == null || mOnActionExpandListener.onMenuItemActionCollapse(this)) { return mMenu.collapseItemActionView(this); } return false; } @Override public MenuItem setOnActionExpandListener(OnActionExpandListener listener) { mOnActionExpandListener = listener; return this; } public boolean hasCollapsibleActionView() { return (mShowAsAction & SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW) != 0 && mActionView != null; } public void setActionViewExpanded(boolean isExpanded) { mIsActionViewExpanded = isExpanded; mMenu.onItemsChanged(false); } public boolean isActionViewExpanded() { return mIsActionViewExpanded; } }
Java
/* * Copyright (C) 2006 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.actionbarsherlock.internal.view.menu; import android.content.Context; import android.graphics.drawable.Drawable; import android.view.View; import com.actionbarsherlock.view.Menu; import com.actionbarsherlock.view.MenuItem; import com.actionbarsherlock.view.SubMenu; /** * The model for a sub menu, which is an extension of the menu. Most methods are proxied to * the parent menu. */ public class SubMenuBuilder extends MenuBuilder implements SubMenu { private MenuBuilder mParentMenu; private MenuItemImpl mItem; public SubMenuBuilder(Context context, MenuBuilder parentMenu, MenuItemImpl item) { super(context); mParentMenu = parentMenu; mItem = item; } @Override public void setQwertyMode(boolean isQwerty) { mParentMenu.setQwertyMode(isQwerty); } @Override public boolean isQwertyMode() { return mParentMenu.isQwertyMode(); } @Override public void setShortcutsVisible(boolean shortcutsVisible) { mParentMenu.setShortcutsVisible(shortcutsVisible); } @Override public boolean isShortcutsVisible() { return mParentMenu.isShortcutsVisible(); } public Menu getParentMenu() { return mParentMenu; } public MenuItem getItem() { return mItem; } @Override public void setCallback(Callback callback) { mParentMenu.setCallback(callback); } @Override public MenuBuilder getRootMenu() { return mParentMenu; } @Override boolean dispatchMenuItemSelected(MenuBuilder menu, MenuItem item) { return super.dispatchMenuItemSelected(menu, item) || mParentMenu.dispatchMenuItemSelected(menu, item); } public SubMenu setIcon(Drawable icon) { mItem.setIcon(icon); return this; } public SubMenu setIcon(int iconRes) { mItem.setIcon(iconRes); return this; } public SubMenu setHeaderIcon(Drawable icon) { return (SubMenu) super.setHeaderIconInt(icon); } public SubMenu setHeaderIcon(int iconRes) { return (SubMenu) super.setHeaderIconInt(iconRes); } public SubMenu setHeaderTitle(CharSequence title) { return (SubMenu) super.setHeaderTitleInt(title); } public SubMenu setHeaderTitle(int titleRes) { return (SubMenu) super.setHeaderTitleInt(titleRes); } public SubMenu setHeaderView(View view) { return (SubMenu) super.setHeaderViewInt(view); } @Override public boolean expandItemActionView(MenuItemImpl item) { return mParentMenu.expandItemActionView(item); } @Override public boolean collapseItemActionView(MenuItemImpl item) { return mParentMenu.collapseItemActionView(item); } @Override public String getActionViewStatesKey() { final int itemId = mItem != null ? mItem.getItemId() : 0; if (itemId == 0) { return null; } return super.getActionViewStatesKey() + ":" + itemId; } }
Java
/* * 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.internal.view.menu; import static com.actionbarsherlock.internal.ResourcesCompat.getResources_getInteger; import java.util.ArrayList; import java.util.HashSet; import java.util.Set; import android.content.Context; import android.content.res.Configuration; import android.content.res.Resources; import android.content.res.TypedArray; import android.os.Build; import android.os.Parcel; import android.os.Parcelable; import android.util.SparseBooleanArray; import android.view.SoundEffectConstants; import android.view.View; import android.view.View.MeasureSpec; import android.view.ViewConfiguration; import android.view.ViewGroup; import android.widget.ImageButton; import com.actionbarsherlock.R; import com.actionbarsherlock.internal.view.View_HasStateListenerSupport; import com.actionbarsherlock.internal.view.View_OnAttachStateChangeListener; import com.actionbarsherlock.internal.view.menu.ActionMenuView.ActionMenuChildView; import com.actionbarsherlock.view.ActionProvider; import com.actionbarsherlock.view.MenuItem; /** * MenuPresenter for building action menus as seen in the action bar and action modes. */ public class ActionMenuPresenter extends BaseMenuPresenter implements ActionProvider.SubUiVisibilityListener { //UNUSED private static final String TAG = "ActionMenuPresenter"; private View mOverflowButton; private boolean mReserveOverflow; private boolean mReserveOverflowSet; private int mWidthLimit; private int mActionItemWidthLimit; private int mMaxItems; private boolean mMaxItemsSet; private boolean mStrictWidthLimit; private boolean mWidthLimitSet; private boolean mExpandedActionViewsExclusive; private int mMinCellSize; // Group IDs that have been added as actions - used temporarily, allocated here for reuse. private final SparseBooleanArray mActionButtonGroups = new SparseBooleanArray(); private View mScrapActionButtonView; private OverflowPopup mOverflowPopup; private ActionButtonSubmenu mActionButtonPopup; private OpenOverflowRunnable mPostedOpenRunnable; final PopupPresenterCallback mPopupPresenterCallback = new PopupPresenterCallback(); int mOpenSubMenuId; public ActionMenuPresenter(Context context) { super(context, R.layout.abs__action_menu_layout, R.layout.abs__action_menu_item_layout); } @Override public void initForMenu(Context context, MenuBuilder menu) { super.initForMenu(context, menu); final Resources res = context.getResources(); if (!mReserveOverflowSet) { mReserveOverflow = reserveOverflow(mContext); } if (!mWidthLimitSet) { mWidthLimit = res.getDisplayMetrics().widthPixels / 2; } // Measure for initial configuration if (!mMaxItemsSet) { mMaxItems = getResources_getInteger(context, R.integer.abs__max_action_buttons); } int width = mWidthLimit; if (mReserveOverflow) { if (mOverflowButton == null) { mOverflowButton = new OverflowMenuButton(mSystemContext); final int spec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED); mOverflowButton.measure(spec, spec); } width -= mOverflowButton.getMeasuredWidth(); } else { mOverflowButton = null; } mActionItemWidthLimit = width; mMinCellSize = (int) (ActionMenuView.MIN_CELL_SIZE * res.getDisplayMetrics().density); // Drop a scrap view as it may no longer reflect the proper context/config. mScrapActionButtonView = null; } public static boolean reserveOverflow(Context context) { //Check for theme-forced overflow action item TypedArray a = context.getTheme().obtainStyledAttributes(R.styleable.SherlockTheme); boolean result = a.getBoolean(R.styleable.SherlockTheme_absForceOverflow, false); a.recycle(); if (result) { return true; } if (Build.VERSION.SDK_INT < Build.VERSION_CODES.ICE_CREAM_SANDWICH) { return (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB); } else { return !HasPermanentMenuKey.get(context); } } private static class HasPermanentMenuKey { public static boolean get(Context context) { return ViewConfiguration.get(context).hasPermanentMenuKey(); } } public void onConfigurationChanged(Configuration newConfig) { if (!mMaxItemsSet) { mMaxItems = getResources_getInteger(mContext, R.integer.abs__max_action_buttons); if (mMenu != null) { mMenu.onItemsChanged(true); } } } public void setWidthLimit(int width, boolean strict) { mWidthLimit = width; mStrictWidthLimit = strict; mWidthLimitSet = true; } public void setReserveOverflow(boolean reserveOverflow) { mReserveOverflow = reserveOverflow; mReserveOverflowSet = true; } public void setItemLimit(int itemCount) { mMaxItems = itemCount; mMaxItemsSet = true; } public void setExpandedActionViewsExclusive(boolean isExclusive) { mExpandedActionViewsExclusive = isExclusive; } @Override public MenuView getMenuView(ViewGroup root) { MenuView result = super.getMenuView(root); ((ActionMenuView) result).setPresenter(this); return result; } @Override public View getItemView(MenuItemImpl item, View convertView, ViewGroup parent) { View actionView = item.getActionView(); if (actionView == null || item.hasCollapsibleActionView()) { if (!(convertView instanceof ActionMenuItemView)) { convertView = null; } actionView = super.getItemView(item, convertView, parent); } actionView.setVisibility(item.isActionViewExpanded() ? View.GONE : View.VISIBLE); final ActionMenuView menuParent = (ActionMenuView) parent; final ViewGroup.LayoutParams lp = actionView.getLayoutParams(); if (!menuParent.checkLayoutParams(lp)) { actionView.setLayoutParams(menuParent.generateLayoutParams(lp)); } return actionView; } @Override public void bindItemView(MenuItemImpl item, MenuView.ItemView itemView) { itemView.initialize(item, 0); final ActionMenuView menuView = (ActionMenuView) mMenuView; ActionMenuItemView actionItemView = (ActionMenuItemView) itemView; actionItemView.setItemInvoker(menuView); } @Override public boolean shouldIncludeItem(int childIndex, MenuItemImpl item) { return item.isActionButton(); } @Override public void updateMenuView(boolean cleared) { super.updateMenuView(cleared); if (mMenu != null) { final ArrayList<MenuItemImpl> actionItems = mMenu.getActionItems(); final int count = actionItems.size(); for (int i = 0; i < count; i++) { final ActionProvider provider = actionItems.get(i).getActionProvider(); if (provider != null) { provider.setSubUiVisibilityListener(this); } } } final ArrayList<MenuItemImpl> nonActionItems = mMenu != null ? mMenu.getNonActionItems() : null; boolean hasOverflow = false; if (mReserveOverflow && nonActionItems != null) { final int count = nonActionItems.size(); if (count == 1) { hasOverflow = !nonActionItems.get(0).isActionViewExpanded(); } else { hasOverflow = count > 0; } } if (hasOverflow) { if (mOverflowButton == null) { mOverflowButton = new OverflowMenuButton(mSystemContext); } ViewGroup parent = (ViewGroup) mOverflowButton.getParent(); if (parent != mMenuView) { if (parent != null) { parent.removeView(mOverflowButton); } ActionMenuView menuView = (ActionMenuView) mMenuView; menuView.addView(mOverflowButton, menuView.generateOverflowButtonLayoutParams()); } } else if (mOverflowButton != null && mOverflowButton.getParent() == mMenuView) { ((ViewGroup) mMenuView).removeView(mOverflowButton); } ((ActionMenuView) mMenuView).setOverflowReserved(mReserveOverflow); } @Override public boolean filterLeftoverView(ViewGroup parent, int childIndex) { if (parent.getChildAt(childIndex) == mOverflowButton) return false; return super.filterLeftoverView(parent, childIndex); } public boolean onSubMenuSelected(SubMenuBuilder subMenu) { if (!subMenu.hasVisibleItems()) return false; SubMenuBuilder topSubMenu = subMenu; while (topSubMenu.getParentMenu() != mMenu) { topSubMenu = (SubMenuBuilder) topSubMenu.getParentMenu(); } View anchor = findViewForItem(topSubMenu.getItem()); if (anchor == null) { if (mOverflowButton == null) return false; anchor = mOverflowButton; } mOpenSubMenuId = subMenu.getItem().getItemId(); mActionButtonPopup = new ActionButtonSubmenu(mContext, subMenu); mActionButtonPopup.setAnchorView(anchor); mActionButtonPopup.show(); super.onSubMenuSelected(subMenu); return true; } private View findViewForItem(MenuItem item) { final ViewGroup parent = (ViewGroup) mMenuView; if (parent == null) return null; final int count = parent.getChildCount(); for (int i = 0; i < count; i++) { final View child = parent.getChildAt(i); if (child instanceof MenuView.ItemView && ((MenuView.ItemView) child).getItemData() == item) { return child; } } return null; } /** * Display the overflow menu if one is present. * @return true if the overflow menu was shown, false otherwise. */ public boolean showOverflowMenu() { if (mReserveOverflow && !isOverflowMenuShowing() && mMenu != null && mMenuView != null && mPostedOpenRunnable == null && !mMenu.getNonActionItems().isEmpty()) { OverflowPopup popup = new OverflowPopup(mContext, mMenu, mOverflowButton, true); mPostedOpenRunnable = new OpenOverflowRunnable(popup); // Post this for later; we might still need a layout for the anchor to be right. ((View) mMenuView).post(mPostedOpenRunnable); // ActionMenuPresenter uses null as a callback argument here // to indicate overflow is opening. super.onSubMenuSelected(null); return true; } return false; } /** * Hide the overflow menu if it is currently showing. * * @return true if the overflow menu was hidden, false otherwise. */ public boolean hideOverflowMenu() { if (mPostedOpenRunnable != null && mMenuView != null) { ((View) mMenuView).removeCallbacks(mPostedOpenRunnable); mPostedOpenRunnable = null; return true; } MenuPopupHelper popup = mOverflowPopup; if (popup != null) { popup.dismiss(); return true; } return false; } /** * Dismiss all popup menus - overflow and submenus. * @return true if popups were dismissed, false otherwise. (This can be because none were open.) */ public boolean dismissPopupMenus() { boolean result = hideOverflowMenu(); result |= hideSubMenus(); return result; } /** * Dismiss all submenu popups. * * @return true if popups were dismissed, false otherwise. (This can be because none were open.) */ public boolean hideSubMenus() { if (mActionButtonPopup != null) { mActionButtonPopup.dismiss(); return true; } return false; } /** * @return true if the overflow menu is currently showing */ public boolean isOverflowMenuShowing() { return mOverflowPopup != null && mOverflowPopup.isShowing(); } /** * @return true if space has been reserved in the action menu for an overflow item. */ public boolean isOverflowReserved() { return mReserveOverflow; } public boolean flagActionItems() { final ArrayList<MenuItemImpl> visibleItems = mMenu.getVisibleItems(); final int itemsSize = visibleItems.size(); int maxActions = mMaxItems; int widthLimit = mActionItemWidthLimit; final int querySpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED); final ViewGroup parent = (ViewGroup) mMenuView; int requiredItems = 0; int requestedItems = 0; int firstActionWidth = 0; boolean hasOverflow = false; for (int i = 0; i < itemsSize; i++) { MenuItemImpl item = visibleItems.get(i); if (item.requiresActionButton()) { requiredItems++; } else if (item.requestsActionButton()) { requestedItems++; } else { hasOverflow = true; } if (mExpandedActionViewsExclusive && item.isActionViewExpanded()) { // Overflow everything if we have an expanded action view and we're // space constrained. maxActions = 0; } } // Reserve a spot for the overflow item if needed. if (mReserveOverflow && (hasOverflow || requiredItems + requestedItems > maxActions)) { maxActions--; } maxActions -= requiredItems; final SparseBooleanArray seenGroups = mActionButtonGroups; seenGroups.clear(); int cellSize = 0; int cellsRemaining = 0; if (mStrictWidthLimit) { cellsRemaining = widthLimit / mMinCellSize; final int cellSizeRemaining = widthLimit % mMinCellSize; cellSize = mMinCellSize + cellSizeRemaining / cellsRemaining; } // Flag as many more requested items as will fit. for (int i = 0; i < itemsSize; i++) { MenuItemImpl item = visibleItems.get(i); if (item.requiresActionButton()) { View v = getItemView(item, mScrapActionButtonView, parent); if (mScrapActionButtonView == null) { mScrapActionButtonView = v; } if (mStrictWidthLimit) { cellsRemaining -= ActionMenuView.measureChildForCells(v, cellSize, cellsRemaining, querySpec, 0); } else { v.measure(querySpec, querySpec); } final int measuredWidth = v.getMeasuredWidth(); widthLimit -= measuredWidth; if (firstActionWidth == 0) { firstActionWidth = measuredWidth; } final int groupId = item.getGroupId(); if (groupId != 0) { seenGroups.put(groupId, true); } item.setIsActionButton(true); } else if (item.requestsActionButton()) { // Items in a group with other items that already have an action slot // can break the max actions rule, but not the width limit. final int groupId = item.getGroupId(); final boolean inGroup = seenGroups.get(groupId); boolean isAction = (maxActions > 0 || inGroup) && widthLimit > 0 && (!mStrictWidthLimit || cellsRemaining > 0); if (isAction) { View v = getItemView(item, mScrapActionButtonView, parent); if (mScrapActionButtonView == null) { mScrapActionButtonView = v; } if (mStrictWidthLimit) { final int cells = ActionMenuView.measureChildForCells(v, cellSize, cellsRemaining, querySpec, 0); cellsRemaining -= cells; if (cells == 0) { isAction = false; } } else { v.measure(querySpec, querySpec); } final int measuredWidth = v.getMeasuredWidth(); widthLimit -= measuredWidth; if (firstActionWidth == 0) { firstActionWidth = measuredWidth; } if (mStrictWidthLimit) { isAction &= widthLimit >= 0; } else { // Did this push the entire first item past the limit? isAction &= widthLimit + firstActionWidth > 0; } } if (isAction && groupId != 0) { seenGroups.put(groupId, true); } else if (inGroup) { // We broke the width limit. Demote the whole group, they all overflow now. seenGroups.put(groupId, false); for (int j = 0; j < i; j++) { MenuItemImpl areYouMyGroupie = visibleItems.get(j); if (areYouMyGroupie.getGroupId() == groupId) { // Give back the action slot if (areYouMyGroupie.isActionButton()) maxActions++; areYouMyGroupie.setIsActionButton(false); } } } if (isAction) maxActions--; item.setIsActionButton(isAction); } } return true; } @Override public void onCloseMenu(MenuBuilder menu, boolean allMenusAreClosing) { dismissPopupMenus(); super.onCloseMenu(menu, allMenusAreClosing); } @Override public Parcelable onSaveInstanceState() { SavedState state = new SavedState(); state.openSubMenuId = mOpenSubMenuId; return state; } @Override public void onRestoreInstanceState(Parcelable state) { SavedState saved = (SavedState) state; if (saved.openSubMenuId > 0) { MenuItem item = mMenu.findItem(saved.openSubMenuId); if (item != null) { SubMenuBuilder subMenu = (SubMenuBuilder) item.getSubMenu(); onSubMenuSelected(subMenu); } } } @Override public void onSubUiVisibilityChanged(boolean isVisible) { if (isVisible) { // Not a submenu, but treat it like one. super.onSubMenuSelected(null); } else { mMenu.close(false); } } private static class SavedState implements Parcelable { public int openSubMenuId; SavedState() { } SavedState(Parcel in) { openSubMenuId = in.readInt(); } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeInt(openSubMenuId); } @SuppressWarnings("unused") public static final Parcelable.Creator<SavedState> CREATOR = new Parcelable.Creator<SavedState>() { public SavedState createFromParcel(Parcel in) { return new SavedState(in); } public SavedState[] newArray(int size) { return new SavedState[size]; } }; } private class OverflowMenuButton extends ImageButton implements ActionMenuChildView, View_HasStateListenerSupport { private final Set<View_OnAttachStateChangeListener> mListeners = new HashSet<View_OnAttachStateChangeListener>(); public OverflowMenuButton(Context context) { super(context, null, R.attr.actionOverflowButtonStyle); setClickable(true); setFocusable(true); setVisibility(VISIBLE); setEnabled(true); } @Override public boolean performClick() { if (super.performClick()) { return true; } playSoundEffect(SoundEffectConstants.CLICK); showOverflowMenu(); return true; } public boolean needsDividerBefore() { return false; } public boolean needsDividerAfter() { return false; } @Override protected void onAttachedToWindow() { super.onAttachedToWindow(); for (View_OnAttachStateChangeListener listener : mListeners) { listener.onViewAttachedToWindow(this); } } @Override protected void onDetachedFromWindow() { super.onDetachedFromWindow(); for (View_OnAttachStateChangeListener listener : mListeners) { listener.onViewDetachedFromWindow(this); } } @Override public void addOnAttachStateChangeListener(View_OnAttachStateChangeListener listener) { mListeners.add(listener); } @Override public void removeOnAttachStateChangeListener(View_OnAttachStateChangeListener listener) { mListeners.remove(listener); } } private class OverflowPopup extends MenuPopupHelper { public OverflowPopup(Context context, MenuBuilder menu, View anchorView, boolean overflowOnly) { super(context, menu, anchorView, overflowOnly); setCallback(mPopupPresenterCallback); } @Override public void onDismiss() { super.onDismiss(); mMenu.close(); mOverflowPopup = null; } } private class ActionButtonSubmenu extends MenuPopupHelper { //UNUSED private SubMenuBuilder mSubMenu; public ActionButtonSubmenu(Context context, SubMenuBuilder subMenu) { super(context, subMenu); //UNUSED mSubMenu = subMenu; MenuItemImpl item = (MenuItemImpl) subMenu.getItem(); if (!item.isActionButton()) { // Give a reasonable anchor to nested submenus. setAnchorView(mOverflowButton == null ? (View) mMenuView : mOverflowButton); } setCallback(mPopupPresenterCallback); boolean preserveIconSpacing = false; final int count = subMenu.size(); for (int i = 0; i < count; i++) { MenuItem childItem = subMenu.getItem(i); if (childItem.isVisible() && childItem.getIcon() != null) { preserveIconSpacing = true; break; } } setForceShowIcon(preserveIconSpacing); } @Override public void onDismiss() { super.onDismiss(); mActionButtonPopup = null; mOpenSubMenuId = 0; } } private class PopupPresenterCallback implements MenuPresenter.Callback { @Override public boolean onOpenSubMenu(MenuBuilder subMenu) { if (subMenu == null) return false; mOpenSubMenuId = ((SubMenuBuilder) subMenu).getItem().getItemId(); return false; } @Override public void onCloseMenu(MenuBuilder menu, boolean allMenusAreClosing) { if (menu instanceof SubMenuBuilder) { ((SubMenuBuilder) menu).getRootMenu().close(false); } } } private class OpenOverflowRunnable implements Runnable { private OverflowPopup mPopup; public OpenOverflowRunnable(OverflowPopup popup) { mPopup = popup; } public void run() { mMenu.changeMenuMode(); final View menuView = (View) mMenuView; if (menuView != null && menuView.getWindowToken() != null && mPopup.tryShow()) { mOverflowPopup = mPopup; } mPostedOpenRunnable = null; } } }
Java
package com.actionbarsherlock.internal.view.menu; import android.graphics.drawable.Drawable; import android.view.View; import com.actionbarsherlock.view.MenuItem; import com.actionbarsherlock.view.SubMenu; public class SubMenuWrapper extends MenuWrapper implements SubMenu { private final android.view.SubMenu mNativeSubMenu; private MenuItem mItem = null; public SubMenuWrapper(android.view.SubMenu nativeSubMenu) { super(nativeSubMenu); mNativeSubMenu = nativeSubMenu; } @Override public SubMenu setHeaderTitle(int titleRes) { mNativeSubMenu.setHeaderTitle(titleRes); return this; } @Override public SubMenu setHeaderTitle(CharSequence title) { mNativeSubMenu.setHeaderTitle(title); return this; } @Override public SubMenu setHeaderIcon(int iconRes) { mNativeSubMenu.setHeaderIcon(iconRes); return this; } @Override public SubMenu setHeaderIcon(Drawable icon) { mNativeSubMenu.setHeaderIcon(icon); return this; } @Override public SubMenu setHeaderView(View view) { mNativeSubMenu.setHeaderView(view); return this; } @Override public void clearHeader() { mNativeSubMenu.clearHeader(); } @Override public SubMenu setIcon(int iconRes) { mNativeSubMenu.setIcon(iconRes); return this; } @Override public SubMenu setIcon(Drawable icon) { mNativeSubMenu.setIcon(icon); return this; } @Override public MenuItem getItem() { if (mItem == null) { mItem = new MenuItemWrapper(mNativeSubMenu.getItem()); } return mItem; } }
Java
/* * Copyright (C) 2006 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.actionbarsherlock.internal.view.menu; import java.lang.ref.WeakReference; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.content.res.Configuration; import android.content.res.Resources; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.os.Parcelable; import android.util.SparseArray; import android.view.ContextMenu.ContextMenuInfo; import android.view.KeyCharacterMap; import android.view.KeyEvent; 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.SubMenu; /** * Implementation of the {@link android.view.Menu} interface for creating a * standard menu UI. */ public class MenuBuilder implements Menu { //UNUSED private static final String TAG = "MenuBuilder"; private static final String PRESENTER_KEY = "android:menu:presenters"; private static final String ACTION_VIEW_STATES_KEY = "android:menu:actionviewstates"; private static final String EXPANDED_ACTION_VIEW_ID = "android:menu:expandedactionview"; private static final int[] sCategoryToOrder = new int[] { 1, /* No category */ 4, /* CONTAINER */ 5, /* SYSTEM */ 3, /* SECONDARY */ 2, /* ALTERNATIVE */ 0, /* SELECTED_ALTERNATIVE */ }; private final Context mContext; private final Resources mResources; /** * Whether the shortcuts should be qwerty-accessible. Use isQwertyMode() * instead of accessing this directly. */ private boolean mQwertyMode; /** * Whether the shortcuts should be visible on menus. Use isShortcutsVisible() * instead of accessing this directly. */ private boolean mShortcutsVisible; /** * Callback that will receive the various menu-related events generated by * this class. Use getCallback to get a reference to the callback. */ private Callback mCallback; /** Contains all of the items for this menu */ private ArrayList<MenuItemImpl> mItems; /** Contains only the items that are currently visible. This will be created/refreshed from * {@link #getVisibleItems()} */ private ArrayList<MenuItemImpl> mVisibleItems; /** * Whether or not the items (or any one item's shown state) has changed since it was last * fetched from {@link #getVisibleItems()} */ private boolean mIsVisibleItemsStale; /** * Contains only the items that should appear in the Action Bar, if present. */ private ArrayList<MenuItemImpl> mActionItems; /** * Contains items that should NOT appear in the Action Bar, if present. */ private ArrayList<MenuItemImpl> mNonActionItems; /** * Whether or not the items (or any one item's action state) has changed since it was * last fetched. */ private boolean mIsActionItemsStale; /** * Default value for how added items should show in the action list. */ private int mDefaultShowAsAction = MenuItem.SHOW_AS_ACTION_NEVER; /** * Current use case is Context Menus: As Views populate the context menu, each one has * extra information that should be passed along. This is the current menu info that * should be set on all items added to this menu. */ private ContextMenuInfo mCurrentMenuInfo; /** Header title for menu types that have a header (context and submenus) */ CharSequence mHeaderTitle; /** Header icon for menu types that have a header and support icons (context) */ Drawable mHeaderIcon; /** Header custom view for menu types that have a header and support custom views (context) */ View mHeaderView; /** * Contains the state of the View hierarchy for all menu views when the menu * was frozen. */ //UNUSED private SparseArray<Parcelable> mFrozenViewStates; /** * Prevents onItemsChanged from doing its junk, useful for batching commands * that may individually call onItemsChanged. */ private boolean mPreventDispatchingItemsChanged = false; private boolean mItemsChangedWhileDispatchPrevented = false; private boolean mOptionalIconsVisible = false; private boolean mIsClosing = false; private ArrayList<MenuItemImpl> mTempShortcutItemList = new ArrayList<MenuItemImpl>(); private CopyOnWriteArrayList<WeakReference<MenuPresenter>> mPresenters = new CopyOnWriteArrayList<WeakReference<MenuPresenter>>(); /** * Currently expanded menu item; must be collapsed when we clear. */ private MenuItemImpl mExpandedItem; /** * Called by menu to notify of close and selection changes. */ public interface Callback { /** * Called when a menu item is selected. * @param menu The menu that is the parent of the item * @param item The menu item that is selected * @return whether the menu item selection was handled */ public boolean onMenuItemSelected(MenuBuilder menu, MenuItem item); /** * Called when the mode of the menu changes (for example, from icon to expanded). * * @param menu the menu that has changed modes */ public void onMenuModeChange(MenuBuilder menu); } /** * Called by menu items to execute their associated action */ public interface ItemInvoker { public boolean invokeItem(MenuItemImpl item); } public MenuBuilder(Context context) { mContext = context; mResources = context.getResources(); mItems = new ArrayList<MenuItemImpl>(); mVisibleItems = new ArrayList<MenuItemImpl>(); mIsVisibleItemsStale = true; mActionItems = new ArrayList<MenuItemImpl>(); mNonActionItems = new ArrayList<MenuItemImpl>(); mIsActionItemsStale = true; setShortcutsVisibleInner(true); } public MenuBuilder setDefaultShowAsAction(int defaultShowAsAction) { mDefaultShowAsAction = defaultShowAsAction; return this; } /** * Add a presenter to this menu. This will only hold a WeakReference; * you do not need to explicitly remove a presenter, but you can using * {@link #removeMenuPresenter(MenuPresenter)}. * * @param presenter The presenter to add */ public void addMenuPresenter(MenuPresenter presenter) { mPresenters.add(new WeakReference<MenuPresenter>(presenter)); presenter.initForMenu(mContext, this); mIsActionItemsStale = true; } /** * Remove a presenter from this menu. That presenter will no longer * receive notifications of updates to this menu's data. * * @param presenter The presenter to remove */ public void removeMenuPresenter(MenuPresenter presenter) { for (WeakReference<MenuPresenter> ref : mPresenters) { final MenuPresenter item = ref.get(); if (item == null || item == presenter) { mPresenters.remove(ref); } } } private void dispatchPresenterUpdate(boolean cleared) { if (mPresenters.isEmpty()) return; stopDispatchingItemsChanged(); for (WeakReference<MenuPresenter> ref : mPresenters) { final MenuPresenter presenter = ref.get(); if (presenter == null) { mPresenters.remove(ref); } else { presenter.updateMenuView(cleared); } } startDispatchingItemsChanged(); } private boolean dispatchSubMenuSelected(SubMenuBuilder subMenu) { if (mPresenters.isEmpty()) return false; boolean result = false; for (WeakReference<MenuPresenter> ref : mPresenters) { final MenuPresenter presenter = ref.get(); if (presenter == null) { mPresenters.remove(ref); } else if (!result) { result = presenter.onSubMenuSelected(subMenu); } } return result; } private void dispatchSaveInstanceState(Bundle outState) { if (mPresenters.isEmpty()) return; SparseArray<Parcelable> presenterStates = new SparseArray<Parcelable>(); for (WeakReference<MenuPresenter> ref : mPresenters) { final MenuPresenter presenter = ref.get(); if (presenter == null) { mPresenters.remove(ref); } else { final int id = presenter.getId(); if (id > 0) { final Parcelable state = presenter.onSaveInstanceState(); if (state != null) { presenterStates.put(id, state); } } } } outState.putSparseParcelableArray(PRESENTER_KEY, presenterStates); } private void dispatchRestoreInstanceState(Bundle state) { SparseArray<Parcelable> presenterStates = state.getSparseParcelableArray(PRESENTER_KEY); if (presenterStates == null || mPresenters.isEmpty()) return; for (WeakReference<MenuPresenter> ref : mPresenters) { final MenuPresenter presenter = ref.get(); if (presenter == null) { mPresenters.remove(ref); } else { final int id = presenter.getId(); if (id > 0) { Parcelable parcel = presenterStates.get(id); if (parcel != null) { presenter.onRestoreInstanceState(parcel); } } } } } public void savePresenterStates(Bundle outState) { dispatchSaveInstanceState(outState); } public void restorePresenterStates(Bundle state) { dispatchRestoreInstanceState(state); } public void saveActionViewStates(Bundle outStates) { SparseArray<Parcelable> viewStates = null; final int itemCount = size(); for (int i = 0; i < itemCount; i++) { final MenuItem item = getItem(i); final View v = item.getActionView(); if (v != null && v.getId() != View.NO_ID) { if (viewStates == null) { viewStates = new SparseArray<Parcelable>(); } v.saveHierarchyState(viewStates); if (item.isActionViewExpanded()) { outStates.putInt(EXPANDED_ACTION_VIEW_ID, item.getItemId()); } } if (item.hasSubMenu()) { final SubMenuBuilder subMenu = (SubMenuBuilder) item.getSubMenu(); subMenu.saveActionViewStates(outStates); } } if (viewStates != null) { outStates.putSparseParcelableArray(getActionViewStatesKey(), viewStates); } } public void restoreActionViewStates(Bundle states) { if (states == null) { return; } SparseArray<Parcelable> viewStates = states.getSparseParcelableArray( getActionViewStatesKey()); final int itemCount = size(); for (int i = 0; i < itemCount; i++) { final MenuItem item = getItem(i); final View v = item.getActionView(); if (v != null && v.getId() != View.NO_ID) { v.restoreHierarchyState(viewStates); } if (item.hasSubMenu()) { final SubMenuBuilder subMenu = (SubMenuBuilder) item.getSubMenu(); subMenu.restoreActionViewStates(states); } } final int expandedId = states.getInt(EXPANDED_ACTION_VIEW_ID); if (expandedId > 0) { MenuItem itemToExpand = findItem(expandedId); if (itemToExpand != null) { itemToExpand.expandActionView(); } } } protected String getActionViewStatesKey() { return ACTION_VIEW_STATES_KEY; } public void setCallback(Callback cb) { mCallback = cb; } /** * Adds an item to the menu. The other add methods funnel to this. */ private MenuItem addInternal(int group, int id, int categoryOrder, CharSequence title) { final int ordering = getOrdering(categoryOrder); final MenuItemImpl item = new MenuItemImpl(this, group, id, categoryOrder, ordering, title, mDefaultShowAsAction); if (mCurrentMenuInfo != null) { // Pass along the current menu info item.setMenuInfo(mCurrentMenuInfo); } mItems.add(findInsertIndex(mItems, ordering), item); onItemsChanged(true); return item; } public MenuItem add(CharSequence title) { return addInternal(0, 0, 0, title); } public MenuItem add(int titleRes) { return addInternal(0, 0, 0, mResources.getString(titleRes)); } public MenuItem add(int group, int id, int categoryOrder, CharSequence title) { return addInternal(group, id, categoryOrder, title); } public MenuItem add(int group, int id, int categoryOrder, int title) { return addInternal(group, id, categoryOrder, mResources.getString(title)); } public SubMenu addSubMenu(CharSequence title) { return addSubMenu(0, 0, 0, title); } public SubMenu addSubMenu(int titleRes) { return addSubMenu(0, 0, 0, mResources.getString(titleRes)); } public SubMenu addSubMenu(int group, int id, int categoryOrder, CharSequence title) { final MenuItemImpl item = (MenuItemImpl) addInternal(group, id, categoryOrder, title); final SubMenuBuilder subMenu = new SubMenuBuilder(mContext, this, item); item.setSubMenu(subMenu); return subMenu; } public SubMenu addSubMenu(int group, int id, int categoryOrder, int title) { return addSubMenu(group, id, categoryOrder, mResources.getString(title)); } public int addIntentOptions(int group, int id, int categoryOrder, ComponentName caller, Intent[] specifics, Intent intent, int flags, MenuItem[] outSpecificItems) { PackageManager pm = mContext.getPackageManager(); final List<ResolveInfo> lri = pm.queryIntentActivityOptions(caller, specifics, intent, 0); final int N = lri != null ? lri.size() : 0; if ((flags & FLAG_APPEND_TO_GROUP) == 0) { removeGroup(group); } for (int i=0; i<N; i++) { final ResolveInfo ri = lri.get(i); Intent rintent = new Intent( ri.specificIndex < 0 ? intent : specifics[ri.specificIndex]); rintent.setComponent(new ComponentName( ri.activityInfo.applicationInfo.packageName, ri.activityInfo.name)); final MenuItem item = add(group, id, categoryOrder, ri.loadLabel(pm)) .setIcon(ri.loadIcon(pm)) .setIntent(rintent); if (outSpecificItems != null && ri.specificIndex >= 0) { outSpecificItems[ri.specificIndex] = item; } } return N; } public void removeItem(int id) { removeItemAtInt(findItemIndex(id), true); } public void removeGroup(int group) { final int i = findGroupIndex(group); if (i >= 0) { final int maxRemovable = mItems.size() - i; int numRemoved = 0; while ((numRemoved++ < maxRemovable) && (mItems.get(i).getGroupId() == group)) { // Don't force update for each one, this method will do it at the end removeItemAtInt(i, false); } // Notify menu views onItemsChanged(true); } } /** * Remove the item at the given index and optionally forces menu views to * update. * * @param index The index of the item to be removed. If this index is * invalid an exception is thrown. * @param updateChildrenOnMenuViews Whether to force update on menu views. * Please make sure you eventually call this after your batch of * removals. */ private void removeItemAtInt(int index, boolean updateChildrenOnMenuViews) { if ((index < 0) || (index >= mItems.size())) return; mItems.remove(index); if (updateChildrenOnMenuViews) onItemsChanged(true); } public void removeItemAt(int index) { removeItemAtInt(index, true); } public void clearAll() { mPreventDispatchingItemsChanged = true; clear(); clearHeader(); mPreventDispatchingItemsChanged = false; mItemsChangedWhileDispatchPrevented = false; onItemsChanged(true); } public void clear() { if (mExpandedItem != null) { collapseItemActionView(mExpandedItem); } mItems.clear(); onItemsChanged(true); } void setExclusiveItemChecked(MenuItem item) { final int group = item.getGroupId(); final int N = mItems.size(); for (int i = 0; i < N; i++) { MenuItemImpl curItem = mItems.get(i); if (curItem.getGroupId() == group) { if (!curItem.isExclusiveCheckable()) continue; if (!curItem.isCheckable()) continue; // Check the item meant to be checked, uncheck the others (that are in the group) curItem.setCheckedInt(curItem == item); } } } public void setGroupCheckable(int group, boolean checkable, boolean exclusive) { final int N = mItems.size(); for (int i = 0; i < N; i++) { MenuItemImpl item = mItems.get(i); if (item.getGroupId() == group) { item.setExclusiveCheckable(exclusive); item.setCheckable(checkable); } } } public void setGroupVisible(int group, boolean visible) { final int N = mItems.size(); // We handle the notification of items being changed ourselves, so we use setVisibleInt rather // than setVisible and at the end notify of items being changed boolean changedAtLeastOneItem = false; for (int i = 0; i < N; i++) { MenuItemImpl item = mItems.get(i); if (item.getGroupId() == group) { if (item.setVisibleInt(visible)) changedAtLeastOneItem = true; } } if (changedAtLeastOneItem) onItemsChanged(true); } public void setGroupEnabled(int group, boolean enabled) { final int N = mItems.size(); for (int i = 0; i < N; i++) { MenuItemImpl item = mItems.get(i); if (item.getGroupId() == group) { item.setEnabled(enabled); } } } public boolean hasVisibleItems() { final int size = size(); for (int i = 0; i < size; i++) { MenuItemImpl item = mItems.get(i); if (item.isVisible()) { return true; } } return false; } public MenuItem findItem(int id) { final int size = size(); for (int i = 0; i < size; i++) { MenuItemImpl item = mItems.get(i); if (item.getItemId() == id) { return item; } else if (item.hasSubMenu()) { MenuItem possibleItem = item.getSubMenu().findItem(id); if (possibleItem != null) { return possibleItem; } } } return null; } public int findItemIndex(int id) { final int size = size(); for (int i = 0; i < size; i++) { MenuItemImpl item = mItems.get(i); if (item.getItemId() == id) { return i; } } return -1; } public int findGroupIndex(int group) { return findGroupIndex(group, 0); } public int findGroupIndex(int group, int start) { final int size = size(); if (start < 0) { start = 0; } for (int i = start; i < size; i++) { final MenuItemImpl item = mItems.get(i); if (item.getGroupId() == group) { return i; } } return -1; } public int size() { return mItems.size(); } /** {@inheritDoc} */ public MenuItem getItem(int index) { return mItems.get(index); } public boolean isShortcutKey(int keyCode, KeyEvent event) { return findItemWithShortcutForKey(keyCode, event) != null; } public void setQwertyMode(boolean isQwerty) { mQwertyMode = isQwerty; onItemsChanged(false); } /** * Returns the ordering across all items. This will grab the category from * the upper bits, find out how to order the category with respect to other * categories, and combine it with the lower bits. * * @param categoryOrder The category order for a particular item (if it has * not been or/add with a category, the default category is * assumed). * @return An ordering integer that can be used to order this item across * all the items (even from other categories). */ private static int getOrdering(int categoryOrder) { final int index = (categoryOrder & CATEGORY_MASK) >> CATEGORY_SHIFT; if (index < 0 || index >= sCategoryToOrder.length) { throw new IllegalArgumentException("order does not contain a valid category."); } return (sCategoryToOrder[index] << CATEGORY_SHIFT) | (categoryOrder & USER_MASK); } /** * @return whether the menu shortcuts are in qwerty mode or not */ boolean isQwertyMode() { return mQwertyMode; } /** * Sets whether the shortcuts should be visible on menus. Devices without hardware * key input will never make shortcuts visible even if this method is passed 'true'. * * @param shortcutsVisible Whether shortcuts should be visible (if true and a * menu item does not have a shortcut defined, that item will * still NOT show a shortcut) */ public void setShortcutsVisible(boolean shortcutsVisible) { if (mShortcutsVisible == shortcutsVisible) return; setShortcutsVisibleInner(shortcutsVisible); onItemsChanged(false); } private void setShortcutsVisibleInner(boolean shortcutsVisible) { mShortcutsVisible = shortcutsVisible && mResources.getConfiguration().keyboard != Configuration.KEYBOARD_NOKEYS && mResources.getBoolean( R.bool.abs__config_showMenuShortcutsWhenKeyboardPresent); } /** * @return Whether shortcuts should be visible on menus. */ public boolean isShortcutsVisible() { return mShortcutsVisible; } Resources getResources() { return mResources; } public Context getContext() { return mContext; } boolean dispatchMenuItemSelected(MenuBuilder menu, MenuItem item) { return mCallback != null && mCallback.onMenuItemSelected(menu, item); } /** * Dispatch a mode change event to this menu's callback. */ public void changeMenuMode() { if (mCallback != null) { mCallback.onMenuModeChange(this); } } private static int findInsertIndex(ArrayList<MenuItemImpl> items, int ordering) { for (int i = items.size() - 1; i >= 0; i--) { MenuItemImpl item = items.get(i); if (item.getOrdering() <= ordering) { return i + 1; } } return 0; } public boolean performShortcut(int keyCode, KeyEvent event, int flags) { final MenuItemImpl item = findItemWithShortcutForKey(keyCode, event); boolean handled = false; if (item != null) { handled = performItemAction(item, flags); } if ((flags & FLAG_ALWAYS_PERFORM_CLOSE) != 0) { close(true); } return handled; } /* * This function will return all the menu and sub-menu items that can * be directly (the shortcut directly corresponds) and indirectly * (the ALT-enabled char corresponds to the shortcut) associated * with the keyCode. */ @SuppressWarnings("deprecation") void findItemsWithShortcutForKey(List<MenuItemImpl> items, int keyCode, KeyEvent event) { final boolean qwerty = isQwertyMode(); final int metaState = event.getMetaState(); final KeyCharacterMap.KeyData possibleChars = new KeyCharacterMap.KeyData(); // Get the chars associated with the keyCode (i.e using any chording combo) final boolean isKeyCodeMapped = event.getKeyData(possibleChars); // The delete key is not mapped to '\b' so we treat it specially if (!isKeyCodeMapped && (keyCode != KeyEvent.KEYCODE_DEL)) { return; } // Look for an item whose shortcut is this key. final int N = mItems.size(); for (int i = 0; i < N; i++) { MenuItemImpl item = mItems.get(i); if (item.hasSubMenu()) { ((MenuBuilder)item.getSubMenu()).findItemsWithShortcutForKey(items, keyCode, event); } final char shortcutChar = qwerty ? item.getAlphabeticShortcut() : item.getNumericShortcut(); if (((metaState & (KeyEvent.META_SHIFT_ON | KeyEvent.META_SYM_ON)) == 0) && (shortcutChar != 0) && (shortcutChar == possibleChars.meta[0] || shortcutChar == possibleChars.meta[2] || (qwerty && shortcutChar == '\b' && keyCode == KeyEvent.KEYCODE_DEL)) && item.isEnabled()) { items.add(item); } } } /* * We want to return the menu item associated with the key, but if there is no * ambiguity (i.e. there is only one menu item corresponding to the key) we want * to return it even if it's not an exact match; this allow the user to * _not_ use the ALT key for example, making the use of shortcuts slightly more * user-friendly. An example is on the G1, '!' and '1' are on the same key, and * in Gmail, Menu+1 will trigger Menu+! (the actual shortcut). * * On the other hand, if two (or more) shortcuts corresponds to the same key, * we have to only return the exact match. */ @SuppressWarnings("deprecation") MenuItemImpl findItemWithShortcutForKey(int keyCode, KeyEvent event) { // Get all items that can be associated directly or indirectly with the keyCode ArrayList<MenuItemImpl> items = mTempShortcutItemList; items.clear(); findItemsWithShortcutForKey(items, keyCode, event); if (items.isEmpty()) { return null; } final int metaState = event.getMetaState(); final KeyCharacterMap.KeyData possibleChars = new KeyCharacterMap.KeyData(); // Get the chars associated with the keyCode (i.e using any chording combo) event.getKeyData(possibleChars); // If we have only one element, we can safely returns it final int size = items.size(); if (size == 1) { return items.get(0); } final boolean qwerty = isQwertyMode(); // If we found more than one item associated with the key, // we have to return the exact match for (int i = 0; i < size; i++) { final MenuItemImpl item = items.get(i); final char shortcutChar = qwerty ? item.getAlphabeticShortcut() : item.getNumericShortcut(); if ((shortcutChar == possibleChars.meta[0] && (metaState & KeyEvent.META_ALT_ON) == 0) || (shortcutChar == possibleChars.meta[2] && (metaState & KeyEvent.META_ALT_ON) != 0) || (qwerty && shortcutChar == '\b' && keyCode == KeyEvent.KEYCODE_DEL)) { return item; } } return null; } public boolean performIdentifierAction(int id, int flags) { // Look for an item whose identifier is the id. return performItemAction(findItem(id), flags); } public boolean performItemAction(MenuItem item, int flags) { MenuItemImpl itemImpl = (MenuItemImpl) item; if (itemImpl == null || !itemImpl.isEnabled()) { return false; } boolean invoked = itemImpl.invoke(); if (itemImpl.hasCollapsibleActionView()) { invoked |= itemImpl.expandActionView(); if (invoked) close(true); } else if (item.hasSubMenu()) { close(false); final SubMenuBuilder subMenu = (SubMenuBuilder) item.getSubMenu(); final ActionProvider provider = item.getActionProvider(); if (provider != null && provider.hasSubMenu()) { provider.onPrepareSubMenu(subMenu); } invoked |= dispatchSubMenuSelected(subMenu); if (!invoked) close(true); } else { if ((flags & FLAG_PERFORM_NO_CLOSE) == 0) { close(true); } } return invoked; } /** * Closes the visible menu. * * @param allMenusAreClosing Whether the menus are completely closing (true), * or whether there is another menu coming in this menu's place * (false). For example, if the menu is closing because a * sub menu is about to be shown, <var>allMenusAreClosing</var> * is false. */ final void close(boolean allMenusAreClosing) { if (mIsClosing) return; mIsClosing = true; for (WeakReference<MenuPresenter> ref : mPresenters) { final MenuPresenter presenter = ref.get(); if (presenter == null) { mPresenters.remove(ref); } else { presenter.onCloseMenu(this, allMenusAreClosing); } } mIsClosing = false; } /** {@inheritDoc} */ public void close() { close(true); } /** * Called when an item is added or removed. * * @param structureChanged true if the menu structure changed, * false if only item properties changed. * (Visibility is a structural property since it affects layout.) */ void onItemsChanged(boolean structureChanged) { if (!mPreventDispatchingItemsChanged) { if (structureChanged) { mIsVisibleItemsStale = true; mIsActionItemsStale = true; } dispatchPresenterUpdate(structureChanged); } else { mItemsChangedWhileDispatchPrevented = true; } } /** * Stop dispatching item changed events to presenters until * {@link #startDispatchingItemsChanged()} is called. Useful when * many menu operations are going to be performed as a batch. */ public void stopDispatchingItemsChanged() { if (!mPreventDispatchingItemsChanged) { mPreventDispatchingItemsChanged = true; mItemsChangedWhileDispatchPrevented = false; } } public void startDispatchingItemsChanged() { mPreventDispatchingItemsChanged = false; if (mItemsChangedWhileDispatchPrevented) { mItemsChangedWhileDispatchPrevented = false; onItemsChanged(true); } } /** * Called by {@link MenuItemImpl} when its visible flag is changed. * @param item The item that has gone through a visibility change. */ void onItemVisibleChanged(MenuItemImpl item) { // Notify of items being changed mIsVisibleItemsStale = true; onItemsChanged(true); } /** * Called by {@link MenuItemImpl} when its action request status is changed. * @param item The item that has gone through a change in action request status. */ void onItemActionRequestChanged(MenuItemImpl item) { // Notify of items being changed mIsActionItemsStale = true; onItemsChanged(true); } ArrayList<MenuItemImpl> getVisibleItems() { if (!mIsVisibleItemsStale) return mVisibleItems; // Refresh the visible items mVisibleItems.clear(); final int itemsSize = mItems.size(); MenuItemImpl item; for (int i = 0; i < itemsSize; i++) { item = mItems.get(i); if (item.isVisible()) mVisibleItems.add(item); } mIsVisibleItemsStale = false; mIsActionItemsStale = true; return mVisibleItems; } /** * This method determines which menu items get to be 'action items' that will appear * in an action bar and which items should be 'overflow items' in a secondary menu. * The rules are as follows: * * <p>Items are considered for inclusion in the order specified within the menu. * There is a limit of mMaxActionItems as a total count, optionally including the overflow * menu button itself. This is a soft limit; if an item shares a group ID with an item * previously included as an action item, the new item will stay with its group and become * an action item itself even if it breaks the max item count limit. This is done to * limit the conceptual complexity of the items presented within an action bar. Only a few * unrelated concepts should be presented to the user in this space, and groups are treated * as a single concept. * * <p>There is also a hard limit of consumed measurable space: mActionWidthLimit. This * limit may be broken by a single item that exceeds the remaining space, but no further * items may be added. If an item that is part of a group cannot fit within the remaining * measured width, the entire group will be demoted to overflow. This is done to ensure room * for navigation and other affordances in the action bar as well as reduce general UI clutter. * * <p>The space freed by demoting a full group cannot be consumed by future menu items. * Once items begin to overflow, all future items become overflow items as well. This is * to avoid inadvertent reordering that may break the app's intended design. */ public void flagActionItems() { if (!mIsActionItemsStale) { return; } // Presenters flag action items as needed. boolean flagged = false; for (WeakReference<MenuPresenter> ref : mPresenters) { final MenuPresenter presenter = ref.get(); if (presenter == null) { mPresenters.remove(ref); } else { flagged |= presenter.flagActionItems(); } } if (flagged) { mActionItems.clear(); mNonActionItems.clear(); ArrayList<MenuItemImpl> visibleItems = getVisibleItems(); final int itemsSize = visibleItems.size(); for (int i = 0; i < itemsSize; i++) { MenuItemImpl item = visibleItems.get(i); if (item.isActionButton()) { mActionItems.add(item); } else { mNonActionItems.add(item); } } } else { // Nobody flagged anything, everything is a non-action item. // (This happens during a first pass with no action-item presenters.) mActionItems.clear(); mNonActionItems.clear(); mNonActionItems.addAll(getVisibleItems()); } mIsActionItemsStale = false; } ArrayList<MenuItemImpl> getActionItems() { flagActionItems(); return mActionItems; } ArrayList<MenuItemImpl> getNonActionItems() { flagActionItems(); return mNonActionItems; } public void clearHeader() { mHeaderIcon = null; mHeaderTitle = null; mHeaderView = null; onItemsChanged(false); } private void setHeaderInternal(final int titleRes, final CharSequence title, final int iconRes, final Drawable icon, final View view) { final Resources r = getResources(); if (view != null) { mHeaderView = view; // If using a custom view, then the title and icon aren't used mHeaderTitle = null; mHeaderIcon = null; } else { if (titleRes > 0) { mHeaderTitle = r.getText(titleRes); } else if (title != null) { mHeaderTitle = title; } if (iconRes > 0) { mHeaderIcon = r.getDrawable(iconRes); } else if (icon != null) { mHeaderIcon = icon; } // If using the title or icon, then a custom view isn't used mHeaderView = null; } // Notify of change onItemsChanged(false); } /** * Sets the header's title. This replaces the header view. Called by the * builder-style methods of subclasses. * * @param title The new title. * @return This MenuBuilder so additional setters can be called. */ protected MenuBuilder setHeaderTitleInt(CharSequence title) { setHeaderInternal(0, title, 0, null, null); return this; } /** * Sets the header's title. This replaces the header view. Called by the * builder-style methods of subclasses. * * @param titleRes The new title (as a resource ID). * @return This MenuBuilder so additional setters can be called. */ protected MenuBuilder setHeaderTitleInt(int titleRes) { setHeaderInternal(titleRes, null, 0, null, null); return this; } /** * Sets the header's icon. This replaces the header view. Called by the * builder-style methods of subclasses. * * @param icon The new icon. * @return This MenuBuilder so additional setters can be called. */ protected MenuBuilder setHeaderIconInt(Drawable icon) { setHeaderInternal(0, null, 0, icon, null); return this; } /** * Sets the header's icon. This replaces the header view. Called by the * builder-style methods of subclasses. * * @param iconRes The new icon (as a resource ID). * @return This MenuBuilder so additional setters can be called. */ protected MenuBuilder setHeaderIconInt(int iconRes) { setHeaderInternal(0, null, iconRes, null, null); return this; } /** * Sets the header's view. This replaces the title and icon. Called by the * builder-style methods of subclasses. * * @param view The new view. * @return This MenuBuilder so additional setters can be called. */ protected MenuBuilder setHeaderViewInt(View view) { setHeaderInternal(0, null, 0, null, view); return this; } public CharSequence getHeaderTitle() { return mHeaderTitle; } public Drawable getHeaderIcon() { return mHeaderIcon; } public View getHeaderView() { return mHeaderView; } /** * Gets the root menu (if this is a submenu, find its root menu). * @return The root menu. */ public MenuBuilder getRootMenu() { return this; } /** * Sets the current menu info that is set on all items added to this menu * (until this is called again with different menu info, in which case that * one will be added to all subsequent item additions). * * @param menuInfo The extra menu information to add. */ public void setCurrentMenuInfo(ContextMenuInfo menuInfo) { mCurrentMenuInfo = menuInfo; } void setOptionalIconsVisible(boolean visible) { mOptionalIconsVisible = visible; } boolean getOptionalIconsVisible() { return mOptionalIconsVisible; } public boolean expandItemActionView(MenuItemImpl item) { if (mPresenters.isEmpty()) return false; boolean expanded = false; stopDispatchingItemsChanged(); for (WeakReference<MenuPresenter> ref : mPresenters) { final MenuPresenter presenter = ref.get(); if (presenter == null) { mPresenters.remove(ref); } else if ((expanded = presenter.expandItemActionView(this, item))) { break; } } startDispatchingItemsChanged(); if (expanded) { mExpandedItem = item; } return expanded; } public boolean collapseItemActionView(MenuItemImpl item) { if (mPresenters.isEmpty() || mExpandedItem != item) return false; boolean collapsed = false; stopDispatchingItemsChanged(); for (WeakReference<MenuPresenter> ref : mPresenters) { final MenuPresenter presenter = ref.get(); if (presenter == null) { mPresenters.remove(ref); } else if ((collapsed = presenter.collapseItemActionView(this, item))) { break; } } startDispatchingItemsChanged(); if (collapsed) { mExpandedItem = null; } return collapsed; } public MenuItemImpl getExpandedItem() { return mExpandedItem; } public boolean bindNativeOverflow(android.view.Menu menu, android.view.MenuItem.OnMenuItemClickListener listener, HashMap<android.view.MenuItem, MenuItemImpl> map) { final List<MenuItemImpl> nonActionItems = getNonActionItems(); if (nonActionItems == null || nonActionItems.size() == 0) { return false; } boolean visible = false; menu.clear(); for (MenuItemImpl nonActionItem : nonActionItems) { if (!nonActionItem.isVisible()) { continue; } visible = true; android.view.MenuItem nativeItem; if (nonActionItem.hasSubMenu()) { android.view.SubMenu nativeSub = menu.addSubMenu(nonActionItem.getGroupId(), nonActionItem.getItemId(), nonActionItem.getOrder(), nonActionItem.getTitle()); SubMenuBuilder subMenu = (SubMenuBuilder)nonActionItem.getSubMenu(); for (MenuItemImpl subItem : subMenu.getVisibleItems()) { android.view.MenuItem nativeSubItem = nativeSub.add(subItem.getGroupId(), subItem.getItemId(), subItem.getOrder(), subItem.getTitle()); nativeSubItem.setIcon(subItem.getIcon()); nativeSubItem.setOnMenuItemClickListener(listener); nativeSubItem.setEnabled(subItem.isEnabled()); nativeSubItem.setIntent(subItem.getIntent()); nativeSubItem.setNumericShortcut(subItem.getNumericShortcut()); nativeSubItem.setAlphabeticShortcut(subItem.getAlphabeticShortcut()); nativeSubItem.setTitleCondensed(subItem.getTitleCondensed()); nativeSubItem.setCheckable(subItem.isCheckable()); nativeSubItem.setChecked(subItem.isChecked()); if (subItem.isExclusiveCheckable()) { nativeSub.setGroupCheckable(subItem.getGroupId(), true, true); } map.put(nativeSubItem, subItem); } nativeItem = nativeSub.getItem(); } else { nativeItem = menu.add(nonActionItem.getGroupId(), nonActionItem.getItemId(), nonActionItem.getOrder(), nonActionItem.getTitle()); } nativeItem.setIcon(nonActionItem.getIcon()); nativeItem.setOnMenuItemClickListener(listener); nativeItem.setEnabled(nonActionItem.isEnabled()); nativeItem.setIntent(nonActionItem.getIntent()); nativeItem.setNumericShortcut(nonActionItem.getNumericShortcut()); nativeItem.setAlphabeticShortcut(nonActionItem.getAlphabeticShortcut()); nativeItem.setTitleCondensed(nonActionItem.getTitleCondensed()); nativeItem.setCheckable(nonActionItem.isCheckable()); nativeItem.setChecked(nonActionItem.isChecked()); if (nonActionItem.isExclusiveCheckable()) { menu.setGroupCheckable(nonActionItem.getGroupId(), true, true); } map.put(nativeItem, nonActionItem); } return visible; } }
Java
package com.actionbarsherlock.internal.view.menu; import android.content.Intent; import android.graphics.drawable.Drawable; import android.view.View; import android.view.ContextMenu.ContextMenuInfo; import com.actionbarsherlock.internal.view.ActionProviderWrapper; import com.actionbarsherlock.view.ActionProvider; import com.actionbarsherlock.view.MenuItem; import com.actionbarsherlock.view.SubMenu; public class MenuItemWrapper implements MenuItem, android.view.MenuItem.OnMenuItemClickListener { private final android.view.MenuItem mNativeItem; private SubMenu mSubMenu = null; private OnMenuItemClickListener mMenuItemClickListener = null; private OnActionExpandListener mActionExpandListener = null; private android.view.MenuItem.OnActionExpandListener mNativeActionExpandListener = null; public MenuItemWrapper(android.view.MenuItem nativeItem) { if (nativeItem == null) { throw new IllegalStateException("Wrapped menu item cannot be null."); } mNativeItem = nativeItem; } @Override public int getItemId() { return mNativeItem.getItemId(); } @Override public int getGroupId() { return mNativeItem.getGroupId(); } @Override public int getOrder() { return mNativeItem.getOrder(); } @Override public MenuItem setTitle(CharSequence title) { mNativeItem.setTitle(title); return this; } @Override public MenuItem setTitle(int title) { mNativeItem.setTitle(title); return this; } @Override public CharSequence getTitle() { return mNativeItem.getTitle(); } @Override public MenuItem setTitleCondensed(CharSequence title) { mNativeItem.setTitleCondensed(title); return this; } @Override public CharSequence getTitleCondensed() { return mNativeItem.getTitleCondensed(); } @Override public MenuItem setIcon(Drawable icon) { mNativeItem.setIcon(icon); return this; } @Override public MenuItem setIcon(int iconRes) { mNativeItem.setIcon(iconRes); return this; } @Override public Drawable getIcon() { return mNativeItem.getIcon(); } @Override public MenuItem setIntent(Intent intent) { mNativeItem.setIntent(intent); return this; } @Override public Intent getIntent() { return mNativeItem.getIntent(); } @Override public MenuItem setShortcut(char numericChar, char alphaChar) { mNativeItem.setShortcut(numericChar, alphaChar); return this; } @Override public MenuItem setNumericShortcut(char numericChar) { mNativeItem.setNumericShortcut(numericChar); return this; } @Override public char getNumericShortcut() { return mNativeItem.getNumericShortcut(); } @Override public MenuItem setAlphabeticShortcut(char alphaChar) { mNativeItem.setAlphabeticShortcut(alphaChar); return this; } @Override public char getAlphabeticShortcut() { return mNativeItem.getAlphabeticShortcut(); } @Override public MenuItem setCheckable(boolean checkable) { mNativeItem.setCheckable(checkable); return this; } @Override public boolean isCheckable() { return mNativeItem.isCheckable(); } @Override public MenuItem setChecked(boolean checked) { mNativeItem.setChecked(checked); return this; } @Override public boolean isChecked() { return mNativeItem.isChecked(); } @Override public MenuItem setVisible(boolean visible) { mNativeItem.setVisible(visible); return this; } @Override public boolean isVisible() { return mNativeItem.isVisible(); } @Override public MenuItem setEnabled(boolean enabled) { mNativeItem.setEnabled(enabled); return this; } @Override public boolean isEnabled() { return mNativeItem.isEnabled(); } @Override public boolean hasSubMenu() { return mNativeItem.hasSubMenu(); } @Override public SubMenu getSubMenu() { if (hasSubMenu() && (mSubMenu == null)) { mSubMenu = new SubMenuWrapper(mNativeItem.getSubMenu()); } return mSubMenu; } @Override public MenuItem setOnMenuItemClickListener(OnMenuItemClickListener menuItemClickListener) { mMenuItemClickListener = menuItemClickListener; //Register ourselves as the listener to proxy mNativeItem.setOnMenuItemClickListener(this); return this; } @Override public boolean onMenuItemClick(android.view.MenuItem item) { if (mMenuItemClickListener != null) { return mMenuItemClickListener.onMenuItemClick(this); } return false; } @Override public ContextMenuInfo getMenuInfo() { return mNativeItem.getMenuInfo(); } @Override public void setShowAsAction(int actionEnum) { mNativeItem.setShowAsAction(actionEnum); } @Override public MenuItem setShowAsActionFlags(int actionEnum) { mNativeItem.setShowAsActionFlags(actionEnum); return this; } @Override public MenuItem setActionView(View view) { mNativeItem.setActionView(view); return this; } @Override public MenuItem setActionView(int resId) { mNativeItem.setActionView(resId); return this; } @Override public View getActionView() { return mNativeItem.getActionView(); } @Override public MenuItem setActionProvider(ActionProvider actionProvider) { mNativeItem.setActionProvider(new ActionProviderWrapper(actionProvider)); return this; } @Override public ActionProvider getActionProvider() { android.view.ActionProvider nativeProvider = mNativeItem.getActionProvider(); if (nativeProvider != null && nativeProvider instanceof ActionProviderWrapper) { return ((ActionProviderWrapper)nativeProvider).unwrap(); } return null; } @Override public boolean expandActionView() { return mNativeItem.expandActionView(); } @Override public boolean collapseActionView() { return mNativeItem.collapseActionView(); } @Override public boolean isActionViewExpanded() { return mNativeItem.isActionViewExpanded(); } @Override public MenuItem setOnActionExpandListener(OnActionExpandListener listener) { mActionExpandListener = listener; if (mNativeActionExpandListener == null) { mNativeActionExpandListener = new android.view.MenuItem.OnActionExpandListener() { @Override public boolean onMenuItemActionExpand(android.view.MenuItem menuItem) { if (mActionExpandListener != null) { return mActionExpandListener.onMenuItemActionExpand(MenuItemWrapper.this); } return false; } @Override public boolean onMenuItemActionCollapse(android.view.MenuItem menuItem) { if (mActionExpandListener != null) { return mActionExpandListener.onMenuItemActionCollapse(MenuItemWrapper.this); } return false; } }; //Register our inner-class as the listener to proxy method calls mNativeItem.setOnActionExpandListener(mNativeActionExpandListener); } return this; } }
Java
package com.actionbarsherlock.internal.view.menu; import java.util.WeakHashMap; import android.content.ComponentName; import android.content.Intent; import android.view.KeyEvent; import com.actionbarsherlock.view.Menu; import com.actionbarsherlock.view.MenuItem; import com.actionbarsherlock.view.SubMenu; public class MenuWrapper implements Menu { private final android.view.Menu mNativeMenu; private final WeakHashMap<android.view.MenuItem, MenuItem> mNativeMap = new WeakHashMap<android.view.MenuItem, MenuItem>(); public MenuWrapper(android.view.Menu nativeMenu) { mNativeMenu = nativeMenu; } public android.view.Menu unwrap() { return mNativeMenu; } private MenuItem addInternal(android.view.MenuItem nativeItem) { MenuItem item = new MenuItemWrapper(nativeItem); mNativeMap.put(nativeItem, item); return item; } @Override public MenuItem add(CharSequence title) { return addInternal(mNativeMenu.add(title)); } @Override public MenuItem add(int titleRes) { return addInternal(mNativeMenu.add(titleRes)); } @Override public MenuItem add(int groupId, int itemId, int order, CharSequence title) { return addInternal(mNativeMenu.add(groupId, itemId, order, title)); } @Override public MenuItem add(int groupId, int itemId, int order, int titleRes) { return addInternal(mNativeMenu.add(groupId, itemId, order, titleRes)); } private SubMenu addInternal(android.view.SubMenu nativeSubMenu) { SubMenu subMenu = new SubMenuWrapper(nativeSubMenu); android.view.MenuItem nativeItem = nativeSubMenu.getItem(); MenuItem item = subMenu.getItem(); mNativeMap.put(nativeItem, item); return subMenu; } @Override public SubMenu addSubMenu(CharSequence title) { return addInternal(mNativeMenu.addSubMenu(title)); } @Override public SubMenu addSubMenu(int titleRes) { return addInternal(mNativeMenu.addSubMenu(titleRes)); } @Override public SubMenu addSubMenu(int groupId, int itemId, int order, CharSequence title) { return addInternal(mNativeMenu.addSubMenu(groupId, itemId, order, title)); } @Override public SubMenu addSubMenu(int groupId, int itemId, int order, int titleRes) { return addInternal(mNativeMenu.addSubMenu(groupId, itemId, order, titleRes)); } @Override public int addIntentOptions(int groupId, int itemId, int order, ComponentName caller, Intent[] specifics, Intent intent, int flags, MenuItem[] outSpecificItems) { android.view.MenuItem[] nativeOutItems = new android.view.MenuItem[outSpecificItems.length]; int result = mNativeMenu.addIntentOptions(groupId, itemId, order, caller, specifics, intent, flags, nativeOutItems); for (int i = 0, length = outSpecificItems.length; i < length; i++) { outSpecificItems[i] = new MenuItemWrapper(nativeOutItems[i]); } return result; } @Override public void removeItem(int id) { mNativeMenu.removeItem(id); } @Override public void removeGroup(int groupId) { mNativeMenu.removeGroup(groupId); } @Override public void clear() { mNativeMap.clear(); mNativeMenu.clear(); } @Override public void setGroupCheckable(int group, boolean checkable, boolean exclusive) { mNativeMenu.setGroupCheckable(group, checkable, exclusive); } @Override public void setGroupVisible(int group, boolean visible) { mNativeMenu.setGroupVisible(group, visible); } @Override public void setGroupEnabled(int group, boolean enabled) { mNativeMenu.setGroupEnabled(group, enabled); } @Override public boolean hasVisibleItems() { return mNativeMenu.hasVisibleItems(); } @Override public MenuItem findItem(int id) { android.view.MenuItem nativeItem = mNativeMenu.findItem(id); return findItem(nativeItem); } public MenuItem findItem(android.view.MenuItem nativeItem) { if (nativeItem == null) { return null; } MenuItem wrapped = mNativeMap.get(nativeItem); if (wrapped != null) { return wrapped; } return addInternal(nativeItem); } @Override public int size() { return mNativeMenu.size(); } @Override public MenuItem getItem(int index) { android.view.MenuItem nativeItem = mNativeMenu.getItem(index); return findItem(nativeItem); } @Override public void close() { mNativeMenu.close(); } @Override public boolean performShortcut(int keyCode, KeyEvent event, int flags) { return mNativeMenu.performShortcut(keyCode, event, flags); } @Override public boolean isShortcutKey(int keyCode, KeyEvent event) { return mNativeMenu.isShortcutKey(keyCode, event); } @Override public boolean performIdentifierAction(int id, int flags) { return mNativeMenu.performIdentifierAction(id, flags); } @Override public void setQwertyMode(boolean isQwerty) { mNativeMenu.setQwertyMode(isQwerty); } }
Java
/* * Copyright (C) 2010 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.internal.view.menu; import java.util.HashSet; import java.util.Set; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Rect; import android.graphics.drawable.Drawable; import android.os.Build; import android.text.TextUtils; import android.util.AttributeSet; import android.view.Gravity; import android.view.MotionEvent; import android.view.View; import android.view.accessibility.AccessibilityEvent; import android.widget.ImageButton; import android.widget.LinearLayout; import android.widget.Toast; import com.actionbarsherlock.R; import com.actionbarsherlock.internal.view.View_HasStateListenerSupport; import com.actionbarsherlock.internal.view.View_OnAttachStateChangeListener; import com.actionbarsherlock.internal.widget.CapitalizingButton; import static com.actionbarsherlock.internal.ResourcesCompat.getResources_getBoolean; /** * @hide */ public class ActionMenuItemView extends LinearLayout implements MenuView.ItemView, View.OnClickListener, View.OnLongClickListener, ActionMenuView.ActionMenuChildView, View_HasStateListenerSupport { //UNUSED private static final String TAG = "ActionMenuItemView"; private MenuItemImpl mItemData; private CharSequence mTitle; private MenuBuilder.ItemInvoker mItemInvoker; private ImageButton mImageButton; private CapitalizingButton mTextButton; private boolean mAllowTextWithIcon; private boolean mExpandedFormat; private int mMinWidth; private final Set<View_OnAttachStateChangeListener> mListeners = new HashSet<View_OnAttachStateChangeListener>(); public ActionMenuItemView(Context context) { this(context, null); } public ActionMenuItemView(Context context, AttributeSet attrs) { this(context, attrs, 0); } public ActionMenuItemView(Context context, AttributeSet attrs, int defStyle) { //TODO super(context, attrs, defStyle); super(context, attrs); mAllowTextWithIcon = getResources_getBoolean(context, R.bool.abs__config_allowActionMenuItemTextWithIcon); TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.SherlockActionMenuItemView, 0, 0); mMinWidth = a.getDimensionPixelSize( R.styleable.SherlockActionMenuItemView_android_minWidth, 0); a.recycle(); } @Override public void addOnAttachStateChangeListener(View_OnAttachStateChangeListener listener) { mListeners.add(listener); } @Override public void removeOnAttachStateChangeListener(View_OnAttachStateChangeListener listener) { mListeners.remove(listener); } @Override protected void onAttachedToWindow() { super.onAttachedToWindow(); for (View_OnAttachStateChangeListener listener : mListeners) { listener.onViewAttachedToWindow(this); } } @Override protected void onDetachedFromWindow() { super.onDetachedFromWindow(); for (View_OnAttachStateChangeListener listener : mListeners) { listener.onViewDetachedFromWindow(this); } } @Override public void onFinishInflate() { mImageButton = (ImageButton) findViewById(R.id.abs__imageButton); mTextButton = (CapitalizingButton) findViewById(R.id.abs__textButton); mImageButton.setOnClickListener(this); mTextButton.setOnClickListener(this); mImageButton.setOnLongClickListener(this); setOnClickListener(this); setOnLongClickListener(this); } public MenuItemImpl getItemData() { return mItemData; } public void initialize(MenuItemImpl itemData, int menuType) { mItemData = itemData; setIcon(itemData.getIcon()); setTitle(itemData.getTitleForItemView(this)); // Title only takes effect if there is no icon setId(itemData.getItemId()); setVisibility(itemData.isVisible() ? View.VISIBLE : View.GONE); setEnabled(itemData.isEnabled()); } @Override public void setEnabled(boolean enabled) { super.setEnabled(enabled); mImageButton.setEnabled(enabled); mTextButton.setEnabled(enabled); } public void onClick(View v) { if (mItemInvoker != null) { mItemInvoker.invokeItem(mItemData); } } public void setItemInvoker(MenuBuilder.ItemInvoker invoker) { mItemInvoker = invoker; } public boolean prefersCondensedTitle() { return true; } public void setCheckable(boolean checkable) { // TODO Support checkable action items } public void setChecked(boolean checked) { // TODO Support checkable action items } public void setExpandedFormat(boolean expandedFormat) { if (mExpandedFormat != expandedFormat) { mExpandedFormat = expandedFormat; if (mItemData != null) { mItemData.actionFormatChanged(); } } } private void updateTextButtonVisibility() { boolean visible = !TextUtils.isEmpty(mTextButton.getText()); visible &= mImageButton.getDrawable() == null || (mItemData.showsTextAsAction() && (mAllowTextWithIcon || mExpandedFormat)); mTextButton.setVisibility(visible ? VISIBLE : GONE); } public void setIcon(Drawable icon) { mImageButton.setImageDrawable(icon); if (icon != null) { mImageButton.setVisibility(VISIBLE); } else { mImageButton.setVisibility(GONE); } updateTextButtonVisibility(); } public boolean hasText() { return mTextButton.getVisibility() != GONE; } public void setShortcut(boolean showShortcut, char shortcutKey) { // Action buttons don't show text for shortcut keys. } public void setTitle(CharSequence title) { mTitle = title; mTextButton.setTextCompat(mTitle); setContentDescription(mTitle); updateTextButtonVisibility(); } @Override public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) { onPopulateAccessibilityEvent(event); return true; } @Override public void onPopulateAccessibilityEvent(AccessibilityEvent event) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) { super.onPopulateAccessibilityEvent(event); } final CharSequence cdesc = getContentDescription(); if (!TextUtils.isEmpty(cdesc)) { event.getText().add(cdesc); } } @Override public boolean dispatchHoverEvent(MotionEvent event) { // Don't allow children to hover; we want this to be treated as a single component. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) { return onHoverEvent(event); } return false; } public boolean showsIcon() { return true; } public boolean needsDividerBefore() { return hasText() && mItemData.getIcon() == null; } public boolean needsDividerAfter() { return hasText(); } @Override public boolean onLongClick(View v) { if (hasText()) { // Don't show the cheat sheet for items that already show text. return false; } final int[] screenPos = new int[2]; final Rect displayFrame = new Rect(); getLocationOnScreen(screenPos); getWindowVisibleDisplayFrame(displayFrame); final Context context = getContext(); final int width = getWidth(); final int height = getHeight(); final int midy = screenPos[1] + height / 2; final int screenWidth = context.getResources().getDisplayMetrics().widthPixels; Toast cheatSheet = Toast.makeText(context, mItemData.getTitle(), Toast.LENGTH_SHORT); if (midy < displayFrame.height()) { // Show along the top; follow action buttons cheatSheet.setGravity(Gravity.TOP | Gravity.RIGHT, screenWidth - screenPos[0] - width / 2, height); } else { // Show along the bottom center cheatSheet.setGravity(Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, height); } cheatSheet.show(); return true; } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); final int widthMode = MeasureSpec.getMode(widthMeasureSpec); final int specSize = MeasureSpec.getSize(widthMeasureSpec); final int oldMeasuredWidth = getMeasuredWidth(); final int targetWidth = widthMode == MeasureSpec.AT_MOST ? Math.min(specSize, mMinWidth) : mMinWidth; if (widthMode != MeasureSpec.EXACTLY && mMinWidth > 0 && oldMeasuredWidth < targetWidth) { // Remeasure at exactly the minimum width. super.onMeasure(MeasureSpec.makeMeasureSpec(targetWidth, MeasureSpec.EXACTLY), heightMeasureSpec); } } }
Java
/* * Copyright (C) 2010 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.internal.view.menu; import java.util.ArrayList; import java.util.List; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.view.KeyEvent; import com.actionbarsherlock.view.Menu; import com.actionbarsherlock.view.MenuItem; import com.actionbarsherlock.view.SubMenu; /** * @hide */ public class ActionMenu implements Menu { private Context mContext; private boolean mIsQwerty; private ArrayList<ActionMenuItem> mItems; public ActionMenu(Context context) { mContext = context; mItems = new ArrayList<ActionMenuItem>(); } public Context getContext() { return mContext; } public MenuItem add(CharSequence title) { return add(0, 0, 0, title); } public MenuItem add(int titleRes) { return add(0, 0, 0, titleRes); } public MenuItem add(int groupId, int itemId, int order, int titleRes) { return add(groupId, itemId, order, mContext.getResources().getString(titleRes)); } public MenuItem add(int groupId, int itemId, int order, CharSequence title) { ActionMenuItem item = new ActionMenuItem(getContext(), groupId, itemId, 0, order, title); mItems.add(order, item); return item; } public int addIntentOptions(int groupId, int itemId, int order, ComponentName caller, Intent[] specifics, Intent intent, int flags, MenuItem[] outSpecificItems) { PackageManager pm = mContext.getPackageManager(); final List<ResolveInfo> lri = pm.queryIntentActivityOptions(caller, specifics, intent, 0); final int N = lri != null ? lri.size() : 0; if ((flags & FLAG_APPEND_TO_GROUP) == 0) { removeGroup(groupId); } for (int i=0; i<N; i++) { final ResolveInfo ri = lri.get(i); Intent rintent = new Intent( ri.specificIndex < 0 ? intent : specifics[ri.specificIndex]); rintent.setComponent(new ComponentName( ri.activityInfo.applicationInfo.packageName, ri.activityInfo.name)); final MenuItem item = add(groupId, itemId, order, ri.loadLabel(pm)) .setIcon(ri.loadIcon(pm)) .setIntent(rintent); if (outSpecificItems != null && ri.specificIndex >= 0) { outSpecificItems[ri.specificIndex] = item; } } return N; } public SubMenu addSubMenu(CharSequence title) { // TODO Implement submenus return null; } public SubMenu addSubMenu(int titleRes) { // TODO Implement submenus return null; } public SubMenu addSubMenu(int groupId, int itemId, int order, CharSequence title) { // TODO Implement submenus return null; } public SubMenu addSubMenu(int groupId, int itemId, int order, int titleRes) { // TODO Implement submenus return null; } public void clear() { mItems.clear(); } public void close() { } private int findItemIndex(int id) { final ArrayList<ActionMenuItem> items = mItems; final int itemCount = items.size(); for (int i = 0; i < itemCount; i++) { if (items.get(i).getItemId() == id) { return i; } } return -1; } public MenuItem findItem(int id) { return mItems.get(findItemIndex(id)); } public MenuItem getItem(int index) { return mItems.get(index); } public boolean hasVisibleItems() { final ArrayList<ActionMenuItem> items = mItems; final int itemCount = items.size(); for (int i = 0; i < itemCount; i++) { if (items.get(i).isVisible()) { return true; } } return false; } private ActionMenuItem findItemWithShortcut(int keyCode, KeyEvent event) { // TODO Make this smarter. final boolean qwerty = mIsQwerty; final ArrayList<ActionMenuItem> items = mItems; final int itemCount = items.size(); for (int i = 0; i < itemCount; i++) { ActionMenuItem item = items.get(i); final char shortcut = qwerty ? item.getAlphabeticShortcut() : item.getNumericShortcut(); if (keyCode == shortcut) { return item; } } return null; } public boolean isShortcutKey(int keyCode, KeyEvent event) { return findItemWithShortcut(keyCode, event) != null; } public boolean performIdentifierAction(int id, int flags) { final int index = findItemIndex(id); if (index < 0) { return false; } return mItems.get(index).invoke(); } public boolean performShortcut(int keyCode, KeyEvent event, int flags) { ActionMenuItem item = findItemWithShortcut(keyCode, event); if (item == null) { return false; } return item.invoke(); } public void removeGroup(int groupId) { final ArrayList<ActionMenuItem> items = mItems; int itemCount = items.size(); int i = 0; while (i < itemCount) { if (items.get(i).getGroupId() == groupId) { items.remove(i); itemCount--; } else { i++; } } } public void removeItem(int id) { mItems.remove(findItemIndex(id)); } public void setGroupCheckable(int group, boolean checkable, boolean exclusive) { final ArrayList<ActionMenuItem> items = mItems; final int itemCount = items.size(); for (int i = 0; i < itemCount; i++) { ActionMenuItem item = items.get(i); if (item.getGroupId() == group) { item.setCheckable(checkable); item.setExclusiveCheckable(exclusive); } } } public void setGroupEnabled(int group, boolean enabled) { final ArrayList<ActionMenuItem> items = mItems; final int itemCount = items.size(); for (int i = 0; i < itemCount; i++) { ActionMenuItem item = items.get(i); if (item.getGroupId() == group) { item.setEnabled(enabled); } } } public void setGroupVisible(int group, boolean visible) { final ArrayList<ActionMenuItem> items = mItems; final int itemCount = items.size(); for (int i = 0; i < itemCount; i++) { ActionMenuItem item = items.get(i); if (item.getGroupId() == group) { item.setVisible(visible); } } } public void setQwertyMode(boolean isQwerty) { mIsQwerty = isQwerty; } public int size() { return mItems.size(); } }
Java
/* * Copyright (C) 2010 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.internal.view.menu; import android.content.Context; import android.content.res.Configuration; import android.graphics.Canvas; import android.os.Build; import android.util.AttributeSet; import android.view.Gravity; import android.view.View; import android.view.ViewGroup; import android.view.accessibility.AccessibilityEvent; import android.widget.LinearLayout; import com.actionbarsherlock.internal.widget.IcsLinearLayout; /** * @hide */ public class ActionMenuView extends IcsLinearLayout implements MenuBuilder.ItemInvoker, MenuView { //UNUSED private static final String TAG = "ActionMenuView"; private static final boolean IS_FROYO = Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO; static final int MIN_CELL_SIZE = 56; // dips static final int GENERATED_ITEM_PADDING = 4; // dips private MenuBuilder mMenu; private boolean mReserveOverflow; private ActionMenuPresenter mPresenter; private boolean mFormatItems; private int mFormatItemsWidth; private int mMinCellSize; private int mGeneratedItemPadding; //UNUSED private int mMeasuredExtraWidth; private boolean mFirst = true; public ActionMenuView(Context context) { this(context, null); } public ActionMenuView(Context context, AttributeSet attrs) { super(context, attrs); setBaselineAligned(false); final float density = context.getResources().getDisplayMetrics().density; mMinCellSize = (int) (MIN_CELL_SIZE * density); mGeneratedItemPadding = (int) (GENERATED_ITEM_PADDING * density); } public void setPresenter(ActionMenuPresenter presenter) { mPresenter = presenter; } public boolean isExpandedFormat() { return mFormatItems; } @Override public void onConfigurationChanged(Configuration newConfig) { if (IS_FROYO) { super.onConfigurationChanged(newConfig); } mPresenter.updateMenuView(false); if (mPresenter != null && mPresenter.isOverflowMenuShowing()) { mPresenter.hideOverflowMenu(); mPresenter.showOverflowMenu(); } } @Override protected void onDraw(Canvas canvas) { //Need to trigger a relayout since we may have been added extremely //late in the initial rendering (e.g., when contained in a ViewPager). //See: https://github.com/JakeWharton/ActionBarSherlock/issues/272 if (!IS_FROYO && mFirst) { mFirst = false; requestLayout(); return; } super.onDraw(canvas); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { // If we've been given an exact size to match, apply special formatting during layout. final boolean wasFormatted = mFormatItems; mFormatItems = MeasureSpec.getMode(widthMeasureSpec) == MeasureSpec.EXACTLY; if (wasFormatted != mFormatItems) { mFormatItemsWidth = 0; // Reset this when switching modes } // Special formatting can change whether items can fit as action buttons. // Kick the menu and update presenters when this changes. final int widthSize = MeasureSpec.getMode(widthMeasureSpec); if (mFormatItems && mMenu != null && widthSize != mFormatItemsWidth) { mFormatItemsWidth = widthSize; mMenu.onItemsChanged(true); } if (mFormatItems) { onMeasureExactFormat(widthMeasureSpec, heightMeasureSpec); } else { super.onMeasure(widthMeasureSpec, heightMeasureSpec); } } private void onMeasureExactFormat(int widthMeasureSpec, int heightMeasureSpec) { // We already know the width mode is EXACTLY if we're here. final int heightMode = MeasureSpec.getMode(heightMeasureSpec); int widthSize = MeasureSpec.getSize(widthMeasureSpec); int heightSize = MeasureSpec.getSize(heightMeasureSpec); final int widthPadding = getPaddingLeft() + getPaddingRight(); final int heightPadding = getPaddingTop() + getPaddingBottom(); widthSize -= widthPadding; // Divide the view into cells. final int cellCount = widthSize / mMinCellSize; final int cellSizeRemaining = widthSize % mMinCellSize; if (cellCount == 0) { // Give up, nothing fits. setMeasuredDimension(widthSize, 0); return; } final int cellSize = mMinCellSize + cellSizeRemaining / cellCount; int cellsRemaining = cellCount; int maxChildHeight = 0; int maxCellsUsed = 0; int expandableItemCount = 0; int visibleItemCount = 0; boolean hasOverflow = false; // This is used as a bitfield to locate the smallest items present. Assumes childCount < 64. long smallestItemsAt = 0; final int childCount = getChildCount(); for (int i = 0; i < childCount; i++) { final View child = getChildAt(i); if (child.getVisibility() == GONE) continue; final boolean isGeneratedItem = child instanceof ActionMenuItemView; visibleItemCount++; if (isGeneratedItem) { // Reset padding for generated menu item views; it may change below // and views are recycled. child.setPadding(mGeneratedItemPadding, 0, mGeneratedItemPadding, 0); } final LayoutParams lp = (LayoutParams) child.getLayoutParams(); lp.expanded = false; lp.extraPixels = 0; lp.cellsUsed = 0; lp.expandable = false; lp.leftMargin = 0; lp.rightMargin = 0; lp.preventEdgeOffset = isGeneratedItem && ((ActionMenuItemView) child).hasText(); // Overflow always gets 1 cell. No more, no less. final int cellsAvailable = lp.isOverflowButton ? 1 : cellsRemaining; final int cellsUsed = measureChildForCells(child, cellSize, cellsAvailable, heightMeasureSpec, heightPadding); maxCellsUsed = Math.max(maxCellsUsed, cellsUsed); if (lp.expandable) expandableItemCount++; if (lp.isOverflowButton) hasOverflow = true; cellsRemaining -= cellsUsed; maxChildHeight = Math.max(maxChildHeight, child.getMeasuredHeight()); if (cellsUsed == 1) smallestItemsAt |= (1 << i); } // When we have overflow and a single expanded (text) item, we want to try centering it // visually in the available space even though overflow consumes some of it. final boolean centerSingleExpandedItem = hasOverflow && visibleItemCount == 2; // Divide space for remaining cells if we have items that can expand. // Try distributing whole leftover cells to smaller items first. boolean needsExpansion = false; while (expandableItemCount > 0 && cellsRemaining > 0) { int minCells = Integer.MAX_VALUE; long minCellsAt = 0; // Bit locations are indices of relevant child views int minCellsItemCount = 0; for (int i = 0; i < childCount; i++) { final View child = getChildAt(i); final LayoutParams lp = (LayoutParams) child.getLayoutParams(); // Don't try to expand items that shouldn't. if (!lp.expandable) continue; // Mark indices of children that can receive an extra cell. if (lp.cellsUsed < minCells) { minCells = lp.cellsUsed; minCellsAt = 1 << i; minCellsItemCount = 1; } else if (lp.cellsUsed == minCells) { minCellsAt |= 1 << i; minCellsItemCount++; } } // Items that get expanded will always be in the set of smallest items when we're done. smallestItemsAt |= minCellsAt; if (minCellsItemCount > cellsRemaining) break; // Couldn't expand anything evenly. Stop. // We have enough cells, all minimum size items will be incremented. minCells++; for (int i = 0; i < childCount; i++) { final View child = getChildAt(i); final LayoutParams lp = (LayoutParams) child.getLayoutParams(); if ((minCellsAt & (1 << i)) == 0) { // If this item is already at our small item count, mark it for later. if (lp.cellsUsed == minCells) smallestItemsAt |= 1 << i; continue; } if (centerSingleExpandedItem && lp.preventEdgeOffset && cellsRemaining == 1) { // Add padding to this item such that it centers. child.setPadding(mGeneratedItemPadding + cellSize, 0, mGeneratedItemPadding, 0); } lp.cellsUsed++; lp.expanded = true; cellsRemaining--; } needsExpansion = true; } // Divide any space left that wouldn't divide along cell boundaries // evenly among the smallest items final boolean singleItem = !hasOverflow && visibleItemCount == 1; if (cellsRemaining > 0 && smallestItemsAt != 0 && (cellsRemaining < visibleItemCount - 1 || singleItem || maxCellsUsed > 1)) { float expandCount = Long.bitCount(smallestItemsAt); if (!singleItem) { // The items at the far edges may only expand by half in order to pin to either side. if ((smallestItemsAt & 1) != 0) { LayoutParams lp = (LayoutParams) getChildAt(0).getLayoutParams(); if (!lp.preventEdgeOffset) expandCount -= 0.5f; } if ((smallestItemsAt & (1 << (childCount - 1))) != 0) { LayoutParams lp = ((LayoutParams) getChildAt(childCount - 1).getLayoutParams()); if (!lp.preventEdgeOffset) expandCount -= 0.5f; } } final int extraPixels = expandCount > 0 ? (int) (cellsRemaining * cellSize / expandCount) : 0; for (int i = 0; i < childCount; i++) { if ((smallestItemsAt & (1 << i)) == 0) continue; final View child = getChildAt(i); final LayoutParams lp = (LayoutParams) child.getLayoutParams(); if (child instanceof ActionMenuItemView) { // If this is one of our views, expand and measure at the larger size. lp.extraPixels = extraPixels; lp.expanded = true; if (i == 0 && !lp.preventEdgeOffset) { // First item gets part of its new padding pushed out of sight. // The last item will get this implicitly from layout. lp.leftMargin = -extraPixels / 2; } needsExpansion = true; } else if (lp.isOverflowButton) { lp.extraPixels = extraPixels; lp.expanded = true; lp.rightMargin = -extraPixels / 2; needsExpansion = true; } else { // If we don't know what it is, give it some margins instead // and let it center within its space. We still want to pin // against the edges. if (i != 0) { lp.leftMargin = extraPixels / 2; } if (i != childCount - 1) { lp.rightMargin = extraPixels / 2; } } } cellsRemaining = 0; } // Remeasure any items that have had extra space allocated to them. if (needsExpansion) { int heightSpec = MeasureSpec.makeMeasureSpec(heightSize - heightPadding, heightMode); for (int i = 0; i < childCount; i++) { final View child = getChildAt(i); final LayoutParams lp = (LayoutParams) child.getLayoutParams(); if (!lp.expanded) continue; final int width = lp.cellsUsed * cellSize + lp.extraPixels; child.measure(MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY), heightSpec); } } if (heightMode != MeasureSpec.EXACTLY) { heightSize = maxChildHeight; } setMeasuredDimension(widthSize, heightSize); //UNUSED mMeasuredExtraWidth = cellsRemaining * cellSize; } /** * Measure a child view to fit within cell-based formatting. The child's width * will be measured to a whole multiple of cellSize. * * <p>Sets the expandable and cellsUsed fields of LayoutParams. * * @param child Child to measure * @param cellSize Size of one cell * @param cellsRemaining Number of cells remaining that this view can expand to fill * @param parentHeightMeasureSpec MeasureSpec used by the parent view * @param parentHeightPadding Padding present in the parent view * @return Number of cells this child was measured to occupy */ static int measureChildForCells(View child, int cellSize, int cellsRemaining, int parentHeightMeasureSpec, int parentHeightPadding) { final LayoutParams lp = (LayoutParams) child.getLayoutParams(); final int childHeightSize = MeasureSpec.getSize(parentHeightMeasureSpec) - parentHeightPadding; final int childHeightMode = MeasureSpec.getMode(parentHeightMeasureSpec); final int childHeightSpec = MeasureSpec.makeMeasureSpec(childHeightSize, childHeightMode); int cellsUsed = 0; if (cellsRemaining > 0) { final int childWidthSpec = MeasureSpec.makeMeasureSpec( cellSize * cellsRemaining, MeasureSpec.AT_MOST); child.measure(childWidthSpec, childHeightSpec); final int measuredWidth = child.getMeasuredWidth(); cellsUsed = measuredWidth / cellSize; if (measuredWidth % cellSize != 0) cellsUsed++; } final ActionMenuItemView itemView = child instanceof ActionMenuItemView ? (ActionMenuItemView) child : null; final boolean expandable = !lp.isOverflowButton && itemView != null && itemView.hasText(); lp.expandable = expandable; lp.cellsUsed = cellsUsed; final int targetWidth = cellsUsed * cellSize; child.measure(MeasureSpec.makeMeasureSpec(targetWidth, MeasureSpec.EXACTLY), childHeightSpec); return cellsUsed; } @Override protected void onLayout(boolean changed, int left, int top, int right, int bottom) { if (!mFormatItems) { super.onLayout(changed, left, top, right, bottom); return; } final int childCount = getChildCount(); final int midVertical = (top + bottom) / 2; final int dividerWidth = 0;//getDividerWidth(); int overflowWidth = 0; //UNUSED int nonOverflowWidth = 0; int nonOverflowCount = 0; int widthRemaining = right - left - getPaddingRight() - getPaddingLeft(); boolean hasOverflow = false; for (int i = 0; i < childCount; i++) { final View v = getChildAt(i); if (v.getVisibility() == GONE) { continue; } LayoutParams p = (LayoutParams) v.getLayoutParams(); if (p.isOverflowButton) { overflowWidth = v.getMeasuredWidth(); if (hasDividerBeforeChildAt(i)) { overflowWidth += dividerWidth; } int height = v.getMeasuredHeight(); int r = getWidth() - getPaddingRight() - p.rightMargin; int l = r - overflowWidth; int t = midVertical - (height / 2); int b = t + height; v.layout(l, t, r, b); widthRemaining -= overflowWidth; hasOverflow = true; } else { final int size = v.getMeasuredWidth() + p.leftMargin + p.rightMargin; //UNUSED nonOverflowWidth += size; widthRemaining -= size; //if (hasDividerBeforeChildAt(i)) { //UNUSED nonOverflowWidth += dividerWidth; //} nonOverflowCount++; } } if (childCount == 1 && !hasOverflow) { // Center a single child final View v = getChildAt(0); final int width = v.getMeasuredWidth(); final int height = v.getMeasuredHeight(); final int midHorizontal = (right - left) / 2; final int l = midHorizontal - width / 2; final int t = midVertical - height / 2; v.layout(l, t, l + width, t + height); return; } final int spacerCount = nonOverflowCount - (hasOverflow ? 0 : 1); final int spacerSize = Math.max(0, spacerCount > 0 ? widthRemaining / spacerCount : 0); int startLeft = getPaddingLeft(); for (int i = 0; i < childCount; i++) { final View v = getChildAt(i); final LayoutParams lp = (LayoutParams) v.getLayoutParams(); if (v.getVisibility() == GONE || lp.isOverflowButton) { continue; } startLeft += lp.leftMargin; int width = v.getMeasuredWidth(); int height = v.getMeasuredHeight(); int t = midVertical - height / 2; v.layout(startLeft, t, startLeft + width, t + height); startLeft += width + lp.rightMargin + spacerSize; } } @Override public void onDetachedFromWindow() { super.onDetachedFromWindow(); mPresenter.dismissPopupMenus(); } public boolean isOverflowReserved() { return mReserveOverflow; } public void setOverflowReserved(boolean reserveOverflow) { mReserveOverflow = reserveOverflow; } @Override protected LayoutParams generateDefaultLayoutParams() { LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); params.gravity = Gravity.CENTER_VERTICAL; return params; } @Override public LayoutParams generateLayoutParams(AttributeSet attrs) { return new LayoutParams(getContext(), attrs); } @Override protected LayoutParams generateLayoutParams(ViewGroup.LayoutParams p) { if (p instanceof LayoutParams) { LayoutParams result = new LayoutParams((LayoutParams) p); if (result.gravity <= Gravity.NO_GRAVITY) { result.gravity = Gravity.CENTER_VERTICAL; } return result; } return generateDefaultLayoutParams(); } @Override protected boolean checkLayoutParams(ViewGroup.LayoutParams p) { return p != null && p instanceof LayoutParams; } public LayoutParams generateOverflowButtonLayoutParams() { LayoutParams result = generateDefaultLayoutParams(); result.isOverflowButton = true; return result; } public boolean invokeItem(MenuItemImpl item) { return mMenu.performItemAction(item, 0); } public int getWindowAnimations() { return 0; } public void initialize(MenuBuilder menu) { mMenu = menu; } //@Override protected boolean hasDividerBeforeChildAt(int childIndex) { final View childBefore = getChildAt(childIndex - 1); final View child = getChildAt(childIndex); boolean result = false; if (childIndex < getChildCount() && childBefore instanceof ActionMenuChildView) { result |= ((ActionMenuChildView) childBefore).needsDividerAfter(); } if (childIndex > 0 && child instanceof ActionMenuChildView) { result |= ((ActionMenuChildView) child).needsDividerBefore(); } return result; } public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) { return false; } public interface ActionMenuChildView { public boolean needsDividerBefore(); public boolean needsDividerAfter(); } public static class LayoutParams extends LinearLayout.LayoutParams { public boolean isOverflowButton; public int cellsUsed; public int extraPixels; public boolean expandable; public boolean preventEdgeOffset; public boolean expanded; public LayoutParams(Context c, AttributeSet attrs) { super(c, attrs); } public LayoutParams(LayoutParams other) { super((LinearLayout.LayoutParams) other); isOverflowButton = other.isOverflowButton; } public LayoutParams(int width, int height) { super(width, height); isOverflowButton = false; } public LayoutParams(int width, int height, boolean isOverflowButton) { super(width, height); this.isOverflowButton = isOverflowButton; } } }
Java
/* * 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.internal.view.menu; import android.content.Context; import android.os.Parcelable; import android.view.ViewGroup; /** * A MenuPresenter is responsible for building views for a Menu object. * It takes over some responsibility from the old style monolithic MenuBuilder class. */ public interface MenuPresenter { /** * Called by menu implementation to notify another component of open/close events. */ public interface Callback { /** * Called when a menu is closing. * @param menu * @param allMenusAreClosing */ public void onCloseMenu(MenuBuilder menu, boolean allMenusAreClosing); /** * Called when a submenu opens. Useful for notifying the application * of menu state so that it does not attempt to hide the action bar * while a submenu is open or similar. * * @param subMenu Submenu currently being opened * @return true if the Callback will handle presenting the submenu, false if * the presenter should attempt to do so. */ public boolean onOpenSubMenu(MenuBuilder subMenu); } /** * Initialize this presenter for the given context and menu. * This method is called by MenuBuilder when a presenter is * added. See {@link MenuBuilder#addMenuPresenter(MenuPresenter)} * * @param context Context for this presenter; used for view creation and resource management * @param menu Menu to host */ public void initForMenu(Context context, MenuBuilder menu); /** * Retrieve a MenuView to display the menu specified in * {@link #initForMenu(Context, Menu)}. * * @param root Intended parent of the MenuView. * @return A freshly created MenuView. */ public MenuView getMenuView(ViewGroup root); /** * Update the menu UI in response to a change. Called by * MenuBuilder during the normal course of operation. * * @param cleared true if the menu was entirely cleared */ public void updateMenuView(boolean cleared); /** * Set a callback object that will be notified of menu events * related to this specific presentation. * @param cb Callback that will be notified of future events */ public void setCallback(Callback cb); /** * Called by Menu implementations to indicate that a submenu item * has been selected. An active Callback should be notified, and * if applicable the presenter should present the submenu. * * @param subMenu SubMenu being opened * @return true if the the event was handled, false otherwise. */ public boolean onSubMenuSelected(SubMenuBuilder subMenu); /** * Called by Menu implementations to indicate that a menu or submenu is * closing. Presenter implementations should close the representation * of the menu indicated as necessary and notify a registered callback. * * @param menu Menu or submenu that is closing. * @param allMenusAreClosing True if all associated menus are closing. */ public void onCloseMenu(MenuBuilder menu, boolean allMenusAreClosing); /** * Called by Menu implementations to flag items that will be shown as actions. * @return true if this presenter changed the action status of any items. */ public boolean flagActionItems(); /** * Called when a menu item with a collapsable action view should expand its action view. * * @param menu Menu containing the item to be expanded * @param item Item to be expanded * @return true if this presenter expanded the action view, false otherwise. */ public boolean expandItemActionView(MenuBuilder menu, MenuItemImpl item); /** * Called when a menu item with a collapsable action view should collapse its action view. * * @param menu Menu containing the item to be collapsed * @param item Item to be collapsed * @return true if this presenter collapsed the action view, false otherwise. */ public boolean collapseItemActionView(MenuBuilder menu, MenuItemImpl item); /** * Returns an ID for determining how to save/restore instance state. * @return a valid ID value. */ public int getId(); /** * Returns a Parcelable describing the current state of the presenter. * It will be passed to the {@link #onRestoreInstanceState(Parcelable)} * method of the presenter sharing the same ID later. * @return The saved instance state */ public Parcelable onSaveInstanceState(); /** * Supplies the previously saved instance state to be restored. * @param state The previously saved instance state */ public void onRestoreInstanceState(Parcelable state); }
Java
package com.actionbarsherlock.internal.view; public interface View_HasStateListenerSupport { void addOnAttachStateChangeListener(View_OnAttachStateChangeListener listener); void removeOnAttachStateChangeListener(View_OnAttachStateChangeListener listener); }
Java
/* * Copyright (C) 2010 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.internal.view; import android.content.Context; import android.view.View; import android.view.accessibility.AccessibilityEvent; import java.lang.ref.WeakReference; import com.actionbarsherlock.internal.view.menu.MenuBuilder; import com.actionbarsherlock.internal.view.menu.MenuPopupHelper; import com.actionbarsherlock.internal.view.menu.SubMenuBuilder; import com.actionbarsherlock.internal.widget.ActionBarContextView; import com.actionbarsherlock.view.ActionMode; import com.actionbarsherlock.view.Menu; import com.actionbarsherlock.view.MenuInflater; import com.actionbarsherlock.view.MenuItem; public class StandaloneActionMode extends ActionMode implements MenuBuilder.Callback { private Context mContext; private ActionBarContextView mContextView; private ActionMode.Callback mCallback; private WeakReference<View> mCustomView; private boolean mFinished; private boolean mFocusable; private MenuBuilder mMenu; public StandaloneActionMode(Context context, ActionBarContextView view, ActionMode.Callback callback, boolean isFocusable) { mContext = context; mContextView = view; mCallback = callback; mMenu = new MenuBuilder(context).setDefaultShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM); mMenu.setCallback(this); mFocusable = isFocusable; } @Override public void setTitle(CharSequence title) { mContextView.setTitle(title); } @Override public void setSubtitle(CharSequence subtitle) { mContextView.setSubtitle(subtitle); } @Override public void setTitle(int resId) { setTitle(mContext.getString(resId)); } @Override public void setSubtitle(int resId) { setSubtitle(mContext.getString(resId)); } @Override public void setCustomView(View view) { mContextView.setCustomView(view); mCustomView = view != null ? new WeakReference<View>(view) : null; } @Override public void invalidate() { mCallback.onPrepareActionMode(this, mMenu); } @Override public void finish() { if (mFinished) { return; } mFinished = true; mContextView.sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED); mCallback.onDestroyActionMode(this); } @Override public Menu getMenu() { return mMenu; } @Override public CharSequence getTitle() { return mContextView.getTitle(); } @Override public CharSequence getSubtitle() { return mContextView.getSubtitle(); } @Override public View getCustomView() { return mCustomView != null ? mCustomView.get() : null; } @Override public MenuInflater getMenuInflater() { return new MenuInflater(mContext); } public boolean onMenuItemSelected(MenuBuilder menu, MenuItem item) { return mCallback.onActionItemClicked(this, item); } public void onCloseMenu(MenuBuilder menu, boolean allMenusAreClosing) { } public boolean onSubMenuSelected(SubMenuBuilder subMenu) { if (!subMenu.hasVisibleItems()) { return true; } new MenuPopupHelper(mContext, subMenu).show(); return true; } public void onCloseSubMenu(SubMenuBuilder menu) { } public void onMenuModeChange(MenuBuilder menu) { invalidate(); mContextView.showOverflowMenu(); } public boolean isUiFocusable() { return mFocusable; } }
Java
package com.actionbarsherlock.internal.view; import com.actionbarsherlock.internal.view.menu.SubMenuWrapper; import com.actionbarsherlock.view.ActionProvider; import android.view.View; public class ActionProviderWrapper extends android.view.ActionProvider { private final ActionProvider mProvider; public ActionProviderWrapper(ActionProvider provider) { super(null/*TODO*/); //XXX this *should* be unused mProvider = provider; } public ActionProvider unwrap() { return mProvider; } @Override public View onCreateActionView() { return mProvider.onCreateActionView(); } @Override public boolean hasSubMenu() { return mProvider.hasSubMenu(); } @Override public boolean onPerformDefaultAction() { return mProvider.onPerformDefaultAction(); } @Override public void onPrepareSubMenu(android.view.SubMenu subMenu) { mProvider.onPrepareSubMenu(new SubMenuWrapper(subMenu)); } }
Java
package com.actionbarsherlock.internal; import com.actionbarsherlock.ActionBarSherlock; import com.actionbarsherlock.app.ActionBar; import com.actionbarsherlock.internal.app.ActionBarWrapper; import com.actionbarsherlock.internal.view.menu.MenuWrapper; import com.actionbarsherlock.view.ActionMode; import com.actionbarsherlock.view.MenuInflater; import android.app.Activity; import android.content.Context; import android.util.Log; import android.util.TypedValue; import android.view.ContextThemeWrapper; import android.view.View; import android.view.Window; import android.view.ViewGroup.LayoutParams; @ActionBarSherlock.Implementation(api = 14) public class ActionBarSherlockNative extends ActionBarSherlock { private ActionBarWrapper mActionBar; private ActionModeWrapper mActionMode; private MenuWrapper mMenu; public ActionBarSherlockNative(Activity activity, int flags) { super(activity, flags); } @Override public ActionBar getActionBar() { if (DEBUG) Log.d(TAG, "[getActionBar]"); initActionBar(); return mActionBar; } private void initActionBar() { if (mActionBar != null || mActivity.getActionBar() == null) { return; } mActionBar = new ActionBarWrapper(mActivity); } @Override public void dispatchInvalidateOptionsMenu() { if (DEBUG) Log.d(TAG, "[dispatchInvalidateOptionsMenu]"); mActivity.getWindow().invalidatePanelMenu(Window.FEATURE_OPTIONS_PANEL); } @Override public boolean dispatchCreateOptionsMenu(android.view.Menu menu) { if (DEBUG) Log.d(TAG, "[dispatchCreateOptionsMenu] menu: " + menu); if (mMenu == null || menu != mMenu.unwrap()) { mMenu = new MenuWrapper(menu); } final boolean result = callbackCreateOptionsMenu(mMenu); if (DEBUG) Log.d(TAG, "[dispatchCreateOptionsMenu] returning " + result); return result; } @Override public boolean dispatchPrepareOptionsMenu(android.view.Menu menu) { if (DEBUG) Log.d(TAG, "[dispatchPrepareOptionsMenu] menu: " + menu); final boolean result = callbackPrepareOptionsMenu(mMenu); if (DEBUG) Log.d(TAG, "[dispatchPrepareOptionsMenu] returning " + result); return result; } @Override public boolean dispatchOptionsItemSelected(android.view.MenuItem item) { if (DEBUG) Log.d(TAG, "[dispatchOptionsItemSelected] item: " + item.getTitleCondensed()); final boolean result = callbackOptionsItemSelected(mMenu.findItem(item)); if (DEBUG) Log.d(TAG, "[dispatchOptionsItemSelected] returning " + result); return result; } @Override public boolean hasFeature(int feature) { if (DEBUG) Log.d(TAG, "[hasFeature] feature: " + feature); final boolean result = mActivity.getWindow().hasFeature(feature); if (DEBUG) Log.d(TAG, "[hasFeature] returning " + result); return result; } @Override public boolean requestFeature(int featureId) { if (DEBUG) Log.d(TAG, "[requestFeature] featureId: " + featureId); final boolean result = mActivity.getWindow().requestFeature(featureId); if (DEBUG) Log.d(TAG, "[requestFeature] returning " + result); return result; } @Override public void setUiOptions(int uiOptions) { if (DEBUG) Log.d(TAG, "[setUiOptions] uiOptions: " + uiOptions); mActivity.getWindow().setUiOptions(uiOptions); } @Override public void setUiOptions(int uiOptions, int mask) { if (DEBUG) Log.d(TAG, "[setUiOptions] uiOptions: " + uiOptions + ", mask: " + mask); mActivity.getWindow().setUiOptions(uiOptions, mask); } @Override public void setContentView(int layoutResId) { if (DEBUG) Log.d(TAG, "[setContentView] layoutResId: " + layoutResId); mActivity.getWindow().setContentView(layoutResId); initActionBar(); } @Override public void setContentView(View view, LayoutParams params) { if (DEBUG) Log.d(TAG, "[setContentView] view: " + view + ", params: " + params); mActivity.getWindow().setContentView(view, params); initActionBar(); } @Override public void addContentView(View view, LayoutParams params) { if (DEBUG) Log.d(TAG, "[addContentView] view: " + view + ", params: " + params); mActivity.getWindow().addContentView(view, params); initActionBar(); } @Override public void setTitle(CharSequence title) { if (DEBUG) Log.d(TAG, "[setTitle] title: " + title); mActivity.getWindow().setTitle(title); } @Override public void setProgressBarVisibility(boolean visible) { if (DEBUG) Log.d(TAG, "[setProgressBarVisibility] visible: " + visible); mActivity.setProgressBarVisibility(visible); } @Override public void setProgressBarIndeterminateVisibility(boolean visible) { if (DEBUG) Log.d(TAG, "[setProgressBarIndeterminateVisibility] visible: " + visible); mActivity.setProgressBarIndeterminateVisibility(visible); } @Override public void setProgressBarIndeterminate(boolean indeterminate) { if (DEBUG) Log.d(TAG, "[setProgressBarIndeterminate] indeterminate: " + indeterminate); mActivity.setProgressBarIndeterminate(indeterminate); } @Override public void setProgress(int progress) { if (DEBUG) Log.d(TAG, "[setProgress] progress: " + progress); mActivity.setProgress(progress); } @Override public void setSecondaryProgress(int secondaryProgress) { if (DEBUG) Log.d(TAG, "[setSecondaryProgress] secondaryProgress: " + secondaryProgress); mActivity.setSecondaryProgress(secondaryProgress); } @Override protected Context getThemedContext() { Context context = mActivity; TypedValue outValue = new TypedValue(); mActivity.getTheme().resolveAttribute(android.R.attr.actionBarWidgetTheme, outValue, true); if (outValue.resourceId != 0) { //We are unable to test if this is the same as our current theme //so we just wrap it and hope that if the attribute was specified //then the user is intentionally specifying an alternate theme. context = new ContextThemeWrapper(context, outValue.resourceId); } return context; } @Override public ActionMode startActionMode(com.actionbarsherlock.view.ActionMode.Callback callback) { if (DEBUG) Log.d(TAG, "[startActionMode] callback: " + callback); if (mActionMode != null) { mActionMode.finish(); } ActionModeCallbackWrapper wrapped = null; if (callback != null) { wrapped = new ActionModeCallbackWrapper(callback); } //Calling this will trigger the callback wrapper's onCreate which //is where we will set the new instance to mActionMode since we need //to pass it through to the sherlock callbacks and the call below //will not have returned yet to store its value. mActivity.startActionMode(wrapped); return mActionMode; } private class ActionModeCallbackWrapper implements android.view.ActionMode.Callback { private final ActionMode.Callback mCallback; public ActionModeCallbackWrapper(ActionMode.Callback callback) { mCallback = callback; } @Override public boolean onCreateActionMode(android.view.ActionMode mode, android.view.Menu menu) { //See ActionBarSherlockNative#startActionMode mActionMode = new ActionModeWrapper(mode); return mCallback.onCreateActionMode(mActionMode, mActionMode.getMenu()); } @Override public boolean onPrepareActionMode(android.view.ActionMode mode, android.view.Menu menu) { return mCallback.onPrepareActionMode(mActionMode, mActionMode.getMenu()); } @Override public boolean onActionItemClicked(android.view.ActionMode mode, android.view.MenuItem item) { return mCallback.onActionItemClicked(mActionMode, mActionMode.getMenu().findItem(item)); } @Override public void onDestroyActionMode(android.view.ActionMode mode) { mCallback.onDestroyActionMode(mActionMode); } } private class ActionModeWrapper extends ActionMode { private final android.view.ActionMode mActionMode; private MenuWrapper mMenu = null; ActionModeWrapper(android.view.ActionMode actionMode) { mActionMode = actionMode; } @Override public void setTitle(CharSequence title) { mActionMode.setTitle(title); } @Override public void setTitle(int resId) { mActionMode.setTitle(resId); } @Override public void setSubtitle(CharSequence subtitle) { mActionMode.setSubtitle(subtitle); } @Override public void setSubtitle(int resId) { mActionMode.setSubtitle(resId); } @Override public void setCustomView(View view) { mActionMode.setCustomView(view); } @Override public void invalidate() { mActionMode.invalidate(); } @Override public void finish() { mActionMode.finish(); } @Override public MenuWrapper getMenu() { if (mMenu == null) { mMenu = new MenuWrapper(mActionMode.getMenu()); } return mMenu; } @Override public CharSequence getTitle() { return mActionMode.getTitle(); } @Override public CharSequence getSubtitle() { return mActionMode.getSubtitle(); } @Override public View getCustomView() { return mActionMode.getCustomView(); } @Override public MenuInflater getMenuInflater() { return ActionBarSherlockNative.this.getMenuInflater(); } @Override public void setTag(Object tag) { mActionMode.setTag(tag); } @Override public Object getTag() { return mActionMode.getTag(); } } }
Java
/* * 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; /** * <p> * 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. * <p> * </p> * 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. * </p> * <p> * The way clients interact with this class is as follows: * </p> * <p> * <pre> * <code> * // 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); * <pre> * <code> * </p> * <p> * <strong>Note:</strong> This class is thread safe. * </p> * * @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 <code>activities</code> 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<ActivityResolveInfo> activities, List<HistoricalRecord> 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. * <p> * <strong>Note:</strong> Modifying the intent is not permitted and * any changes to the latter will be ignored. * </p> * * @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<String, ActivityChooserModel> sDataModelRegistry = new HashMap<String, ActivityChooserModel>(); /** * Lock for synchronizing on this instance. */ private final Object mInstanceLock = new Object(); /** * List of activities that can handle the current intent. */ private final List<ActivityResolveInfo> mActivites = new ArrayList<ActivityResolveInfo>(); /** * List with historical choice records. */ private final List<HistoricalRecord> mHistoricalRecords = new ArrayList<HistoricalRecord>(); /** * 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. * <p> * <strong>Note:</strong> 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 <code>null</code> for the file name. In such * case a new model is returned for each invocation. * </p> * * <p> * <strong>Always use difference historical data files for semantically different actions. * For example, sharing is different from importing.</strong> * </p> * * @param context Context for loading resources. * @param historyFileName File name with choice history, <code>null</code> * 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. * <p> * <strong>Note:</strong> Clients must set only semantically similar * intents for each data model. * <p> * * @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<ActivityResolveInfo> 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. * <p> * <strong>Note:</strong> 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. * </p> * * @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, <code>null</code> 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. * <p> * <strong>Note:</strong> 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. * <p> */ 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<Runnable> mTasks = new LinkedList<Runnable>(); 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} * <p> * <strong>Note:</strong> 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. * </p> * * @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<HistoricalRecord> 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<ResolveInfo> 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<ActivityResolveInfo> { /** * 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<String, ActivityResolveInfo> mPackageNameToActivityMap = new HashMap<String, ActivityResolveInfo>(); public void sort(Intent intent, List<ActivityResolveInfo> activities, List<HistoricalRecord> historicalRecords) { Map<String, ActivityResolveInfo> 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<HistoricalRecord> readRecords = new ArrayList<HistoricalRecord>(); 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<HistoricalRecord> uniqueShareRecords = new LinkedHashSet<HistoricalRecord>(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<HistoricalRecord> 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<HistoricalRecord> records = null; synchronized (mInstanceLock) { records = new ArrayList<HistoricalRecord>(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 */ } } } } } }
Java
/* * 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}. * <p> * The view is composed of two adjacent buttons: * <ul> * <li> * 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. * </li> * <li> * 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. * </li> * </ul> * </p> * * @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. * * <strong>Note:</strong> 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; } } }
Java
/* * 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. * <p> * Here is how to use the action provider with custom backing file in a {@link MenuItem}: * </p> * <p> * <pre> * <code> * // 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); * } * </pre> * </code> * </p> * <p> * <strong>Note:</strong> 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. * </p> * * @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. * <p> * <strong>Note:</strong> Modifying the intent is not permitted and * any changes to the latter will be ignored. * </p> * * @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. * <p> * <strong>Note:</strong> If you choose the backing share history file * you will still be notified in this callback. * </p> * @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 <code>null</code> * if share history should not be persisted between sessions. * <p> * <strong>Note:</strong> 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. * <p> * * @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: * <p> * <pre> * <code> * 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()); * </pre> * </code> * </p> * * @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; } } }
Java
package com.actionbarsherlock; import static android.view.ViewGroup.LayoutParams.MATCH_PARENT; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.util.HashMap; import java.util.Iterator; import android.app.Activity; import android.content.Context; import android.content.res.Configuration; import android.os.Build; import android.os.Bundle; import android.util.DisplayMetrics; import android.util.Log; import android.view.KeyEvent; import android.view.View; import android.view.ViewGroup; import android.view.Window; import com.actionbarsherlock.app.ActionBar; import com.actionbarsherlock.internal.ActionBarSherlockCompat; import com.actionbarsherlock.internal.ActionBarSherlockNative; import com.actionbarsherlock.view.ActionMode; import com.actionbarsherlock.view.Menu; import com.actionbarsherlock.view.MenuInflater; import com.actionbarsherlock.view.MenuItem; /** * <p>Helper for implementing the action bar design pattern across all versions * of Android.</p> * * <p>This class will manage interaction with a custom action bar based on the * Android 4.0 source code. The exposed API mirrors that of its native * counterpart and you should refer to its documentation for instruction.</p> * * @author Jake Wharton <jakewharton@gmail.com> */ public abstract class ActionBarSherlock { protected static final String TAG = "ActionBarSherlock"; protected static final boolean DEBUG = false; private static final Class<?>[] CONSTRUCTOR_ARGS = new Class[] { Activity.class, int.class }; private static final HashMap<Implementation, Class<? extends ActionBarSherlock>> IMPLEMENTATIONS = new HashMap<Implementation, Class<? extends ActionBarSherlock>>(); static { //Register our two built-in implementations registerImplementation(ActionBarSherlockCompat.class); registerImplementation(ActionBarSherlockNative.class); } /** * <p>Denotes an implementation of ActionBarSherlock which provides an * action bar-enhanced experience.</p> */ @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) public @interface Implementation { static final int DEFAULT_API = -1; static final int DEFAULT_DPI = -1; int api() default DEFAULT_API; int dpi() default DEFAULT_DPI; } /** Activity interface for menu creation callback. */ public interface OnCreatePanelMenuListener { public boolean onCreatePanelMenu(int featureId, Menu menu); } /** Activity interface for menu creation callback. */ public interface OnCreateOptionsMenuListener { public boolean onCreateOptionsMenu(Menu menu); } /** Activity interface for menu item selection callback. */ public interface OnMenuItemSelectedListener { public boolean onMenuItemSelected(int featureId, MenuItem item); } /** Activity interface for menu item selection callback. */ public interface OnOptionsItemSelectedListener { public boolean onOptionsItemSelected(MenuItem item); } /** Activity interface for menu preparation callback. */ public interface OnPreparePanelListener { public boolean onPreparePanel(int featureId, View view, Menu menu); } /** Activity interface for menu preparation callback. */ public interface OnPrepareOptionsMenuListener { public boolean onPrepareOptionsMenu(Menu menu); } /** Activity interface for action mode finished callback. */ public interface OnActionModeFinishedListener { public void onActionModeFinished(ActionMode mode); } /** Activity interface for action mode started callback. */ public interface OnActionModeStartedListener { public void onActionModeStarted(ActionMode mode); } /** * If set, the logic in these classes will assume that an {@link Activity} * is dispatching all of the required events to the class. This flag should * only be used internally or if you are creating your own base activity * modeled after one of the included types (e.g., {@code SherlockActivity}). */ public static final int FLAG_DELEGATE = 1; /** * Register an ActionBarSherlock implementation. * * @param implementationClass Target implementation class which extends * {@link ActionBarSherlock}. This class must also be annotated with * {@link Implementation}. */ public static void registerImplementation(Class<? extends ActionBarSherlock> implementationClass) { if (!implementationClass.isAnnotationPresent(Implementation.class)) { throw new IllegalArgumentException("Class " + implementationClass.getSimpleName() + " is not annotated with @Implementation"); } else if (IMPLEMENTATIONS.containsValue(implementationClass)) { if (DEBUG) Log.w(TAG, "Class " + implementationClass.getSimpleName() + " already registered"); return; } Implementation impl = implementationClass.getAnnotation(Implementation.class); if (DEBUG) Log.i(TAG, "Registering " + implementationClass.getSimpleName() + " with qualifier " + impl); IMPLEMENTATIONS.put(impl, implementationClass); } /** * Unregister an ActionBarSherlock implementation. <strong>This should be * considered very volatile and you should only use it if you know what * you are doing.</strong> You have been warned. * * @param implementationClass Target implementation class. * @return Boolean indicating whether the class was removed. */ public static boolean unregisterImplementation(Class<? extends ActionBarSherlock> implementationClass) { return IMPLEMENTATIONS.values().remove(implementationClass); } /** * Wrap an activity with an action bar abstraction which will enable the * use of a custom implementation on platforms where a native version does * not exist. * * @param activity Activity to wrap. * @return Instance to interact with the action bar. */ public static ActionBarSherlock wrap(Activity activity) { return wrap(activity, 0); } /** * Wrap an activity with an action bar abstraction which will enable the * use of a custom implementation on platforms where a native version does * not exist. * * @param activity Owning activity. * @param flags Option flags to control behavior. * @return Instance to interact with the action bar. */ public static ActionBarSherlock wrap(Activity activity, int flags) { //Create a local implementation map we can modify HashMap<Implementation, Class<? extends ActionBarSherlock>> impls = new HashMap<Implementation, Class<? extends ActionBarSherlock>>(IMPLEMENTATIONS); boolean hasQualfier; /* DPI FILTERING */ hasQualfier = false; for (Implementation key : impls.keySet()) { //Only honor TVDPI as a specific qualifier if (key.dpi() == DisplayMetrics.DENSITY_TV) { hasQualfier = true; break; } } if (hasQualfier) { final boolean isTvDpi = activity.getResources().getDisplayMetrics().densityDpi == DisplayMetrics.DENSITY_TV; for (Iterator<Implementation> keys = impls.keySet().iterator(); keys.hasNext(); ) { int keyDpi = keys.next().dpi(); if ((isTvDpi && keyDpi != DisplayMetrics.DENSITY_TV) || (!isTvDpi && keyDpi == DisplayMetrics.DENSITY_TV)) { keys.remove(); } } } /* API FILTERING */ hasQualfier = false; for (Implementation key : impls.keySet()) { if (key.api() != Implementation.DEFAULT_API) { hasQualfier = true; break; } } if (hasQualfier) { final int runtimeApi = Build.VERSION.SDK_INT; int bestApi = 0; for (Iterator<Implementation> keys = impls.keySet().iterator(); keys.hasNext(); ) { int keyApi = keys.next().api(); if (keyApi > runtimeApi) { keys.remove(); } else if (keyApi > bestApi) { bestApi = keyApi; } } for (Iterator<Implementation> keys = impls.keySet().iterator(); keys.hasNext(); ) { if (keys.next().api() != bestApi) { keys.remove(); } } } if (impls.size() > 1) { throw new IllegalStateException("More than one implementation matches configuration."); } if (impls.isEmpty()) { throw new IllegalStateException("No implementations match configuration."); } Class<? extends ActionBarSherlock> impl = impls.values().iterator().next(); if (DEBUG) Log.i(TAG, "Using implementation: " + impl.getSimpleName()); try { Constructor<? extends ActionBarSherlock> ctor = impl.getConstructor(CONSTRUCTOR_ARGS); return ctor.newInstance(activity, flags); } catch (NoSuchMethodException e) { throw new RuntimeException(e); } catch (IllegalArgumentException e) { throw new RuntimeException(e); } catch (InstantiationException e) { throw new RuntimeException(e); } catch (IllegalAccessException e) { throw new RuntimeException(e); } catch (InvocationTargetException e) { throw new RuntimeException(e); } } /** Activity which is displaying the action bar. Also used for context. */ protected final Activity mActivity; /** Whether delegating actions for the activity or managing ourselves. */ protected final boolean mIsDelegate; /** Reference to our custom menu inflater which supports action items. */ protected MenuInflater mMenuInflater; protected ActionBarSherlock(Activity activity, int flags) { if (DEBUG) Log.d(TAG, "[<ctor>] activity: " + activity + ", flags: " + flags); mActivity = activity; mIsDelegate = (flags & FLAG_DELEGATE) != 0; } /** * Get the current action bar instance. * * @return Action bar instance. */ public abstract ActionBar getActionBar(); /////////////////////////////////////////////////////////////////////////// // Lifecycle and interaction callbacks when delegating /////////////////////////////////////////////////////////////////////////// /** * Notify action bar of a configuration change event. Should be dispatched * after the call to the superclass implementation. * * <blockquote><pre> * @Override * public void onConfigurationChanged(Configuration newConfig) { * super.onConfigurationChanged(newConfig); * mSherlock.dispatchConfigurationChanged(newConfig); * } * </pre></blockquote> * * @param newConfig The new device configuration. */ public void dispatchConfigurationChanged(Configuration newConfig) {} /** * Notify the action bar that the activity has finished its resuming. This * should be dispatched after the call to the superclass implementation. * * <blockquote><pre> * @Override * protected void onPostResume() { * super.onPostResume(); * mSherlock.dispatchPostResume(); * } * </pre></blockquote> */ public void dispatchPostResume() {} /** * Notify the action bar that the activity is pausing. This should be * dispatched before the call to the superclass implementation. * * <blockquote><pre> * @Override * protected void onPause() { * mSherlock.dispatchPause(); * super.onPause(); * } * </pre></blockquote> */ public void dispatchPause() {} /** * Notify the action bar that the activity is stopping. This should be * called before the superclass implementation. * * <blockquote><p> * @Override * protected void onStop() { * mSherlock.dispatchStop(); * super.onStop(); * } * </p></blockquote> */ public void dispatchStop() {} /** * Indicate that the menu should be recreated by calling * {@link OnCreateOptionsMenuListener#onCreateOptionsMenu(com.actionbarsherlock.view.Menu)}. */ public abstract void dispatchInvalidateOptionsMenu(); /** * Notify the action bar that it should display its overflow menu if it is * appropriate for the device. The implementation should conditionally * call the superclass method only if this method returns {@code false}. * * <blockquote><p> * @Override * public void openOptionsMenu() { * if (!mSherlock.dispatchOpenOptionsMenu()) { * super.openOptionsMenu(); * } * } * </p></blockquote> * * @return {@code true} if the opening of the menu was handled internally. */ public boolean dispatchOpenOptionsMenu() { return false; } /** * Notify the action bar that it should close its overflow menu if it is * appropriate for the device. This implementation should conditionally * call the superclass method only if this method returns {@code false}. * * <blockquote><pre> * @Override * public void closeOptionsMenu() { * if (!mSherlock.dispatchCloseOptionsMenu()) { * super.closeOptionsMenu(); * } * } * </pre></blockquote> * * @return {@code true} if the closing of the menu was handled internally. */ public boolean dispatchCloseOptionsMenu() { return false; } /** * Notify the class that the activity has finished its creation. This * should be called after the superclass implementation. * * <blockquote><pre> * @Override * protected void onPostCreate(Bundle savedInstanceState) { * mSherlock.dispatchPostCreate(savedInstanceState); * super.onPostCreate(savedInstanceState); * } * </pre></blockquote> * * @param savedInstanceState If the activity is being re-initialized after * previously being shut down then this Bundle * contains the data it most recently supplied in * {@link Activity#}onSaveInstanceState(Bundle)}. * <strong>Note: Otherwise it is null.</strong> */ public void dispatchPostCreate(Bundle savedInstanceState) {} /** * Notify the action bar that the title has changed and the action bar * should be updated to reflect the change. This should be called before * the superclass implementation. * * <blockquote><pre> * @Override * protected void onTitleChanged(CharSequence title, int color) { * mSherlock.dispatchTitleChanged(title, color); * super.onTitleChanged(title, color); * } * </pre></blockquote> * * @param title New activity title. * @param color New activity color. */ public void dispatchTitleChanged(CharSequence title, int color) {} /** * Notify the action bar the user has created a key event. This is used to * toggle the display of the overflow action item with the menu key and to * close the action mode or expanded action item with the back key. * * <blockquote><pre> * @Override * public boolean dispatchKeyEvent(KeyEvent event) { * if (mSherlock.dispatchKeyEvent(event)) { * return true; * } * return super.dispatchKeyEvent(event); * } * </pre></blockquote> * * @param event Description of the key event. * @return {@code true} if the event was handled. */ public boolean dispatchKeyEvent(KeyEvent event) { return false; } /** * 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. * * @param menu Activity native menu. * @return {@code true} since we always want to say that we have a native */ public abstract boolean dispatchCreateOptionsMenu(android.view.Menu menu); /** * Notify the action bar that the Activity has triggered a menu preparation * which usually means that the user has requested the overflow menu via a * hardware menu key. You should return the result of this method call and * not call the superclass implementation. * * <blockquote><p> * @Override * public final boolean onPrepareOptionsMenu(android.view.Menu menu) { * return mSherlock.dispatchPrepareOptionsMenu(menu); * } * </p></blockquote> * * @param menu Activity native menu. * @return {@code true} if menu display should proceed. */ public abstract boolean dispatchPrepareOptionsMenu(android.view.Menu menu); /** * Notify the action bar that a native options menu item has been selected. * The implementation should return the result of this method call. * * <blockquote><p> * @Override * public final boolean onOptionsItemSelected(android.view.MenuItem item) { * return mSherlock.dispatchOptionsItemSelected(item); * } * </p></blockquote> * * @param item Options menu item. * @return @{code true} if the selection was handled. */ public abstract boolean dispatchOptionsItemSelected(android.view.MenuItem item); /** * Notify the action bar that the overflow menu has been opened. The * implementation should conditionally return {@code true} if this method * returns {@code true}, otherwise return the result of the superclass * method. * * <blockquote><p> * @Override * public final boolean onMenuOpened(int featureId, android.view.Menu menu) { * if (mSherlock.dispatchMenuOpened(featureId, menu)) { * return true; * } * return super.onMenuOpened(featureId, menu); * } * </p></blockquote> * * @param featureId Window feature which triggered the event. * @param menu Activity native menu. * @return {@code true} if the event was handled by this method. */ public boolean dispatchMenuOpened(int featureId, android.view.Menu menu) { return false; } /** * Notify the action bar that the overflow menu has been closed. This * method should be called before the superclass implementation. * * <blockquote><p> * @Override * public void onPanelClosed(int featureId, android.view.Menu menu) { * mSherlock.dispatchPanelClosed(featureId, menu); * super.onPanelClosed(featureId, menu); * } * </p></blockquote> * * @param featureId * @param menu */ public void dispatchPanelClosed(int featureId, android.view.Menu menu) {} /** * Notify the action bar that the activity has been destroyed. This method * should be called before the superclass implementation. * * <blockquote><p> * @Override * public void onDestroy() { * mSherlock.dispatchDestroy(); * super.onDestroy(); * } * </p></blockquote> */ public void dispatchDestroy() {} /////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////// /** * Internal method to trigger the menu creation process. * * @return {@code true} if menu creation should proceed. */ protected final boolean callbackCreateOptionsMenu(Menu menu) { if (DEBUG) Log.d(TAG, "[callbackCreateOptionsMenu] menu: " + menu); 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 abstract boolean hasFeature(int featureId); /** * Enable extended screen features. This must be called before * {@code setContentView()}. May be called as many times as desired as long * as it is before {@code setContentView()}. If not called, no extended * features will be available. You can not turn off a feature once it is * requested. * * @param featureId The desired features, defined as constants by Window. * @return Returns true if the requested feature is supported and now * enabled. */ 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 abstract void setUiOptions(int uiOptions); /** * Set extra options that will influence the UI for this window. Only the * bits filtered by mask will be modified. * * @param uiOptions Flags specifying extra options for this window. * @param mask Flags specifying which options should be modified. Others * will remain unchanged. */ public abstract void setUiOptions(int uiOptions, int mask); /** * Set the content of the activity inside the action bar. * * @param layoutResId Layout resource ID. */ public abstract void setContentView(int layoutResId); /** * Set the content of the activity inside the action bar. * * @param view The desired content to display. */ public void setContentView(View view) { if (DEBUG) Log.d(TAG, "[setContentView] view: " + view); setContentView(view, new ViewGroup.LayoutParams(MATCH_PARENT, MATCH_PARENT)); } /** * Set the content of the activity inside the action bar. * * @param view The desired content to display. * @param params Layout parameters to apply to the view. */ public abstract void setContentView(View view, ViewGroup.LayoutParams params); /** * Variation on {@link #setContentView(android.view.View, android.view.ViewGroup.LayoutParams)} * to add an additional content view to the screen. Added after any * existing ones on the screen -- existing views are NOT removed. * * @param view The desired content to display. * @param params Layout parameters for the view. */ public abstract void addContentView(View view, ViewGroup.LayoutParams params); /** * Change the title associated with this activity. */ public abstract void setTitle(CharSequence title); /** * Change the title associated with this activity. */ public void setTitle(int resId) { if (DEBUG) Log.d(TAG, "[setTitle] resId: " + resId); setTitle(mActivity.getString(resId)); } /** * Sets the visibility of the progress bar in the title. * <p> * In order for the progress bar to be shown, the feature must be requested * via {@link #requestWindowFeature(int)}. * * @param visible Whether to show the progress bars in the title. */ public abstract void setProgressBarVisibility(boolean visible); /** * Sets the visibility of the indeterminate progress bar in the title. * <p> * In order for the progress bar to be shown, the feature must be requested * via {@link #requestWindowFeature(int)}. * * @param visible Whether to show the progress bars in the title. */ public abstract void setProgressBarIndeterminateVisibility(boolean visible); /** * Sets whether the horizontal progress bar in the title should be indeterminate (the circular * is always indeterminate). * <p> * In order for the progress bar to be shown, the feature must be requested * via {@link #requestWindowFeature(int)}. * * @param indeterminate Whether the horizontal progress bar should be indeterminate. */ public abstract void setProgressBarIndeterminate(boolean indeterminate); /** * Sets the progress for the progress bars in the title. * <p> * In order for the progress bar to be shown, the feature must be requested * via {@link #requestWindowFeature(int)}. * * @param progress The progress for the progress bar. Valid ranges are from * 0 to 10000 (both inclusive). If 10000 is given, the progress * bar will be completely filled and will fade out. */ public abstract void setProgress(int progress); /** * Sets the secondary progress for the progress bar in the title. This * progress is drawn between the primary progress (set via * {@link #setProgress(int)} and the background. It can be ideal for media * scenarios such as showing the buffering progress while the default * progress shows the play progress. * <p> * In order for the progress bar to be shown, the feature must be requested * via {@link #requestWindowFeature(int)}. * * @param secondaryProgress The secondary progress for the progress bar. Valid ranges are from * 0 to 10000 (both inclusive). */ public abstract void setSecondaryProgress(int secondaryProgress); /** * Get a menu inflater instance which supports the newer menu attributes. * * @return Menu inflater instance. */ public MenuInflater getMenuInflater() { if (DEBUG) Log.d(TAG, "[getMenuInflater]"); // Make sure that action views can get an appropriate theme. if (mMenuInflater == null) { if (getActionBar() != null) { mMenuInflater = new MenuInflater(getThemedContext()); } else { mMenuInflater = new MenuInflater(mActivity); } } return mMenuInflater; } protected abstract Context getThemedContext(); /** * Start an action mode. * * @param callback Callback that will manage lifecycle events for this * context mode. * @return The ContextMode that was started, or null if it was canceled. * @see ActionMode */ public abstract ActionMode startActionMode(ActionMode.Callback callback); }
Java
/* * Copyright (C) 2007 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.view; import android.graphics.drawable.Drawable; import android.view.View; /** * Subclass of {@link Menu} for sub menus. * <p> * Sub menus do not support item icons, or nested sub menus. * * <div class="special reference"> * <h3>Developer Guides</h3> * <p>For information about creating menus, read the * <a href="{@docRoot}guide/topics/ui/menus.html">Menus</a> developer guide.</p> * </div> */ public interface SubMenu extends Menu { /** * Sets the submenu header's title to the title given in <var>titleRes</var> * resource identifier. * * @param titleRes The string resource identifier used for the title. * @return This SubMenu so additional setters can be called. */ public SubMenu setHeaderTitle(int titleRes); /** * Sets the submenu header's title to the title given in <var>title</var>. * * @param title The character sequence used for the title. * @return This SubMenu so additional setters can be called. */ public SubMenu setHeaderTitle(CharSequence title); /** * Sets the submenu header's icon to the icon given in <var>iconRes</var> * resource id. * * @param iconRes The resource identifier used for the icon. * @return This SubMenu so additional setters can be called. */ public SubMenu setHeaderIcon(int iconRes); /** * Sets the submenu header's icon to the icon given in <var>icon</var> * {@link Drawable}. * * @param icon The {@link Drawable} used for the icon. * @return This SubMenu so additional setters can be called. */ public SubMenu setHeaderIcon(Drawable icon); /** * Sets the header of the submenu to the {@link View} given in * <var>view</var>. This replaces the header title and icon (and those * replace this). * * @param view The {@link View} used for the header. * @return This SubMenu so additional setters can be called. */ public SubMenu setHeaderView(View view); /** * Clears the header of the submenu. */ public void clearHeader(); /** * Change the icon associated with this submenu's item in its parent menu. * * @see MenuItem#setIcon(int) * @param iconRes The new icon (as a resource ID) to be displayed. * @return This SubMenu so additional setters can be called. */ public SubMenu setIcon(int iconRes); /** * Change the icon associated with this submenu's item in its parent menu. * * @see MenuItem#setIcon(Drawable) * @param icon The new icon (as a Drawable) to be displayed. * @return This SubMenu so additional setters can be called. */ public SubMenu setIcon(Drawable icon); /** * Gets the {@link MenuItem} that represents this submenu in the parent * menu. Use this for setting additional item attributes. * * @return The {@link MenuItem} that launches the submenu when invoked. */ public MenuItem getItem(); }
Java
/* * 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.view; /** * When a {@link View} implements this interface it will receive callbacks * when expanded or collapsed as an action view alongside the optional, * app-specified callbacks to {@link OnActionExpandListener}. * * <p>See {@link MenuItem} for more information about action views. * See {@link android.app.ActionBar} for more information about the action bar. */ public interface CollapsibleActionView { /** * Called when this view is expanded as an action view. * See {@link MenuItem#expandActionView()}. */ public void onActionViewExpanded(); /** * Called when this view is collapsed as an action view. * See {@link MenuItem#collapseActionView()}. */ public void onActionViewCollapsed(); }
Java
/* * Copyright (C) 2006 The Android Open Source Project * 2011 Jake Wharton * * 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.view; import java.io.IOException; import java.lang.reflect.Constructor; 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; /** * This class is used to instantiate menu XML files into Menu objects. * <p> * For performance reasons, menu inflation relies heavily on pre-processing of * XML files that is done at build time. Therefore, it is not currently possible * to use MenuInflater with an XmlPullParser over a plain XML file at runtime; * it only works with an XmlPullParser returned from a compiled resource (R. * <em>something</em> file.) */ public class MenuInflater { private static final String LOG_TAG = "MenuInflater"; /** Menu tag name in XML. */ private static final String XML_MENU = "menu"; /** Group tag name in XML. */ private static final String XML_GROUP = "group"; /** Item tag name in XML. */ private static final String XML_ITEM = "item"; private static final int NO_ID = 0; private static final Class<?>[] ACTION_VIEW_CONSTRUCTOR_SIGNATURE = new Class[] {Context.class}; private static final Class<?>[] ACTION_PROVIDER_CONSTRUCTOR_SIGNATURE = ACTION_VIEW_CONSTRUCTOR_SIGNATURE; private final Object[] mActionViewConstructorArguments; private final Object[] mActionProviderConstructorArguments; private Context mContext; /** * Constructs a menu inflater. * * @see Activity#getMenuInflater() */ public MenuInflater(Context context) { mContext = context; mActionViewConstructorArguments = new Object[] {context}; mActionProviderConstructorArguments = mActionViewConstructorArguments; } /** * Inflate a menu hierarchy from the specified XML resource. Throws * {@link InflateException} if there is an error. * * @param menuRes Resource ID for an XML layout resource to load (e.g., * <code>R.menu.main_activity</code>) * @param menu The Menu to inflate into. The items and submenus will be * added to this Menu. */ public void inflate(int menuRes, Menu menu) { XmlResourceParser parser = null; try { parser = mContext.getResources().getLayout(menuRes); AttributeSet attrs = Xml.asAttributeSet(parser); parseMenu(parser, attrs, menu); } catch (XmlPullParserException e) { throw new InflateException("Error inflating menu XML", e); } catch (IOException e) { throw new InflateException("Error inflating menu XML", e); } finally { if (parser != null) parser.close(); } } /** * Called internally to fill the given menu. If a sub menu is seen, it will * call this recursively. */ private void parseMenu(XmlPullParser parser, AttributeSet attrs, Menu menu) throws XmlPullParserException, IOException { MenuState menuState = new MenuState(menu); int eventType = parser.getEventType(); String tagName; boolean lookingForEndOfUnknownTag = false; String unknownTagName = null; // This loop will skip to the menu start tag do { if (eventType == XmlPullParser.START_TAG) { tagName = parser.getName(); if (tagName.equals(XML_MENU)) { // Go to next tag eventType = parser.next(); break; } throw new RuntimeException("Expecting menu, got " + tagName); } eventType = parser.next(); } while (eventType != XmlPullParser.END_DOCUMENT); boolean reachedEndOfMenu = false; while (!reachedEndOfMenu) { switch (eventType) { case XmlPullParser.START_TAG: if (lookingForEndOfUnknownTag) { break; } tagName = parser.getName(); if (tagName.equals(XML_GROUP)) { menuState.readGroup(attrs); } else if (tagName.equals(XML_ITEM)) { menuState.readItem(attrs); } else if (tagName.equals(XML_MENU)) { // A menu start tag denotes a submenu for an item SubMenu subMenu = menuState.addSubMenuItem(); // Parse the submenu into returned SubMenu parseMenu(parser, attrs, subMenu); } else { lookingForEndOfUnknownTag = true; unknownTagName = tagName; } break; case XmlPullParser.END_TAG: tagName = parser.getName(); if (lookingForEndOfUnknownTag && tagName.equals(unknownTagName)) { lookingForEndOfUnknownTag = false; unknownTagName = null; } else if (tagName.equals(XML_GROUP)) { menuState.resetGroup(); } else if (tagName.equals(XML_ITEM)) { // Add the item if it hasn't been added (if the item was // a submenu, it would have been added already) if (!menuState.hasAddedItem()) { if (menuState.itemActionProvider != null && menuState.itemActionProvider.hasSubMenu()) { menuState.addSubMenuItem(); } else { menuState.addItem(); } } } else if (tagName.equals(XML_MENU)) { reachedEndOfMenu = true; } break; case XmlPullParser.END_DOCUMENT: throw new RuntimeException("Unexpected end of document"); } eventType = parser.next(); } } private static class InflatedOnMenuItemClickListener implements MenuItem.OnMenuItemClickListener { private static final Class<?>[] PARAM_TYPES = new Class[] { MenuItem.class }; private Context mContext; private Method mMethod; public InflatedOnMenuItemClickListener(Context context, String methodName) { mContext = context; Class<?> c = context.getClass(); try { mMethod = c.getMethod(methodName, PARAM_TYPES); } catch (Exception e) { InflateException ex = new InflateException( "Couldn't resolve menu item onClick handler " + methodName + " in class " + c.getName()); ex.initCause(e); throw ex; } } public boolean onMenuItemClick(MenuItem item) { try { if (mMethod.getReturnType() == Boolean.TYPE) { return (Boolean) mMethod.invoke(mContext, item); } else { mMethod.invoke(mContext, item); return true; } } catch (Exception e) { throw new RuntimeException(e); } } } /** * State for the current menu. * <p> * Groups can not be nested unless there is another menu (which will have * its state class). */ private class MenuState { private Menu menu; /* * Group state is set on items as they are added, allowing an item to * override its group state. (As opposed to set on items at the group end tag.) */ private int groupId; private int groupCategory; private int groupOrder; private int groupCheckable; private boolean groupVisible; private boolean groupEnabled; private boolean itemAdded; private int itemId; private int itemCategoryOrder; private CharSequence itemTitle; private CharSequence itemTitleCondensed; private int itemIconResId; private char itemAlphabeticShortcut; private char itemNumericShortcut; /** * Sync to attrs.xml enum: * - 0: none * - 1: all * - 2: exclusive */ private int itemCheckable; private boolean itemChecked; private boolean itemVisible; private boolean itemEnabled; /** * Sync to attrs.xml enum, values in MenuItem: * - 0: never * - 1: ifRoom * - 2: always * - -1: Safe sentinel for "no value". */ private int itemShowAsAction; private int itemActionViewLayout; private String itemActionViewClassName; private String itemActionProviderClassName; private String itemListenerMethodName; private ActionProvider itemActionProvider; private static final int defaultGroupId = NO_ID; private static final int defaultItemId = NO_ID; private static final int defaultItemCategory = 0; private static final int defaultItemOrder = 0; private static final int defaultItemCheckable = 0; private static final boolean defaultItemChecked = false; private static final boolean defaultItemVisible = true; private static final boolean defaultItemEnabled = true; public MenuState(final Menu menu) { this.menu = menu; resetGroup(); } public void resetGroup() { groupId = defaultGroupId; groupCategory = defaultItemCategory; groupOrder = defaultItemOrder; groupCheckable = defaultItemCheckable; groupVisible = defaultItemVisible; groupEnabled = defaultItemEnabled; } /** * Called when the parser is pointing to a group tag. */ public void readGroup(AttributeSet attrs) { TypedArray a = mContext.obtainStyledAttributes(attrs, R.styleable.SherlockMenuGroup); 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); a.recycle(); } /** * Called when the parser is pointing to an item tag. */ public void readItem(AttributeSet attrs) { TypedArray a = mContext.obtainStyledAttributes(attrs, R.styleable.SherlockMenuItem); // Inherit attributes from the group as default value 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.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(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(R.styleable.SherlockMenuItem_android_checked, defaultItemChecked); itemVisible = a.getBoolean(R.styleable.SherlockMenuItem_android_visible, groupVisible); itemEnabled = a.getBoolean(R.styleable.SherlockMenuItem_android_enabled, groupEnabled); TypedValue value = new TypedValue(); a.getValue(R.styleable.SherlockMenuItem_android_showAsAction, value); itemShowAsAction = value.type == TypedValue.TYPE_INT_HEX ? value.data : -1; 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) { itemActionProvider = newInstance(itemActionProviderClassName, ACTION_PROVIDER_CONSTRUCTOR_SIGNATURE, mActionProviderConstructorArguments); } else { if (hasActionProvider) { Log.w(LOG_TAG, "Ignoring attribute 'actionProviderClass'." + " Action view already specified."); } itemActionProvider = null; } a.recycle(); itemAdded = false; } private char getShortcut(String shortcutString) { if (shortcutString == null) { return 0; } else { return shortcutString.charAt(0); } } private void setItem(MenuItem item) { item.setChecked(itemChecked) .setVisible(itemVisible) .setEnabled(itemEnabled) .setCheckable(itemCheckable >= 1) .setTitleCondensed(itemTitleCondensed) .setIcon(itemIconResId) .setAlphabeticShortcut(itemAlphabeticShortcut) .setNumericShortcut(itemNumericShortcut); if (itemShowAsAction >= 0) { item.setShowAsAction(itemShowAsAction); } if (itemListenerMethodName != null) { if (mContext.isRestricted()) { throw new IllegalStateException("The android:onClick attribute cannot " + "be used within a restricted context"); } item.setOnMenuItemClickListener( new InflatedOnMenuItemClickListener(mContext, itemListenerMethodName)); } if (itemCheckable >= 2) { if (item instanceof MenuItemImpl) { MenuItemImpl impl = (MenuItemImpl) item; impl.setExclusiveCheckable(true); } else { menu.setGroupCheckable(groupId, true, true); } } boolean actionViewSpecified = false; if (itemActionViewClassName != null) { View actionView = (View) newInstance(itemActionViewClassName, ACTION_VIEW_CONSTRUCTOR_SIGNATURE, mActionViewConstructorArguments); item.setActionView(actionView); actionViewSpecified = true; } if (itemActionViewLayout > 0) { if (!actionViewSpecified) { item.setActionView(itemActionViewLayout); actionViewSpecified = true; } else { Log.w(LOG_TAG, "Ignoring attribute 'itemActionViewLayout'." + " Action view already specified."); } } if (itemActionProvider != null) { item.setActionProvider(itemActionProvider); } } public void addItem() { itemAdded = true; setItem(menu.add(groupId, itemId, itemCategoryOrder, itemTitle)); } public SubMenu addSubMenuItem() { itemAdded = true; SubMenu subMenu = menu.addSubMenu(groupId, itemId, itemCategoryOrder, itemTitle); setItem(subMenu.getItem()); return subMenu; } public boolean hasAddedItem() { return itemAdded; } @SuppressWarnings("unchecked") private <T> T newInstance(String className, Class<?>[] constructorSignature, Object[] arguments) { try { Class<?> clazz = mContext.getClassLoader().loadClass(className); Constructor<?> constructor = clazz.getConstructor(constructorSignature); return (T) constructor.newInstance(arguments); } catch (Exception e) { Log.w(LOG_TAG, "Cannot instantiate class: " + className, e); } return null; } } }
Java
/* * 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.view; import android.content.Context; import android.view.View; /** * This class is a mediator for accomplishing a given task, for example sharing a file. * It is responsible for creating a view that performs an action that accomplishes the task. * This class also implements other functions such a performing a default action. * <p> * An ActionProvider can be optionally specified for a {@link MenuItem} and in such a * case it will be responsible for creating the action view that appears in the * {@link android.app.ActionBar} as a substitute for the menu item when the item is * displayed as an action item. Also the provider is responsible for performing a * default action if a menu item placed on the overflow menu of the ActionBar is * selected and none of the menu item callbacks has handled the selection. For this * case the provider can also optionally provide a sub-menu for accomplishing the * task at hand. * </p> * <p> * There are two ways for using an action provider for creating and handling of action views: * <ul> * <li> * Setting the action provider on a {@link MenuItem} directly by calling * {@link MenuItem#setActionProvider(ActionProvider)}. * </li> * <li> * Declaring the action provider in the menu XML resource. For example: * <pre> * <code> * &lt;item android:id="@+id/my_menu_item" * android:title="Title" * android:icon="@drawable/my_menu_item_icon" * android:showAsAction="ifRoom" * android:actionProviderClass="foo.bar.SomeActionProvider" /&gt; * </code> * </pre> * </li> * </ul> * </p> * * @see MenuItem#setActionProvider(ActionProvider) * @see MenuItem#getActionProvider() */ public abstract class ActionProvider { private SubUiVisibilityListener mSubUiVisibilityListener; /** * Creates a new instance. * * @param context Context for accessing resources. */ public ActionProvider(Context context) { } /** * Factory method for creating new action views. * * @return A new action view. */ public abstract View onCreateActionView(); /** * Performs an optional default action. * <p> * For the case of an action provider placed in a menu item not shown as an action this * method is invoked if previous callbacks for processing menu selection has handled * the event. * </p> * <p> * A menu item selection is processed in the following order: * <ul> * <li> * Receiving a call to {@link MenuItem.OnMenuItemClickListener#onMenuItemClick * MenuItem.OnMenuItemClickListener.onMenuItemClick}. * </li> * <li> * Receiving a call to {@link android.app.Activity#onOptionsItemSelected(MenuItem) * Activity.onOptionsItemSelected(MenuItem)} * </li> * <li> * Receiving a call to {@link android.app.Fragment#onOptionsItemSelected(MenuItem) * Fragment.onOptionsItemSelected(MenuItem)} * </li> * <li> * Launching the {@link android.content.Intent} set via * {@link MenuItem#setIntent(android.content.Intent) MenuItem.setIntent(android.content.Intent)} * </li> * <li> * Invoking this method. * </li> * </ul> * </p> * <p> * The default implementation does not perform any action and returns false. * </p> */ public boolean onPerformDefaultAction() { return false; } /** * Determines if this ActionProvider has a submenu associated with it. * * <p>Associated submenus will be shown when an action view is not. This * provider instance will receive a call to {@link #onPrepareSubMenu(SubMenu)} * after the call to {@link #onPerformDefaultAction()} and before a submenu is * displayed to the user. * * @return true if the item backed by this provider should have an associated submenu */ public boolean hasSubMenu() { return false; } /** * Called to prepare an associated submenu for the menu item backed by this ActionProvider. * * <p>if {@link #hasSubMenu()} returns true, this method will be called when the * menu item is selected to prepare the submenu for presentation to the user. Apps * may use this to create or alter submenu content right before display. * * @param subMenu Submenu that will be displayed */ public void onPrepareSubMenu(SubMenu subMenu) { } /** * Notify the system that the visibility of an action view's sub-UI such as * an anchored popup has changed. This will affect how other system * visibility notifications occur. * * @hide Pending future API approval */ public void subUiVisibilityChanged(boolean isVisible) { if (mSubUiVisibilityListener != null) { mSubUiVisibilityListener.onSubUiVisibilityChanged(isVisible); } } /** * @hide Internal use only */ public void setSubUiVisibilityListener(SubUiVisibilityListener listener) { mSubUiVisibilityListener = listener; } /** * @hide Internal use only */ public interface SubUiVisibilityListener { public void onSubUiVisibilityChanged(boolean isVisible); } }
Java
/* * Copyright (C) 2006 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.actionbarsherlock.view; import android.content.ComponentName; import android.content.Intent; import android.view.KeyEvent; /** * Interface for managing the items in a menu. * <p> * By default, every Activity supports an options menu of actions or options. * You can add items to this menu and handle clicks on your additions. The * easiest way of adding menu items is inflating an XML file into the * {@link Menu} via {@link MenuInflater}. The easiest way of attaching code to * clicks is via {@link Activity#onOptionsItemSelected(MenuItem)} and * {@link Activity#onContextItemSelected(MenuItem)}. * <p> * Different menu types support different features: * <ol> * <li><b>Context menus</b>: Do not support item shortcuts and item icons. * <li><b>Options menus</b>: The <b>icon menus</b> do not support item check * marks and only show the item's * {@link MenuItem#setTitleCondensed(CharSequence) condensed title}. The * <b>expanded menus</b> (only available if six or more menu items are visible, * reached via the 'More' item in the icon menu) do not show item icons, and * item check marks are discouraged. * <li><b>Sub menus</b>: Do not support item icons, or nested sub menus. * </ol> * * <div class="special reference"> * <h3>Developer Guides</h3> * <p>For more information about creating menus, read the * <a href="{@docRoot}guide/topics/ui/menus.html">Menus</a> developer guide.</p> * </div> */ public interface Menu { /** * This is the part of an order integer that the user can provide. * @hide */ static final int USER_MASK = 0x0000ffff; /** * Bit shift of the user portion of the order integer. * @hide */ static final int USER_SHIFT = 0; /** * This is the part of an order integer that supplies the category of the * item. * @hide */ static final int CATEGORY_MASK = 0xffff0000; /** * Bit shift of the category portion of the order integer. * @hide */ static final int CATEGORY_SHIFT = 16; /** * Value to use for group and item identifier integers when you don't care * about them. */ static final int NONE = 0; /** * First value for group and item identifier integers. */ static final int FIRST = 1; // Implementation note: Keep these CATEGORY_* in sync with the category enum // in attrs.xml /** * Category code for the order integer for items/groups that are part of a * container -- or/add this with your base value. */ static final int CATEGORY_CONTAINER = 0x00010000; /** * Category code for the order integer for items/groups that are provided by * the system -- or/add this with your base value. */ static final int CATEGORY_SYSTEM = 0x00020000; /** * Category code for the order integer for items/groups that are * user-supplied secondary (infrequently used) options -- or/add this with * your base value. */ static final int CATEGORY_SECONDARY = 0x00030000; /** * Category code for the order integer for items/groups that are * alternative actions on the data that is currently displayed -- or/add * this with your base value. */ static final int CATEGORY_ALTERNATIVE = 0x00040000; /** * Flag for {@link #addIntentOptions}: if set, do not automatically remove * any existing menu items in the same group. */ static final int FLAG_APPEND_TO_GROUP = 0x0001; /** * Flag for {@link #performShortcut}: if set, do not close the menu after * executing the shortcut. */ static final int FLAG_PERFORM_NO_CLOSE = 0x0001; /** * Flag for {@link #performShortcut(int, KeyEvent, int)}: if set, always * close the menu after executing the shortcut. Closing the menu also resets * the prepared state. */ static final int FLAG_ALWAYS_PERFORM_CLOSE = 0x0002; /** * Add a new item to the menu. This item displays the given title for its * label. * * @param title The text to display for the item. * @return The newly added menu item. */ public MenuItem add(CharSequence title); /** * Add a new item to the menu. This item displays the given title for its * label. * * @param titleRes Resource identifier of title string. * @return The newly added menu item. */ public MenuItem add(int titleRes); /** * Add a new item to the menu. This item displays the given title for its * label. * * @param groupId The group identifier that this item should be part of. * This can be used to define groups of items for batch state * changes. Normally use {@link #NONE} if an item should not be in a * group. * @param itemId Unique item ID. Use {@link #NONE} if you do not need a * unique ID. * @param order The order for the item. Use {@link #NONE} if you do not care * about the order. See {@link MenuItem#getOrder()}. * @param title The text to display for the item. * @return The newly added menu item. */ public MenuItem add(int groupId, int itemId, int order, CharSequence title); /** * Variation on {@link #add(int, int, int, CharSequence)} that takes a * string resource identifier instead of the string itself. * * @param groupId The group identifier that this item should be part of. * This can also be used to define groups of items for batch state * changes. Normally use {@link #NONE} if an item should not be in a * group. * @param itemId Unique item ID. Use {@link #NONE} if you do not need a * unique ID. * @param order The order for the item. Use {@link #NONE} if you do not care * about the order. See {@link MenuItem#getOrder()}. * @param titleRes Resource identifier of title string. * @return The newly added menu item. */ public MenuItem add(int groupId, int itemId, int order, int titleRes); /** * Add a new sub-menu to the menu. This item displays the given title for * its label. To modify other attributes on the submenu's menu item, use * {@link SubMenu#getItem()}. * * @param title The text to display for the item. * @return The newly added sub-menu */ SubMenu addSubMenu(final CharSequence title); /** * Add a new sub-menu to the menu. This item displays the given title for * its label. To modify other attributes on the submenu's menu item, use * {@link SubMenu#getItem()}. * * @param titleRes Resource identifier of title string. * @return The newly added sub-menu */ SubMenu addSubMenu(final int titleRes); /** * Add a new sub-menu to the menu. This item displays the given * <var>title</var> for its label. To modify other attributes on the * submenu's menu item, use {@link SubMenu#getItem()}. *<p> * Note that you can only have one level of sub-menus, i.e. you cannnot add * a subMenu to a subMenu: An {@link UnsupportedOperationException} will be * thrown if you try. * * @param groupId The group identifier that this item should be part of. * This can also be used to define groups of items for batch state * changes. Normally use {@link #NONE} if an item should not be in a * group. * @param itemId Unique item ID. Use {@link #NONE} if you do not need a * unique ID. * @param order The order for the item. Use {@link #NONE} if you do not care * about the order. See {@link MenuItem#getOrder()}. * @param title The text to display for the item. * @return The newly added sub-menu */ SubMenu addSubMenu(final int groupId, final int itemId, int order, final CharSequence title); /** * Variation on {@link #addSubMenu(int, int, int, CharSequence)} that takes * a string resource identifier for the title instead of the string itself. * * @param groupId The group identifier that this item should be part of. * This can also be used to define groups of items for batch state * changes. Normally use {@link #NONE} if an item should not be in a group. * @param itemId Unique item ID. Use {@link #NONE} if you do not need a unique ID. * @param order The order for the item. Use {@link #NONE} if you do not care about the * order. See {@link MenuItem#getOrder()}. * @param titleRes Resource identifier of title string. * @return The newly added sub-menu */ SubMenu addSubMenu(int groupId, int itemId, int order, int titleRes); /** * Add a group of menu items corresponding to actions that can be performed * for a particular Intent. The Intent is most often configured with a null * action, the data that the current activity is working with, and includes * either the {@link Intent#CATEGORY_ALTERNATIVE} or * {@link Intent#CATEGORY_SELECTED_ALTERNATIVE} to find activities that have * said they would like to be included as optional action. You can, however, * use any Intent you want. * * <p> * See {@link android.content.pm.PackageManager#queryIntentActivityOptions} * for more * details on the <var>caller</var>, <var>specifics</var>, and * <var>intent</var> arguments. The list returned by that function is used * to populate the resulting menu items. * * <p> * All of the menu items of possible options for the intent will be added * with the given group and id. You can use the group to control ordering of * the items in relation to other items in the menu. Normally this function * will automatically remove any existing items in the menu in the same * group and place a divider above and below the added items; this behavior * can be modified with the <var>flags</var> parameter. For each of the * generated items {@link MenuItem#setIntent} is called to associate the * appropriate Intent with the item; this means the activity will * automatically be started for you without having to do anything else. * * @param groupId The group identifier that the items should be part of. * This can also be used to define groups of items for batch state * changes. Normally use {@link #NONE} if the items should not be in * a group. * @param itemId Unique item ID. Use {@link #NONE} if you do not need a * unique ID. * @param order The order for the items. Use {@link #NONE} if you do not * care about the order. See {@link MenuItem#getOrder()}. * @param caller The current activity component name as defined by * queryIntentActivityOptions(). * @param specifics Specific items to place first as defined by * queryIntentActivityOptions(). * @param intent Intent describing the kinds of items to populate in the * list as defined by queryIntentActivityOptions(). * @param flags Additional options controlling how the items are added. * @param outSpecificItems Optional array in which to place the menu items * that were generated for each of the <var>specifics</var> that were * requested. Entries may be null if no activity was found for that * specific action. * @return The number of menu items that were added. * * @see #FLAG_APPEND_TO_GROUP * @see MenuItem#setIntent * @see android.content.pm.PackageManager#queryIntentActivityOptions */ public int addIntentOptions(int groupId, int itemId, int order, ComponentName caller, Intent[] specifics, Intent intent, int flags, MenuItem[] outSpecificItems); /** * Remove the item with the given identifier. * * @param id The item to be removed. If there is no item with this * identifier, nothing happens. */ public void removeItem(int id); /** * Remove all items in the given group. * * @param groupId The group to be removed. If there are no items in this * group, nothing happens. */ public void removeGroup(int groupId); /** * Remove all existing items from the menu, leaving it empty as if it had * just been created. */ public void clear(); /** * Control whether a particular group of items can show a check mark. This * is similar to calling {@link MenuItem#setCheckable} on all of the menu items * with the given group identifier, but in addition you can control whether * this group contains a mutually-exclusive set items. This should be called * after the items of the group have been added to the menu. * * @param group The group of items to operate on. * @param checkable Set to true to allow a check mark, false to * disallow. The default is false. * @param exclusive If set to true, only one item in this group can be * checked at a time; checking an item will automatically * uncheck all others in the group. If set to false, each * item can be checked independently of the others. * * @see MenuItem#setCheckable * @see MenuItem#setChecked */ public void setGroupCheckable(int group, boolean checkable, boolean exclusive); /** * Show or hide all menu items that are in the given group. * * @param group The group of items to operate on. * @param visible If true the items are visible, else they are hidden. * * @see MenuItem#setVisible */ public void setGroupVisible(int group, boolean visible); /** * Enable or disable all menu items that are in the given group. * * @param group The group of items to operate on. * @param enabled If true the items will be enabled, else they will be disabled. * * @see MenuItem#setEnabled */ public void setGroupEnabled(int group, boolean enabled); /** * Return whether the menu currently has item items that are visible. * * @return True if there is one or more item visible, * else false. */ public boolean hasVisibleItems(); /** * Return the menu item with a particular identifier. * * @param id The identifier to find. * * @return The menu item object, or null if there is no item with * this identifier. */ public MenuItem findItem(int id); /** * Get the number of items in the menu. Note that this will change any * times items are added or removed from the menu. * * @return The item count. */ public int size(); /** * Gets the menu item at the given index. * * @param index The index of the menu item to return. * @return The menu item. * @exception IndexOutOfBoundsException * when {@code index < 0 || >= size()} */ public MenuItem getItem(int index); /** * Closes the menu, if open. */ public void close(); /** * Execute the menu item action associated with the given shortcut * character. * * @param keyCode The keycode of the shortcut key. * @param event Key event message. * @param flags Additional option flags or 0. * * @return If the given shortcut exists and is shown, returns * true; else returns false. * * @see #FLAG_PERFORM_NO_CLOSE */ public boolean performShortcut(int keyCode, KeyEvent event, int flags); /** * Is a keypress one of the defined shortcut keys for this window. * @param keyCode the key code from {@link KeyEvent} to check. * @param event the {@link KeyEvent} to use to help check. */ boolean isShortcutKey(int keyCode, KeyEvent event); /** * Execute the menu item action associated with the given menu identifier. * * @param id Identifier associated with the menu item. * @param flags Additional option flags or 0. * * @return If the given identifier exists and is shown, returns * true; else returns false. * * @see #FLAG_PERFORM_NO_CLOSE */ public boolean performIdentifierAction(int id, int flags); /** * Control whether the menu should be running in qwerty mode (alphabetic * shortcuts) or 12-key mode (numeric shortcuts). * * @param isQwerty If true the menu will use alphabetic shortcuts; else it * will use numeric shortcuts. */ public void setQwertyMode(boolean isQwerty); }
Java
/* * Copyright (C) 2010 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.view; import android.view.View; /** * Represents a contextual mode of the user interface. Action modes can be used for * modal interactions with content and replace parts of the normal UI until finished. * Examples of good action modes include selection modes, search, content editing, etc. */ public abstract class ActionMode { private Object mTag; /** * Set a tag object associated with this ActionMode. * * <p>Like the tag available to views, this allows applications to associate arbitrary * data with an ActionMode for later reference. * * @param tag Tag to associate with this ActionMode * * @see #getTag() */ public void setTag(Object tag) { mTag = tag; } /** * Retrieve the tag object associated with this ActionMode. * * <p>Like the tag available to views, this allows applications to associate arbitrary * data with an ActionMode for later reference. * * @return Tag associated with this ActionMode * * @see #setTag(Object) */ public Object getTag() { return mTag; } /** * Set the title of the action mode. This method will have no visible effect if * a custom view has been set. * * @param title Title string to set * * @see #setTitle(int) * @see #setCustomView(View) */ public abstract void setTitle(CharSequence title); /** * Set the title of the action mode. This method will have no visible effect if * a custom view has been set. * * @param resId Resource ID of a string to set as the title * * @see #setTitle(CharSequence) * @see #setCustomView(View) */ public abstract void setTitle(int resId); /** * Set the subtitle of the action mode. This method will have no visible effect if * a custom view has been set. * * @param subtitle Subtitle string to set * * @see #setSubtitle(int) * @see #setCustomView(View) */ public abstract void setSubtitle(CharSequence subtitle); /** * Set the subtitle of the action mode. This method will have no visible effect if * a custom view has been set. * * @param resId Resource ID of a string to set as the subtitle * * @see #setSubtitle(CharSequence) * @see #setCustomView(View) */ public abstract void setSubtitle(int resId); /** * Set a custom view for this action mode. The custom view will take the place of * the title and subtitle. Useful for things like search boxes. * * @param view Custom view to use in place of the title/subtitle. * * @see #setTitle(CharSequence) * @see #setSubtitle(CharSequence) */ public abstract void setCustomView(View view); /** * Invalidate the action mode and refresh menu content. The mode's * {@link ActionMode.Callback} will have its * {@link Callback#onPrepareActionMode(ActionMode, Menu)} method called. * If it returns true the menu will be scanned for updated content and any relevant changes * will be reflected to the user. */ public abstract void invalidate(); /** * Finish and close this action mode. The action mode's {@link ActionMode.Callback} will * have its {@link Callback#onDestroyActionMode(ActionMode)} method called. */ public abstract void finish(); /** * Returns the menu of actions that this action mode presents. * @return The action mode's menu. */ public abstract Menu getMenu(); /** * Returns the current title of this action mode. * @return Title text */ public abstract CharSequence getTitle(); /** * Returns the current subtitle of this action mode. * @return Subtitle text */ public abstract CharSequence getSubtitle(); /** * Returns the current custom view for this action mode. * @return The current custom view */ public abstract View getCustomView(); /** * Returns a {@link MenuInflater} with the ActionMode's context. */ public abstract MenuInflater getMenuInflater(); /** * Returns whether the UI presenting this action mode can take focus or not. * This is used by internal components within the framework that would otherwise * present an action mode UI that requires focus, such as an EditText as a custom view. * * @return true if the UI used to show this action mode can take focus * @hide Internal use only */ public boolean isUiFocusable() { return true; } /** * Callback interface for action modes. Supplied to * {@link View#startActionMode(Callback)}, a Callback * configures and handles events raised by a user's interaction with an action mode. * * <p>An action mode's lifecycle is as follows: * <ul> * <li>{@link Callback#onCreateActionMode(ActionMode, Menu)} once on initial * creation</li> * <li>{@link Callback#onPrepareActionMode(ActionMode, Menu)} after creation * and any time the {@link ActionMode} is invalidated</li> * <li>{@link Callback#onActionItemClicked(ActionMode, MenuItem)} any time a * contextual action button is clicked</li> * <li>{@link Callback#onDestroyActionMode(ActionMode)} when the action mode * is closed</li> * </ul> */ public interface Callback { /** * Called when action mode is first created. The menu supplied will be used to * generate action buttons for the action mode. * * @param mode ActionMode being created * @param menu Menu used to populate action buttons * @return true if the action mode should be created, false if entering this * mode should be aborted. */ public boolean onCreateActionMode(ActionMode mode, Menu menu); /** * Called to refresh an action mode's action menu whenever it is invalidated. * * @param mode ActionMode being prepared * @param menu Menu used to populate action buttons * @return true if the menu or action mode was updated, false otherwise. */ public boolean onPrepareActionMode(ActionMode mode, Menu menu); /** * Called to report a user click on an action button. * * @param mode The current ActionMode * @param item The item that was clicked * @return true if this callback handled the event, false if the standard MenuItem * invocation should continue. */ public boolean onActionItemClicked(ActionMode mode, MenuItem item); /** * Called when an action mode is about to be exited and destroyed. * * @param mode The current ActionMode being destroyed */ public void onDestroyActionMode(ActionMode mode); } }
Java
/* * Copyright (C) 2008 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.view; import android.content.Intent; import android.graphics.drawable.Drawable; import android.view.ContextMenu.ContextMenuInfo; import android.view.View; /** * Interface for direct access to a previously created menu item. * <p> * An Item is returned by calling one of the {@link android.view.Menu#add} * methods. * <p> * For a feature set of specific menu types, see {@link Menu}. * * <div class="special reference"> * <h3>Developer Guides</h3> * <p>For information about creating menus, read the * <a href="{@docRoot}guide/topics/ui/menus.html">Menus</a> developer guide.</p> * </div> */ 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 = 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 = 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 = 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 = 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 = android.view.MenuItem.SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW; /** * Interface definition for a callback to be invoked when a menu item is * clicked. * * @see Activity#onContextItemSelected(MenuItem) * @see Activity#onOptionsItemSelected(MenuItem) */ public interface OnMenuItemClickListener { /** * Called when a menu item has been invoked. This is the first code * that is executed; if it returns true, no other callbacks will be * executed. * * @param item The menu item that was invoked. * * @return Return true to consume this click and prevent others from * executing. */ public boolean onMenuItemClick(MenuItem item); } /** * Interface definition for a callback to be invoked when a menu item * marked with {@link MenuItem#SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW} is * expanded or collapsed. * * @see MenuItem#expandActionView() * @see MenuItem#collapseActionView() * @see MenuItem#setShowAsActionFlags(int) */ public interface OnActionExpandListener { /** * Called when a menu item with {@link MenuItem#SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW} * is expanded. * @param item Item that was expanded * @return true if the item should expand, false if expansion should be suppressed. */ public boolean onMenuItemActionExpand(MenuItem item); /** * Called when a menu item with {@link MenuItem#SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW} * is collapsed. * @param item Item that was collapsed * @return true if the item should collapse, false if collapsing should be suppressed. */ public boolean onMenuItemActionCollapse(MenuItem item); } /** * Return the identifier for this menu item. The identifier can not * be changed after the menu is created. * * @return The menu item's identifier. */ public int getItemId(); /** * Return the group identifier that this menu item is part of. The group * identifier can not be changed after the menu is created. * * @return The menu item's group identifier. */ public int getGroupId(); /** * Return the category and order within the category of this item. This * item will be shown before all items (within its category) that have * order greater than this value. * <p> * An order integer contains the item's category (the upper bits of the * integer; set by or/add the category with the order within the * category) and the ordering of the item within that category (the * lower bits). Example categories are {@link Menu#CATEGORY_SYSTEM}, * {@link Menu#CATEGORY_SECONDARY}, {@link Menu#CATEGORY_ALTERNATIVE}, * {@link Menu#CATEGORY_CONTAINER}. See {@link Menu} for a full list. * * @return The order of this item. */ public int getOrder(); /** * Change the title associated with this item. * * @param title The new text to be displayed. * @return This Item so additional setters can be called. */ public MenuItem setTitle(CharSequence title); /** * Change the title associated with this item. * <p> * Some menu types do not sufficient space to show the full title, and * instead a condensed title is preferred. See {@link Menu} for more * information. * * @param title The resource id of the new text to be displayed. * @return This Item so additional setters can be called. * @see #setTitleCondensed(CharSequence) */ public MenuItem setTitle(int title); /** * Retrieve the current title of the item. * * @return The title. */ public CharSequence getTitle(); /** * Change the condensed title associated with this item. The condensed * title is used in situations where the normal title may be too long to * be displayed. * * @param title The new text to be displayed as the condensed title. * @return This Item so additional setters can be called. */ public MenuItem setTitleCondensed(CharSequence title); /** * Retrieve the current condensed title of the item. If a condensed * title was never set, it will return the normal title. * * @return The condensed title, if it exists. * Otherwise the normal title. */ public CharSequence getTitleCondensed(); /** * Change the icon associated with this item. This icon will not always be * shown, so the title should be sufficient in describing this item. See * {@link Menu} for the menu types that support icons. * * @param icon The new icon (as a Drawable) to be displayed. * @return This Item so additional setters can be called. */ public MenuItem setIcon(Drawable icon); /** * Change the icon associated with this item. This icon will not always be * shown, so the title should be sufficient in describing this item. See * {@link Menu} for the menu types that support icons. * <p> * This method will set the resource ID of the icon which will be used to * lazily get the Drawable when this item is being shown. * * @param iconRes The new icon (as a resource ID) to be displayed. * @return This Item so additional setters can be called. */ public MenuItem setIcon(int iconRes); /** * Returns the icon for this item as a Drawable (getting it from resources if it hasn't been * loaded before). * * @return The icon as a Drawable. */ public Drawable getIcon(); /** * Change the Intent associated with this item. By default there is no * Intent associated with a menu item. If you set one, and nothing * else handles the item, then the default behavior will be to call * {@link android.content.Context#startActivity} with the given Intent. * * <p>Note that setIntent() can not be used with the versions of * {@link Menu#add} that take a Runnable, because {@link Runnable#run} * does not return a value so there is no way to tell if it handled the * item. In this case it is assumed that the Runnable always handles * the item, and the intent will never be started. * * @see #getIntent * @param intent The Intent to associated with the item. This Intent * object is <em>not</em> copied, so be careful not to * modify it later. * @return This Item so additional setters can be called. */ public MenuItem setIntent(Intent intent); /** * Return the Intent associated with this item. This returns a * reference to the Intent which you can change as desired to modify * what the Item is holding. * * @see #setIntent * @return Returns the last value supplied to {@link #setIntent}, or * null. */ public Intent getIntent(); /** * Change both the numeric and alphabetic shortcut associated with this * item. Note that the shortcut will be triggered when the key that * generates the given character is pressed alone or along with with the alt * key. Also note that case is not significant and that alphabetic shortcut * characters will be displayed in lower case. * <p> * See {@link Menu} for the menu types that support shortcuts. * * @param numericChar The numeric shortcut key. This is the shortcut when * using a numeric (e.g., 12-key) keyboard. * @param alphaChar The alphabetic shortcut key. This is the shortcut when * using a keyboard with alphabetic keys. * @return This Item so additional setters can be called. */ public MenuItem setShortcut(char numericChar, char alphaChar); /** * Change the numeric shortcut associated with this item. * <p> * See {@link Menu} for the menu types that support shortcuts. * * @param numericChar The numeric shortcut key. This is the shortcut when * using a 12-key (numeric) keyboard. * @return This Item so additional setters can be called. */ public MenuItem setNumericShortcut(char numericChar); /** * Return the char for this menu item's numeric (12-key) shortcut. * * @return Numeric character to use as a shortcut. */ public char getNumericShortcut(); /** * Change the alphabetic shortcut associated with this item. The shortcut * will be triggered when the key that generates the given character is * pressed alone or along with with the alt key. Case is not significant and * shortcut characters will be displayed in lower case. Note that menu items * with the characters '\b' or '\n' as shortcuts will get triggered by the * Delete key or Carriage Return key, respectively. * <p> * See {@link Menu} for the menu types that support shortcuts. * * @param alphaChar The alphabetic shortcut key. This is the shortcut when * using a keyboard with alphabetic keys. * @return This Item so additional setters can be called. */ public MenuItem setAlphabeticShortcut(char alphaChar); /** * Return the char for this menu item's alphabetic shortcut. * * @return Alphabetic character to use as a shortcut. */ public char getAlphabeticShortcut(); /** * Control whether this item can display a check mark. Setting this does * not actually display a check mark (see {@link #setChecked} for that); * rather, it ensures there is room in the item in which to display a * check mark. * <p> * See {@link Menu} for the menu types that support check marks. * * @param checkable Set to true to allow a check mark, false to * disallow. The default is false. * @see #setChecked * @see #isCheckable * @see Menu#setGroupCheckable * @return This Item so additional setters can be called. */ public MenuItem setCheckable(boolean checkable); /** * Return whether the item can currently display a check mark. * * @return If a check mark can be displayed, returns true. * * @see #setCheckable */ public boolean isCheckable(); /** * Control whether this item is shown with a check mark. Note that you * must first have enabled checking with {@link #setCheckable} or else * the check mark will not appear. If this item is a member of a group that contains * mutually-exclusive items (set via {@link Menu#setGroupCheckable(int, boolean, boolean)}, * the other items in the group will be unchecked. * <p> * See {@link Menu} for the menu types that support check marks. * * @see #setCheckable * @see #isChecked * @see Menu#setGroupCheckable * @param checked Set to true to display a check mark, false to hide * it. The default value is false. * @return This Item so additional setters can be called. */ public MenuItem setChecked(boolean checked); /** * Return whether the item is currently displaying a check mark. * * @return If a check mark is displayed, returns true. * * @see #setChecked */ public boolean isChecked(); /** * Sets the visibility of the menu item. Even if a menu item is not visible, * it may still be invoked via its shortcut (to completely disable an item, * set it to invisible and {@link #setEnabled(boolean) disabled}). * * @param visible If true then the item will be visible; if false it is * hidden. * @return This Item so additional setters can be called. */ public MenuItem setVisible(boolean visible); /** * Return the visibility of the menu item. * * @return If true the item is visible; else it is hidden. */ public boolean isVisible(); /** * Sets whether the menu item is enabled. Disabling a menu item will not * allow it to be invoked via its shortcut. The menu item will still be * visible. * * @param enabled If true then the item will be invokable; if false it is * won't be invokable. * @return This Item so additional setters can be called. */ public MenuItem setEnabled(boolean enabled); /** * Return the enabled state of the menu item. * * @return If true the item is enabled and hence invokable; else it is not. */ public boolean isEnabled(); /** * Check whether this item has an associated sub-menu. I.e. it is a * sub-menu of another menu. * * @return If true this item has a menu; else it is a * normal item. */ public boolean hasSubMenu(); /** * Get the sub-menu to be invoked when this item is selected, if it has * one. See {@link #hasSubMenu()}. * * @return The associated menu if there is one, else null */ public SubMenu getSubMenu(); /** * Set a custom listener for invocation of this menu item. In most * situations, it is more efficient and easier to use * {@link Activity#onOptionsItemSelected(MenuItem)} or * {@link Activity#onContextItemSelected(MenuItem)}. * * @param menuItemClickListener The object to receive invokations. * @return This Item so additional setters can be called. * @see Activity#onOptionsItemSelected(MenuItem) * @see Activity#onContextItemSelected(MenuItem) */ public MenuItem setOnMenuItemClickListener(MenuItem.OnMenuItemClickListener menuItemClickListener); /** * Gets the extra information linked to this menu item. This extra * information is set by the View that added this menu item to the * menu. * * @see OnCreateContextMenuListener * @return The extra information linked to the View that added this * menu item to the menu. This can be null. */ public ContextMenuInfo getMenuInfo(); /** * Sets how this item should display in the presence of an Action Bar. * The parameter actionEnum is a flag set. One of {@link #SHOW_AS_ACTION_ALWAYS}, * {@link #SHOW_AS_ACTION_IF_ROOM}, or {@link #SHOW_AS_ACTION_NEVER} should * be used, and you may optionally OR the value with {@link #SHOW_AS_ACTION_WITH_TEXT}. * SHOW_AS_ACTION_WITH_TEXT requests that when the item is shown as an action, * it should be shown with a text label. * * @param actionEnum How the item should display. One of * {@link #SHOW_AS_ACTION_ALWAYS}, {@link #SHOW_AS_ACTION_IF_ROOM}, or * {@link #SHOW_AS_ACTION_NEVER}. SHOW_AS_ACTION_NEVER is the default. * * @see android.app.ActionBar * @see #setActionView(View) */ public void setShowAsAction(int actionEnum); /** * Sets how this item should display in the presence of an Action Bar. * The parameter actionEnum is a flag set. One of {@link #SHOW_AS_ACTION_ALWAYS}, * {@link #SHOW_AS_ACTION_IF_ROOM}, or {@link #SHOW_AS_ACTION_NEVER} should * be used, and you may optionally OR the value with {@link #SHOW_AS_ACTION_WITH_TEXT}. * SHOW_AS_ACTION_WITH_TEXT requests that when the item is shown as an action, * it should be shown with a text label. * * <p>Note: This method differs from {@link #setShowAsAction(int)} only in that it * returns the current MenuItem instance for call chaining. * * @param actionEnum How the item should display. One of * {@link #SHOW_AS_ACTION_ALWAYS}, {@link #SHOW_AS_ACTION_IF_ROOM}, or * {@link #SHOW_AS_ACTION_NEVER}. SHOW_AS_ACTION_NEVER is the default. * * @see android.app.ActionBar * @see #setActionView(View) * @return This MenuItem instance for call chaining. */ public MenuItem setShowAsActionFlags(int actionEnum); /** * Set an action view for this menu item. An action view will be displayed in place * of an automatically generated menu item element in the UI when this item is shown * as an action within a parent. * <p> * <strong>Note:</strong> Setting an action view overrides the action provider * set via {@link #setActionProvider(ActionProvider)}. * </p> * * @param view View to use for presenting this item to the user. * @return This Item so additional setters can be called. * * @see #setShowAsAction(int) */ public MenuItem setActionView(View view); /** * Set an action view for this menu item. An action view will be displayed in place * of an automatically generated menu item element in the UI when this item is shown * as an action within a parent. * <p> * <strong>Note:</strong> Setting an action view overrides the action provider * set via {@link #setActionProvider(ActionProvider)}. * </p> * * @param resId Layout resource to use for presenting this item to the user. * @return This Item so additional setters can be called. * * @see #setShowAsAction(int) */ public MenuItem setActionView(int resId); /** * Returns the currently set action view for this menu item. * * @return This item's action view * * @see #setActionView(View) * @see #setShowAsAction(int) */ public View getActionView(); /** * Sets the {@link ActionProvider} responsible for creating an action view if * the item is placed on the action bar. The provider also provides a default * action invoked if the item is placed in the overflow menu. * <p> * <strong>Note:</strong> Setting an action provider overrides the action view * set via {@link #setActionView(int)} or {@link #setActionView(View)}. * </p> * * @param actionProvider The action provider. * @return This Item so additional setters can be called. * * @see ActionProvider */ public MenuItem setActionProvider(ActionProvider actionProvider); /** * Gets the {@link ActionProvider}. * * @return The action provider. * * @see ActionProvider * @see #setActionProvider(ActionProvider) */ public ActionProvider getActionProvider(); /** * Expand the action view associated with this menu item. * The menu item must have an action view set, as well as * the showAsAction flag {@link #SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW}. * If a listener has been set using {@link #setOnActionExpandListener(OnActionExpandListener)} * it will have its {@link OnActionExpandListener#onMenuItemActionExpand(MenuItem)} * method invoked. The listener may return false from this method to prevent expanding * the action view. * * @return true if the action view was expanded, false otherwise. */ public boolean expandActionView(); /** * Collapse the action view associated with this menu item. * The menu item must have an action view set, as well as the showAsAction flag * {@link #SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW}. If a listener has been set using * {@link #setOnActionExpandListener(OnActionExpandListener)} it will have its * {@link OnActionExpandListener#onMenuItemActionCollapse(MenuItem)} method invoked. * The listener may return false from this method to prevent collapsing the action view. * * @return true if the action view was collapsed, false otherwise. */ public boolean collapseActionView(); /** * Returns true if this menu item's action view has been expanded. * * @return true if the item's action view is expanded, false otherwise. * * @see #expandActionView() * @see #collapseActionView() * @see #SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW * @see OnActionExpandListener */ public boolean isActionViewExpanded(); /** * Set an {@link OnActionExpandListener} on this menu item to be notified when * the associated action view is expanded or collapsed. The menu item must * be configured to expand or collapse its action view using the flag * {@link #SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW}. * * @param listener Listener that will respond to expand/collapse events * @return This menu item instance for call chaining */ public MenuItem setOnActionExpandListener(OnActionExpandListener listener); }
Java
/* * Copyright (C) 2006 The Android Open Source Project * Copyright (C) 2011 Jake Wharton * * 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.view; import android.content.Context; /** * <p>Abstract base class for a top-level window look and behavior policy. An * instance of this class should be used as the top-level view added to the * window manager. It provides standard UI policies such as a background, title * area, default key processing, etc.</p> * * <p>The only existing implementation of this abstract class is * android.policy.PhoneWindow, which you should instantiate when needing a * Window. Eventually that class will be refactored and a factory method added * for creating Window instances without knowing about a particular * implementation.</p> */ public abstract class Window extends android.view.Window { public static final long FEATURE_ACTION_BAR = android.view.Window.FEATURE_ACTION_BAR; public static final long FEATURE_ACTION_BAR_OVERLAY = android.view.Window.FEATURE_ACTION_BAR_OVERLAY; public static final long FEATURE_ACTION_MODE_OVERLAY = android.view.Window.FEATURE_ACTION_MODE_OVERLAY; public static final long FEATURE_NO_TITLE = android.view.Window.FEATURE_NO_TITLE; public static final long FEATURE_PROGRESS = android.view.Window.FEATURE_PROGRESS; public static final long FEATURE_INDETERMINATE_PROGRESS = android.view.Window.FEATURE_INDETERMINATE_PROGRESS; /** * Create a new instance for a context. * * @param context Context. */ private Window(Context context) { super(context); } public interface Callback { /** * Called when a panel's menu item has been selected by the user. * * @param featureId The panel that the menu is in. * @param item The menu item that was selected. * * @return boolean Return true to finish processing of selection, or * false to perform the normal menu handling (calling its * Runnable or sending a Message to its target Handler). */ public boolean onMenuItemSelected(int featureId, MenuItem item); } }
Java
public class main { int a; int b; public main() { a = 10; b = 20; } }
Java
public class svnTest { public svnTest() { ; // 11 ; // 22 int a; } }
Java
public class main { int a; int b; int sum; public main() { a = 10; b = 20; sum = 0; } public void add() { sum = a + b; this.sum = sum; } }
Java
public class SVNTest { }
Java
/* * Copyright 2007 ZXing authors * * 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.onurgunduz.qrdec.client; /** * <p>Encapsulates data masks for the data bits in a QR code, per ISO 18004:2006 6.8. Implementations * of this class can un-mask a raw BitMatrix. For simplicity, they will unmask the entire BitMatrix, * including areas used for finder patterns, timing patterns, etc. These areas should be unused * after the point they are unmasked anyway.</p> * * <p>Note that the diagram in section 6.8.1 is misleading since it indicates that i is column position * and j is row position. In fact, as the text says, i is row position and j is column position.</p> * * @author Sean Owen */ abstract class DataMask { /** * See ISO 18004:2006 6.8.1 */ private static final DataMask[] DATA_MASKS = { new DataMask000(), new DataMask001(), new DataMask010(), new DataMask011(), new DataMask100(), new DataMask101(), new DataMask110(), new DataMask111(), }; private DataMask() { } /** * <p>Implementations of this method reverse the data masking process applied to a QR Code and * make its bits ready to read.</p> * * @param bits representation of QR Code bits from {@link com.google.zxing.common.BitMatrix#getBits()} * @param dimension dimension of QR Code, represented by bits, being unmasked */ abstract void unmaskBitMatrix(int[] bits, int dimension); /** * @param reference a value between 0 and 7 indicating one of the eight possible * data mask patterns a QR Code may use * @return {@link DataMask} encapsulating the data mask pattern */ static DataMask forReference(int reference) { if (reference < 0 || reference > 7) { throw new IllegalArgumentException(); } return DATA_MASKS[reference]; } /** * 000: mask bits for which (i + j) mod 2 == 0 */ private static class DataMask000 extends DataMask { private static final int BITMASK = 0x55555555; // = 010101... void unmaskBitMatrix(int[] bits, int dimension) { // This one's easy. Because the dimension of BitMatrix is always odd, // we can merely flip every other bit int max = bits.length; for (int i = 0; i < max; i++) { bits[i] ^= BITMASK; } } } /** * 001: mask bits for which i mod 2 == 0 */ private static class DataMask001 extends DataMask { void unmaskBitMatrix(int[] bits, int dimension) { int bitMask = 0; int count = 0; int offset = 0; for (int j = 0; j < dimension; j++) { for (int i = 0; i < dimension; i++) { if ((i & 0x01) == 0) { bitMask |= 1 << count; } if (++count == 32) { bits[offset++] ^= bitMask; count = 0; bitMask = 0; } } } bits[offset] ^= bitMask; } } /** * 010: mask bits for which j mod 3 == 0 */ private static class DataMask010 extends DataMask { void unmaskBitMatrix(int[] bits, int dimension) { int bitMask = 0; int count = 0; int offset = 0; for (int j = 0; j < dimension; j++) { boolean columnMasked = j % 3 == 0; for (int i = 0; i < dimension; i++) { if (columnMasked) { bitMask |= 1 << count; } if (++count == 32) { bits[offset++] ^= bitMask; count = 0; bitMask = 0; } } } bits[offset] ^= bitMask; } } /** * 011: mask bits for which (i + j) mod 3 == 0 */ private static class DataMask011 extends DataMask { void unmaskBitMatrix(int[] bits, int dimension) { int bitMask = 0; int count = 0; int offset = 0; for (int j = 0; j < dimension; j++) { for (int i = 0; i < dimension; i++) { if ((i + j) % 3 == 0) { bitMask |= 1 << count; } if (++count == 32) { bits[offset++] ^= bitMask; count = 0; bitMask = 0; } } } bits[offset] ^= bitMask; } } /** * 100: mask bits for which (i/2 + j/3) mod 2 == 0 */ private static class DataMask100 extends DataMask { void unmaskBitMatrix(int[] bits, int dimension) { int bitMask = 0; int count = 0; int offset = 0; for (int j = 0; j < dimension; j++) { int jComponentParity = (j / 3) & 0x01; for (int i = 0; i < dimension; i++) { if (((i >> 1) & 0x01) == jComponentParity) { bitMask |= 1 << count; } if (++count == 32) { bits[offset++] ^= bitMask; count = 0; bitMask = 0; } } } bits[offset] ^= bitMask; } } /** * 101: mask bits for which ij mod 2 + ij mod 3 == 0 */ private static class DataMask101 extends DataMask { void unmaskBitMatrix(int[] bits, int dimension) { int bitMask = 0; int count = 0; int offset = 0; for (int j = 0; j < dimension; j++) { for (int i = 0; i < dimension; i++) { int product = i * j; if (((product & 0x01) == 0) && product % 3 == 0) { bitMask |= 1 << count; } if (++count == 32) { bits[offset++] ^= bitMask; count = 0; bitMask = 0; } } } bits[offset] ^= bitMask; } } /** * 110: mask bits for which (ij mod 2 + ij mod 3) mod 2 == 0 */ private static class DataMask110 extends DataMask { void unmaskBitMatrix(int[] bits, int dimension) { int bitMask = 0; int count = 0; int offset = 0; for (int j = 0; j < dimension; j++) { for (int i = 0; i < dimension; i++) { int product = i * j; if ((((product & 0x01) + product % 3) & 0x01) == 0) { bitMask |= 1 << count; } if (++count == 32) { bits[offset++] ^= bitMask; count = 0; bitMask = 0; } } } bits[offset] ^= bitMask; } } /** * 111: mask bits for which ((i+j)mod 2 + ij mod 3) mod 2 == 0 */ private static class DataMask111 extends DataMask { void unmaskBitMatrix(int[] bits, int dimension) { int bitMask = 0; int count = 0; int offset = 0; for (int j = 0; j < dimension; j++) { for (int i = 0; i < dimension; i++) { if (((((i + j) & 0x01) + (i * j) % 3) & 0x01) == 0) { bitMask |= 1 << count; } if (++count == 32) { bits[offset++] ^= bitMask; count = 0; bitMask = 0; } } } bits[offset] ^= bitMask; } } }
Java
/* * Copyright 2008 ZXing authors * * 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.onurgunduz.qrdec.client; /** * Superclass of classes encapsulating types ECIs, according to "Extended Channel Interpretations" 5.3 * of ISO 18004. * * @author Sean Owen */ public abstract class ECI { private final int value; ECI(int value) { this.value = value; } public int getValue() { return value; } /** * @param value ECI value * @return {@link ECI} representing ECI of given value, or null if it is legal but unsupported * @throws IllegalArgumentException if ECI value is invalid */ public static ECI getECIByValue(int value) { if (value < 0 || value > 999999) { throw new IllegalArgumentException("Bad ECI value: " + value); } if (value < 900) { // Character set ECIs use 000000 - 000899 return CharacterSetECI.getCharacterSetECIByValue(value); } return null; } }
Java
package com.onurgunduz.qrdec.client; /** * <p>Represnts a square matrix of bits. In function arguments below, i is the row position * and j the column position of a bit. The top left bit corresponds to i = 0 and j = 0.</p> * * <p>Internally the bits are represented in a compact 1-D array of 32-bit ints. The * ordering of bits is column-major; that is the bits in this array correspond to * j=0 and i=0..dimension-1 first, then j=1 and i=0..dimension-1, etc.</p> * * <p>Within each int, less-signficant bits correspond to lower values of i and higher rows. * That is, the top-left bit is the least significant bit of the first int.</p> * * <p>This class is a convenient wrapper around this representation, but also exposes the internal * array for efficient access and manipulation.</p> * * @author Sean Owen */ public final class BitMatrix { private final int dimension; private final int[] bits; public BitMatrix(int dimension) { if (dimension < 1) { throw new IllegalArgumentException("dimension must be at least 1"); } this.dimension = dimension; int numBits = dimension * dimension; int arraySize = numBits >> 5; // one int per 32 bits if ((numBits & 0x1F) != 0) { // plus one more if there are leftovers arraySize++; } bits = new int[arraySize]; } /** * @param i row offset * @param j column offset * @return value of given bit in matrix */ public boolean get(int i, int j) { int offset = i + dimension * j; return ((bits[offset >> 5] >>> (offset & 0x1F)) & 0x01) != 0; } /** * <p>Sets the given bit to true.</p> * * @param i row offset * @param j column offset */ public void set(int i, int j) { int offset = i + dimension * j; bits[offset >> 5] |= 1 << (offset & 0x1F); } /** * <p>Sets a square region of the bit matrix to true.</p> * * @param topI row offset of region's top-left corner (inclusive) * @param leftJ column offset of region's top-left corner (inclusive) * @param height height of region * @param width width of region */ public void setRegion(int topI, int leftJ, int height, int width) { if (topI < 0 || leftJ < 0) { throw new IllegalArgumentException("topI and leftJ must be nonnegative"); } if (height < 1 || width < 1) { throw new IllegalArgumentException("height and width must be at least 1"); } int maxJ = leftJ + width; int maxI = topI + height; if (maxI > dimension || maxJ > dimension) { throw new IllegalArgumentException( "topI + height and leftJ + width must be <= matrix dimension"); } for (int j = leftJ; j < maxJ; j++) { int jOffset = dimension * j; for (int i = topI; i < maxI; i++) { int offset = i + jOffset; bits[offset >> 5] |= 1 << (offset & 0x1F); } } } /** * @return row/column dimension of this matrix */ public int getDimension() { return dimension; } /** * @return array of ints holding internal representation of this matrix's bits */ public int[] getBits() { return bits; } public String toString() { StringBuffer result = new StringBuffer(dimension * (dimension + 1)); for (int i = 0; i < dimension; i++) { for (int j = 0; j < dimension; j++) { result.append(get(i, j) ? "X " : " "); } result.append('\n'); } return result.toString(); } }
Java
/* * Copyright 2007 ZXing authors * * 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.onurgunduz.qrdec.client; import com.onurgunduz.qrdec.client.ReaderException; import com.onurgunduz.qrdec.client.BitMatrix; /** * See ISO 18004:2006 Annex D * * @author Sean Owen */ public final class Version { /** * See ISO 18004:2006 Annex D. * Element i represents the raw version bits that specify version i + 7 */ private static final int[] VERSION_DECODE_INFO = { 0x07C94, 0x085BC, 0x09A99, 0x0A4D3, 0x0BBF6, 0x0C762, 0x0D847, 0x0E60D, 0x0F928, 0x10B78, 0x1145D, 0x12A17, 0x13532, 0x149A6, 0x15683, 0x168C9, 0x177EC, 0x18EC4, 0x191E1, 0x1AFAB, 0x1B08E, 0x1CC1A, 0x1D33F, 0x1ED75, 0x1F250, 0x209D5, 0x216F0, 0x228BA, 0x2379F, 0x24B0B, 0x2542E, 0x26A64, 0x27541, 0x28C69 }; private static final Version[] VERSIONS = buildVersions(); private final int versionNumber; private final int[] alignmentPatternCenters; private final ECBlocks[] ecBlocks; private final int totalCodewords; private Version(int versionNumber, int[] alignmentPatternCenters, ECBlocks ecBlocks1, ECBlocks ecBlocks2, ECBlocks ecBlocks3, ECBlocks ecBlocks4) { this.versionNumber = versionNumber; this.alignmentPatternCenters = alignmentPatternCenters; this.ecBlocks = new ECBlocks[]{ecBlocks1, ecBlocks2, ecBlocks3, ecBlocks4}; int total = 0; int ecCodewords = ecBlocks1.getECCodewordsPerBlock(); ECB[] ecbArray = ecBlocks1.getECBlocks(); for (int i = 0; i < ecbArray.length; i++) { ECB ecBlock = ecbArray[i]; total += ecBlock.getCount() * (ecBlock.getDataCodewords() + ecCodewords); } this.totalCodewords = total; } public int getVersionNumber() { return versionNumber; } public int[] getAlignmentPatternCenters() { return alignmentPatternCenters; } public int getTotalCodewords() { return totalCodewords; } public int getDimensionForVersion() { return 17 + 4 * versionNumber; } public ECBlocks getECBlocksForLevel(ErrorCorrectionLevel ecLevel) { return ecBlocks[ecLevel.ordinal()]; } /** * <p>Deduces version information purely from QR Code dimensions.</p> * * @param dimension dimension in modules * @return {@link Version} for a QR Code of that dimension * @throws ReaderException if dimension is not 1 mod 4 */ public static Version getProvisionalVersionForDimension(int dimension) throws ReaderException { if (dimension % 4 != 1) { throw ReaderException.getInstance(); } return getVersionForNumber((dimension - 17) >> 2); } public static Version getVersionForNumber(int versionNumber) { if (versionNumber < 1 || versionNumber > 40) { throw new IllegalArgumentException(); } return VERSIONS[versionNumber - 1]; } static Version decodeVersionInformation(int versionBits) { int bestDifference = Integer.MAX_VALUE; int bestVersion = 0; for (int i = 0; i < VERSION_DECODE_INFO.length; i++) { int targetVersion = VERSION_DECODE_INFO[i]; // Do the version info bits match exactly? done. if (targetVersion == versionBits) { return getVersionForNumber(i + 7); } // Otherwise see if this is the closest to a real version info bit string // we have seen so far int bitsDifference = FormatInformation.numBitsDiffering(versionBits, targetVersion); if (bitsDifference < bestDifference) { bestVersion = i + 7; } } // We can tolerate up to 3 bits of error since no two version info codewords will // differ in less than 4 bits. if (bestDifference <= 3) { return getVersionForNumber(bestVersion); } // If we didn't find a close enough match, fail return null; } /** * See ISO 18004:2006 Annex E */ BitMatrix buildFunctionPattern() { int dimension = getDimensionForVersion(); BitMatrix bitMatrix = new BitMatrix(dimension); // Top left finder pattern + separator + format bitMatrix.setRegion(0, 0, 9, 9); // Top right finder pattern + separator + format bitMatrix.setRegion(0, dimension - 8, 9, 8); // Bottom left finder pattern + separator + format bitMatrix.setRegion(dimension - 8, 0, 8, 9); // Alignment patterns int max = alignmentPatternCenters.length; for (int x = 0; x < max; x++) { int i = alignmentPatternCenters[x] - 2; for (int y = 0; y < max; y++) { if ((x == 0 && (y == 0 || y == max - 1)) || (x == max - 1 && y == 0)) { // No alignment patterns near the three finder paterns continue; } bitMatrix.setRegion(i, alignmentPatternCenters[y] - 2, 5, 5); } } // Vertical timing pattern bitMatrix.setRegion(9, 6, dimension - 17, 1); // Horizontal timing pattern bitMatrix.setRegion(6, 9, 1, dimension - 17); if (versionNumber > 6) { // Version info, top right bitMatrix.setRegion(0, dimension - 11, 6, 3); // Version info, bottom left bitMatrix.setRegion(dimension - 11, 0, 3, 6); } return bitMatrix; } /** * <p>Encapsulates a set of error-correction blocks in one symbol version. Most versions will * use blocks of differing sizes within one version, so, this encapsulates the parameters for * each set of blocks. It also holds the number of error-correction codewords per block since it * will be the same across all blocks within one version.</p> */ public static final class ECBlocks { private final int ecCodewordsPerBlock; private final ECB[] ecBlocks; private ECBlocks(int ecCodewordsPerBlock, ECB ecBlocks) { this.ecCodewordsPerBlock = ecCodewordsPerBlock; this.ecBlocks = new ECB[]{ecBlocks}; } private ECBlocks(int ecCodewordsPerBlock, ECB ecBlocks1, ECB ecBlocks2) { this.ecCodewordsPerBlock = ecCodewordsPerBlock; this.ecBlocks = new ECB[]{ecBlocks1, ecBlocks2}; } public int getECCodewordsPerBlock() { return ecCodewordsPerBlock; } public int getNumBlocks() { int total = 0; for (int i = 0; i < ecBlocks.length; i++) { total += ecBlocks[i].getCount(); } return total; } public int getTotalECCodewords() { return ecCodewordsPerBlock * getNumBlocks(); } public ECB[] getECBlocks() { return ecBlocks; } } /** * <p>Encapsualtes the parameters for one error-correction block in one symbol version. * This includes the number of data codewords, and the number of times a block with these * parameters is used consecutively in the QR code version's format.</p> */ public static final class ECB { private final int count; private final int dataCodewords; ECB(int count, int dataCodewords) { this.count = count; this.dataCodewords = dataCodewords; } public int getCount() { return count; } public int getDataCodewords() { return dataCodewords; } } public String toString() { return String.valueOf(versionNumber); } /** * See ISO 18004:2006 6.5.1 Table 9 */ private static Version[] buildVersions() { return new Version[]{ new Version(1, new int[]{}, new ECBlocks(7, new ECB(1, 19)), new ECBlocks(10, new ECB(1, 16)), new ECBlocks(13, new ECB(1, 13)), new ECBlocks(17, new ECB(1, 9))), new Version(2, new int[]{6, 18}, new ECBlocks(10, new ECB(1, 34)), new ECBlocks(16, new ECB(1, 28)), new ECBlocks(22, new ECB(1, 22)), new ECBlocks(28, new ECB(1, 16))), new Version(3, new int[]{6, 22}, new ECBlocks(15, new ECB(1, 55)), new ECBlocks(26, new ECB(1, 44)), new ECBlocks(18, new ECB(2, 17)), new ECBlocks(22, new ECB(2, 13))), new Version(4, new int[]{6, 26}, new ECBlocks(20, new ECB(1, 80)), new ECBlocks(18, new ECB(2, 32)), new ECBlocks(26, new ECB(2, 24)), new ECBlocks(16, new ECB(4, 9))), new Version(5, new int[]{6, 30}, new ECBlocks(26, new ECB(1, 108)), new ECBlocks(24, new ECB(2, 43)), new ECBlocks(18, new ECB(2, 15), new ECB(2, 16)), new ECBlocks(22, new ECB(2, 11), new ECB(2, 12))), new Version(6, new int[]{6, 34}, new ECBlocks(18, new ECB(2, 68)), new ECBlocks(16, new ECB(4, 27)), new ECBlocks(24, new ECB(4, 19)), new ECBlocks(28, new ECB(4, 15))), new Version(7, new int[]{6, 22, 38}, new ECBlocks(20, new ECB(2, 78)), new ECBlocks(18, new ECB(4, 31)), new ECBlocks(18, new ECB(2, 14), new ECB(4, 15)), new ECBlocks(26, new ECB(4, 13), new ECB(1, 14))), new Version(8, new int[]{6, 24, 42}, new ECBlocks(24, new ECB(2, 97)), new ECBlocks(22, new ECB(2, 38), new ECB(2, 39)), new ECBlocks(22, new ECB(4, 18), new ECB(2, 19)), new ECBlocks(26, new ECB(4, 14), new ECB(2, 15))), new Version(9, new int[]{6, 26, 46}, new ECBlocks(30, new ECB(2, 116)), new ECBlocks(22, new ECB(3, 36), new ECB(2, 37)), new ECBlocks(20, new ECB(4, 16), new ECB(4, 17)), new ECBlocks(24, new ECB(4, 12), new ECB(4, 13))), new Version(10, new int[]{6, 28, 50}, new ECBlocks(18, new ECB(2, 68), new ECB(2, 69)), new ECBlocks(26, new ECB(4, 43), new ECB(1, 44)), new ECBlocks(24, new ECB(6, 19), new ECB(2, 20)), new ECBlocks(28, new ECB(6, 15), new ECB(2, 16))), new Version(11, new int[]{6, 30, 54}, new ECBlocks(20, new ECB(4, 81)), new ECBlocks(30, new ECB(1, 50), new ECB(4, 51)), new ECBlocks(28, new ECB(4, 22), new ECB(4, 23)), new ECBlocks(24, new ECB(3, 12), new ECB(8, 13))), new Version(12, new int[]{6, 32, 58}, new ECBlocks(24, new ECB(2, 92), new ECB(2, 93)), new ECBlocks(22, new ECB(6, 36), new ECB(2, 37)), new ECBlocks(26, new ECB(4, 20), new ECB(6, 21)), new ECBlocks(28, new ECB(7, 14), new ECB(4, 15))), new Version(13, new int[]{6, 34, 62}, new ECBlocks(26, new ECB(4, 107)), new ECBlocks(22, new ECB(8, 37), new ECB(1, 38)), new ECBlocks(24, new ECB(8, 20), new ECB(4, 21)), new ECBlocks(22, new ECB(12, 11), new ECB(4, 12))), new Version(14, new int[]{6, 26, 46, 66}, new ECBlocks(30, new ECB(3, 115), new ECB(1, 116)), new ECBlocks(24, new ECB(4, 40), new ECB(5, 41)), new ECBlocks(20, new ECB(11, 16), new ECB(5, 17)), new ECBlocks(24, new ECB(11, 12), new ECB(5, 13))), new Version(15, new int[]{6, 26, 48, 70}, new ECBlocks(22, new ECB(5, 87), new ECB(1, 88)), new ECBlocks(24, new ECB(5, 41), new ECB(5, 42)), new ECBlocks(30, new ECB(5, 24), new ECB(7, 25)), new ECBlocks(24, new ECB(11, 12), new ECB(7, 13))), new Version(16, new int[]{6, 26, 50, 74}, new ECBlocks(24, new ECB(5, 98), new ECB(1, 99)), new ECBlocks(28, new ECB(7, 45), new ECB(3, 46)), new ECBlocks(24, new ECB(15, 19), new ECB(2, 20)), new ECBlocks(30, new ECB(3, 15), new ECB(13, 16))), new Version(17, new int[]{6, 30, 54, 78}, new ECBlocks(28, new ECB(1, 107), new ECB(5, 108)), new ECBlocks(28, new ECB(10, 46), new ECB(1, 47)), new ECBlocks(28, new ECB(1, 22), new ECB(15, 23)), new ECBlocks(28, new ECB(2, 14), new ECB(17, 15))), new Version(18, new int[]{6, 30, 56, 82}, new ECBlocks(30, new ECB(5, 120), new ECB(1, 121)), new ECBlocks(26, new ECB(9, 43), new ECB(4, 44)), new ECBlocks(28, new ECB(17, 22), new ECB(1, 23)), new ECBlocks(28, new ECB(2, 14), new ECB(19, 15))), new Version(19, new int[]{6, 30, 58, 86}, new ECBlocks(28, new ECB(3, 113), new ECB(4, 114)), new ECBlocks(26, new ECB(3, 44), new ECB(11, 45)), new ECBlocks(26, new ECB(17, 21), new ECB(4, 22)), new ECBlocks(26, new ECB(9, 13), new ECB(16, 14))), new Version(20, new int[]{6, 34, 62, 90}, new ECBlocks(28, new ECB(3, 107), new ECB(5, 108)), new ECBlocks(26, new ECB(3, 41), new ECB(13, 42)), new ECBlocks(30, new ECB(15, 24), new ECB(5, 25)), new ECBlocks(28, new ECB(15, 15), new ECB(10, 16))), new Version(21, new int[]{6, 28, 50, 72, 94}, new ECBlocks(28, new ECB(4, 116), new ECB(4, 117)), new ECBlocks(26, new ECB(17, 42)), new ECBlocks(28, new ECB(17, 22), new ECB(6, 23)), new ECBlocks(30, new ECB(19, 16), new ECB(6, 17))), new Version(22, new int[]{6, 26, 50, 74, 98}, new ECBlocks(28, new ECB(2, 111), new ECB(7, 112)), new ECBlocks(28, new ECB(17, 46)), new ECBlocks(30, new ECB(7, 24), new ECB(16, 25)), new ECBlocks(24, new ECB(34, 13))), new Version(23, new int[]{6, 30, 54, 74, 102}, new ECBlocks(30, new ECB(4, 121), new ECB(5, 122)), new ECBlocks(28, new ECB(4, 47), new ECB(14, 48)), new ECBlocks(30, new ECB(11, 24), new ECB(14, 25)), new ECBlocks(30, new ECB(16, 15), new ECB(14, 16))), new Version(24, new int[]{6, 28, 54, 80, 106}, new ECBlocks(30, new ECB(6, 117), new ECB(4, 118)), new ECBlocks(28, new ECB(6, 45), new ECB(14, 46)), new ECBlocks(30, new ECB(11, 24), new ECB(16, 25)), new ECBlocks(30, new ECB(30, 16), new ECB(2, 17))), new Version(25, new int[]{6, 32, 58, 84, 110}, new ECBlocks(26, new ECB(8, 106), new ECB(4, 107)), new ECBlocks(28, new ECB(8, 47), new ECB(13, 48)), new ECBlocks(30, new ECB(7, 24), new ECB(22, 25)), new ECBlocks(30, new ECB(22, 15), new ECB(13, 16))), new Version(26, new int[]{6, 30, 58, 86, 114}, new ECBlocks(28, new ECB(10, 114), new ECB(2, 115)), new ECBlocks(28, new ECB(19, 46), new ECB(4, 47)), new ECBlocks(28, new ECB(28, 22), new ECB(6, 23)), new ECBlocks(30, new ECB(33, 16), new ECB(4, 17))), new Version(27, new int[]{6, 34, 62, 90, 118}, new ECBlocks(30, new ECB(8, 122), new ECB(4, 123)), new ECBlocks(28, new ECB(22, 45), new ECB(3, 46)), new ECBlocks(30, new ECB(8, 23), new ECB(26, 24)), new ECBlocks(30, new ECB(12, 15), new ECB(28, 16))), new Version(28, new int[]{6, 26, 50, 74, 98, 122}, new ECBlocks(30, new ECB(3, 117), new ECB(10, 118)), new ECBlocks(28, new ECB(3, 45), new ECB(23, 46)), new ECBlocks(30, new ECB(4, 24), new ECB(31, 25)), new ECBlocks(30, new ECB(11, 15), new ECB(31, 16))), new Version(29, new int[]{6, 30, 54, 78, 102, 126}, new ECBlocks(30, new ECB(7, 116), new ECB(7, 117)), new ECBlocks(28, new ECB(21, 45), new ECB(7, 46)), new ECBlocks(30, new ECB(1, 23), new ECB(37, 24)), new ECBlocks(30, new ECB(19, 15), new ECB(26, 16))), new Version(30, new int[]{6, 26, 52, 78, 104, 130}, new ECBlocks(30, new ECB(5, 115), new ECB(10, 116)), new ECBlocks(28, new ECB(19, 47), new ECB(10, 48)), new ECBlocks(30, new ECB(15, 24), new ECB(25, 25)), new ECBlocks(30, new ECB(23, 15), new ECB(25, 16))), new Version(31, new int[]{6, 30, 56, 82, 108, 134}, new ECBlocks(30, new ECB(13, 115), new ECB(3, 116)), new ECBlocks(28, new ECB(2, 46), new ECB(29, 47)), new ECBlocks(30, new ECB(42, 24), new ECB(1, 25)), new ECBlocks(30, new ECB(23, 15), new ECB(28, 16))), new Version(32, new int[]{6, 34, 60, 86, 112, 138}, new ECBlocks(30, new ECB(17, 115)), new ECBlocks(28, new ECB(10, 46), new ECB(23, 47)), new ECBlocks(30, new ECB(10, 24), new ECB(35, 25)), new ECBlocks(30, new ECB(19, 15), new ECB(35, 16))), new Version(33, new int[]{6, 30, 58, 86, 114, 142}, new ECBlocks(30, new ECB(17, 115), new ECB(1, 116)), new ECBlocks(28, new ECB(14, 46), new ECB(21, 47)), new ECBlocks(30, new ECB(29, 24), new ECB(19, 25)), new ECBlocks(30, new ECB(11, 15), new ECB(46, 16))), new Version(34, new int[]{6, 34, 62, 90, 118, 146}, new ECBlocks(30, new ECB(13, 115), new ECB(6, 116)), new ECBlocks(28, new ECB(14, 46), new ECB(23, 47)), new ECBlocks(30, new ECB(44, 24), new ECB(7, 25)), new ECBlocks(30, new ECB(59, 16), new ECB(1, 17))), new Version(35, new int[]{6, 30, 54, 78, 102, 126, 150}, new ECBlocks(30, new ECB(12, 121), new ECB(7, 122)), new ECBlocks(28, new ECB(12, 47), new ECB(26, 48)), new ECBlocks(30, new ECB(39, 24), new ECB(14, 25)), new ECBlocks(30, new ECB(22, 15), new ECB(41, 16))), new Version(36, new int[]{6, 24, 50, 76, 102, 128, 154}, new ECBlocks(30, new ECB(6, 121), new ECB(14, 122)), new ECBlocks(28, new ECB(6, 47), new ECB(34, 48)), new ECBlocks(30, new ECB(46, 24), new ECB(10, 25)), new ECBlocks(30, new ECB(2, 15), new ECB(64, 16))), new Version(37, new int[]{6, 28, 54, 80, 106, 132, 158}, new ECBlocks(30, new ECB(17, 122), new ECB(4, 123)), new ECBlocks(28, new ECB(29, 46), new ECB(14, 47)), new ECBlocks(30, new ECB(49, 24), new ECB(10, 25)), new ECBlocks(30, new ECB(24, 15), new ECB(46, 16))), new Version(38, new int[]{6, 32, 58, 84, 110, 136, 162}, new ECBlocks(30, new ECB(4, 122), new ECB(18, 123)), new ECBlocks(28, new ECB(13, 46), new ECB(32, 47)), new ECBlocks(30, new ECB(48, 24), new ECB(14, 25)), new ECBlocks(30, new ECB(42, 15), new ECB(32, 16))), new Version(39, new int[]{6, 26, 54, 82, 110, 138, 166}, new ECBlocks(30, new ECB(20, 117), new ECB(4, 118)), new ECBlocks(28, new ECB(40, 47), new ECB(7, 48)), new ECBlocks(30, new ECB(43, 24), new ECB(22, 25)), new ECBlocks(30, new ECB(10, 15), new ECB(67, 16))), new Version(40, new int[]{6, 30, 58, 86, 114, 142, 170}, new ECBlocks(30, new ECB(19, 118), new ECB(6, 119)), new ECBlocks(28, new ECB(18, 47), new ECB(31, 48)), new ECBlocks(30, new ECB(34, 24), new ECB(34, 25)), new ECBlocks(30, new ECB(20, 15), new ECB(61, 16))) }; } }
Java
/* * Copyright 2007 ZXing authors * * 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.onurgunduz.qrdec.client; /** * The general exception class throw when something goes wrong during decoding of a barcode. * This includes, but is not limited to, failing checksums / error correction algorithms, being * unable to locate finder timing patterns, and so on. * * @author Sean Owen */ public final class ReaderException extends Exception { // TODO: Currently we throw up to 400 ReaderExceptions while scanning a single 240x240 image before // rejecting it. This involves a lot of overhead and memory allocation, and affects both performance // and latency on continuous scan clients. In the future, we should change all the decoders not to // throw exceptions for routine events, like not finding a barcode on a given row. Instead, we // should return error codes back to the callers, and simply delete this class. In the mean time, I // have altered this class to be as lightweight as possible, by ignoring the exception string, and // by disabling the generation of stack traces, which is especially time consuming. These are just // temporary measures, pending the big cleanup. private static final ReaderException instance = new ReaderException(); private ReaderException() { // do nothing } public static ReaderException getInstance() { return instance; } // Prevent stack traces from being taken // srowen says: huh, my IDE is saying this is not an override. native methods can't be overridden? // This, at least, does not hurt. Because we use a singleton pattern here, it doesn't matter anyhow. public Throwable fillInStackTrace() { return null; } }
Java
/* * Copyright 2007 ZXing authors * * 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.onurgunduz.qrdec.client; /** * <p>This provides an easy abstraction to read bits at a time from a sequence of bytes, where the * number of bits read is not often a multiple of 8.</p> * * <p>This class is not thread-safe.</p> * * @author Sean Owen */ public final class BitSource { private final byte[] bytes; private int byteOffset; private int bitOffset; /** * @param bytes bytes from which this will read bits. Bits will be read from the first byte first. * Bits are read within a byte from most-significant to least-significant bit. */ public BitSource(byte[] bytes) { this.bytes = bytes; } /** * @param numBits number of bits to read * @return int representing the bits read. The bits will appear as the least-significant * bits of the int * @throws IllegalArgumentException if numBits isn't in [1,32] */ public int readBits(int numBits) { if (numBits < 1 || numBits > 32) { throw new IllegalArgumentException(); } int result = 0; // First, read remainder from current byte if (bitOffset > 0) { int bitsLeft = 8 - bitOffset; int toRead = numBits < bitsLeft ? numBits : bitsLeft; int bitsToNotRead = bitsLeft - toRead; int mask = (0xFF >> (8 - toRead)) << bitsToNotRead; result = (bytes[byteOffset] & mask) >> bitsToNotRead; numBits -= toRead; bitOffset += toRead; if (bitOffset == 8) { bitOffset = 0; byteOffset++; } } // Next read whole bytes if (numBits > 0) { while (numBits >= 8) { result = (result << 8) | (bytes[byteOffset] & 0xFF); byteOffset++; numBits -= 8; } // Finally read a partial byte if (numBits > 0) { int bitsToNotRead = 8 - numBits; int mask = (0xFF >> bitsToNotRead) << bitsToNotRead; result = (result << numBits) | ((bytes[byteOffset] & mask) >> bitsToNotRead); bitOffset += numBits; } } return result; } /** * @return number of bits that can be read successfully */ public int available() { return 8 * (bytes.length - byteOffset) - bitOffset; } }
Java
/* * Copyright 2007 ZXing authors * * 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.onurgunduz.qrdec.client; /** * <p>This class contains utility methods for performing mathematical operations over * the Galois Field GF(256). Operations use a given primitive polynomial in calculations.</p> * * <p>Throughout this package, elements of GF(256) are represented as an <code>int</code> * for convenience and speed (but at the cost of memory). * Only the bottom 8 bits are really used.</p> * * @author Sean Owen */ public final class GF256 { public static final GF256 QR_CODE_FIELD = new GF256(0x011D); // x^8 + x^4 + x^3 + x^2 + 1 public static final GF256 DATA_MATRIX_FIELD = new GF256(0x012D); // x^8 + x^5 + x^3 + x^2 + 1 private final int[] expTable; private final int[] logTable; private final GF256Poly zero; private final GF256Poly one; /** * Create a representation of GF(256) using the given primitive polynomial. * * @param primitive irreducible polynomial whose coefficients are represented by * the bits of an int, where the least-significant bit represents the constant * coefficient */ private GF256(int primitive) { expTable = new int[256]; logTable = new int[256]; int x = 1; for (int i = 0; i < 256; i++) { expTable[i] = x; x <<= 1; // x = x * 2; we're assuming the generator alpha is 2 if (x >= 0x100) { x ^= primitive; } } for (int i = 0; i < 255; i++) { logTable[expTable[i]] = i; } // logTable[0] == 0 but this should never be used zero = new GF256Poly(this, new int[]{0}); one = new GF256Poly(this, new int[]{1}); } GF256Poly getZero() { return zero; } GF256Poly getOne() { return one; } /** * @return the monomial representing coefficient * x^degree */ GF256Poly buildMonomial(int degree, int coefficient) { if (degree < 0) { throw new IllegalArgumentException(); } if (coefficient == 0) { return zero; } int[] coefficients = new int[degree + 1]; coefficients[0] = coefficient; return new GF256Poly(this, coefficients); } /** * Implements both addition and subtraction -- they are the same in GF(256). * * @return sum/difference of a and b */ static int addOrSubtract(int a, int b) { return a ^ b; } /** * @return 2 to the power of a in GF(256) */ int exp(int a) { return expTable[a]; } /** * @return base 2 log of a in GF(256) */ int log(int a) { if (a == 0) { throw new IllegalArgumentException(); } return logTable[a]; } /** * @return multiplicative inverse of a */ int inverse(int a) { if (a == 0) { throw new ArithmeticException(); } return expTable[255 - logTable[a]]; } /** * @param a * @param b * @return product of a and b in GF(256) */ int multiply(int a, int b) { if (a == 0 || b == 0) { return 0; } if (a == 1) { return b; } if (b == 1) { return a; } return expTable[(logTable[a] + logTable[b]) % 255]; } }
Java
/* * Copyright 2007 ZXing authors * * 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.onurgunduz.qrdec.client; import com.onurgunduz.qrdec.client.ReaderException; /** * <p>Encapsulates a QR Code's format information, including the data mask used and * error correction level.</p> * * @author Sean Owen * @see DataMask * @see ErrorCorrectionLevel */ final class FormatInformation { private static final int FORMAT_INFO_MASK_QR = 0x5412; /** * See ISO 18004:2006, Annex C, Table C.1 */ private static final int[][] FORMAT_INFO_DECODE_LOOKUP = { {0x5412, 0x00}, {0x5125, 0x01}, {0x5E7C, 0x02}, {0x5B4B, 0x03}, {0x45F9, 0x04}, {0x40CE, 0x05}, {0x4F97, 0x06}, {0x4AA0, 0x07}, {0x77C4, 0x08}, {0x72F3, 0x09}, {0x7DAA, 0x0A}, {0x789D, 0x0B}, {0x662F, 0x0C}, {0x6318, 0x0D}, {0x6C41, 0x0E}, {0x6976, 0x0F}, {0x1689, 0x10}, {0x13BE, 0x11}, {0x1CE7, 0x12}, {0x19D0, 0x13}, {0x0762, 0x14}, {0x0255, 0x15}, {0x0D0C, 0x16}, {0x083B, 0x17}, {0x355F, 0x18}, {0x3068, 0x19}, {0x3F31, 0x1A}, {0x3A06, 0x1B}, {0x24B4, 0x1C}, {0x2183, 0x1D}, {0x2EDA, 0x1E}, {0x2BED, 0x1F}, }; /** * Offset i holds the number of 1 bits in the binary representation of i */ private static final int[] BITS_SET_IN_HALF_BYTE = {0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4}; private final ErrorCorrectionLevel errorCorrectionLevel; private final byte dataMask; private FormatInformation(int formatInfo) { // Bits 3,4 errorCorrectionLevel = ErrorCorrectionLevel.forBits((formatInfo >> 3) & 0x03); // Bottom 3 bits dataMask = (byte) (formatInfo & 0x07); } static int numBitsDiffering(int a, int b) { a ^= b; // a now has a 1 bit exactly where its bit differs with b's // Count bits set quickly with a series of lookups: return BITS_SET_IN_HALF_BYTE[a & 0x0F] + BITS_SET_IN_HALF_BYTE[(a >>> 4 & 0x0F)] + BITS_SET_IN_HALF_BYTE[(a >>> 8 & 0x0F)] + BITS_SET_IN_HALF_BYTE[(a >>> 12 & 0x0F)] + BITS_SET_IN_HALF_BYTE[(a >>> 16 & 0x0F)] + BITS_SET_IN_HALF_BYTE[(a >>> 20 & 0x0F)] + BITS_SET_IN_HALF_BYTE[(a >>> 24 & 0x0F)] + BITS_SET_IN_HALF_BYTE[(a >>> 28 & 0x0F)]; } /** * @param rawFormatInfo * @return */ static FormatInformation decodeFormatInformation(int rawFormatInfo) { FormatInformation formatInfo = doDecodeFormatInformation(rawFormatInfo); if (formatInfo != null) { return formatInfo; } // Should return null, but, some QR codes apparently // do not mask this info. Try again, first masking the raw bits so // the function will unmask return doDecodeFormatInformation(rawFormatInfo ^ FORMAT_INFO_MASK_QR); } private static FormatInformation doDecodeFormatInformation(int rawFormatInfo) { // Unmask: int unmaskedFormatInfo = rawFormatInfo ^ FORMAT_INFO_MASK_QR; // Find the int in FORMAT_INFO_DECODE_LOOKUP with fewest bits differing int bestDifference = Integer.MAX_VALUE; int bestFormatInfo = 0; for (int i = 0; i < FORMAT_INFO_DECODE_LOOKUP.length; i++) { int[] decodeInfo = FORMAT_INFO_DECODE_LOOKUP[i]; int targetInfo = decodeInfo[0]; if (targetInfo == unmaskedFormatInfo) { // Found an exact match return new FormatInformation(decodeInfo[1]); } int bitsDifference = numBitsDiffering(unmaskedFormatInfo, targetInfo); if (bitsDifference < bestDifference) { bestFormatInfo = decodeInfo[1]; bestDifference = bitsDifference; } } if (bestDifference <= 3) { return new FormatInformation(bestFormatInfo); } return null; } ErrorCorrectionLevel getErrorCorrectionLevel() { return errorCorrectionLevel; } byte getDataMask() { return dataMask; } public int hashCode() { return (errorCorrectionLevel.ordinal() << 3) | (int) dataMask; } public boolean equals(Object o) { if (!(o instanceof FormatInformation)) { return false; } FormatInformation other = (FormatInformation) o; return this.errorCorrectionLevel == other.errorCorrectionLevel && this.dataMask == other.dataMask; } }
Java
/* * Copyright 2007 ZXing authors * * 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.onurgunduz.qrdec.client; import com.onurgunduz.qrdec.client.ReaderException; import com.onurgunduz.qrdec.client.BitSource; import com.onurgunduz.qrdec.client.CharacterSetECI; import com.onurgunduz.qrdec.client.DecoderResult; import java.util.Vector; /** * <p>QR Codes can encode text as bits in one of several modes, and can use multiple modes * in one QR Code. This class decodes the bits back into text.</p> * * <p>See ISO 18004:2006, 6.4.3 - 6.4.7</p> * * @author Sean Owen */ final class DecodedBitStreamParser { /** * See ISO 18004:2006, 6.4.4 Table 5 */ private static final char[] ALPHANUMERIC_CHARS = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', ' ', '$', '%', '*', '+', '-', '.', '/', ':' }; private static final String SHIFT_JIS = "SJIS"; private static final String EUC_JP = "EUC_JP"; private static final boolean ASSUME_SHIFT_JIS; private static final String UTF8 = "UTF8"; private static final String ISO88591 = "ISO8859_1"; static { // String platformDefault = System.getProperty("file.encoding"); String platformDefault = "UTF-8"; ASSUME_SHIFT_JIS = SHIFT_JIS.equalsIgnoreCase(platformDefault) || EUC_JP.equalsIgnoreCase(platformDefault); } private DecodedBitStreamParser() { } static DecoderResult decode(byte[] bytes, Version version) throws ReaderException { BitSource bits = new BitSource(bytes); StringBuffer result = new StringBuffer(); CharacterSetECI currentCharacterSetECI = null; boolean fc1InEffect = false; Vector byteSegments = new Vector(1); Mode mode; do { // While still another segment to read... if (bits.available() < 4) { // OK, assume we're done. Really, a TERMINATOR mode should have been recorded here mode = Mode.TERMINATOR; } else { try { mode = Mode.forBits(bits.readBits(4)); // mode is encoded by 4 bits } catch (IllegalArgumentException iae) { throw ReaderException.getInstance(); } } if (!mode.equals(Mode.TERMINATOR)) { if (mode.equals(Mode.FNC1_FIRST_POSITION) || mode.equals(Mode.FNC1_SECOND_POSITION)) { // We do little with FNC1 except alter the parsed result a bit according to the spec fc1InEffect = true; } else if (mode.equals(Mode.STRUCTURED_APPEND)) { // not really supported; all we do is ignore it // Read next 8 bits (symbol sequence #) and 8 bits (parity data), then continue bits.readBits(16); } else if (mode.equals(Mode.ECI)) { // Count doesn't apply to ECI int value = parseECIValue(bits); currentCharacterSetECI = CharacterSetECI.getCharacterSetECIByValue(value); if (currentCharacterSetECI == null) { throw ReaderException.getInstance(); } } else { // How many characters will follow, encoded in this mode? int count = bits.readBits(mode.getCharacterCountBits(version)); if (mode.equals(Mode.NUMERIC)) { decodeNumericSegment(bits, result, count); } else if (mode.equals(Mode.ALPHANUMERIC)) { decodeAlphanumericSegment(bits, result, count, fc1InEffect); } else if (mode.equals(Mode.BYTE)) { decodeByteSegment(bits, result, count, currentCharacterSetECI, byteSegments); } else if (mode.equals(Mode.KANJI)) { decodeKanjiSegment(bits, result, count); } else { throw ReaderException.getInstance(); } } } } while (!mode.equals(Mode.TERMINATOR)); return new DecoderResult(bytes, result.toString(), byteSegments.isEmpty() ? null : byteSegments); } private static void decodeKanjiSegment(BitSource bits, StringBuffer result, int count) throws ReaderException { // Each character will require 2 bytes. Read the characters as 2-byte pairs // and decode as Shift_JIS afterwards byte[] buffer = new byte[2 * count]; int offset = 0; while (count > 0) { // Each 13 bits encodes a 2-byte character int twoBytes = bits.readBits(13); int assembledTwoBytes = ((twoBytes / 0x0C0) << 8) | (twoBytes % 0x0C0); if (assembledTwoBytes < 0x01F00) { // In the 0x8140 to 0x9FFC range assembledTwoBytes += 0x08140; } else { // In the 0xE040 to 0xEBBF range assembledTwoBytes += 0x0C140; } buffer[offset] = (byte) (assembledTwoBytes >> 8); buffer[offset + 1] = (byte) assembledTwoBytes; offset += 2; count--; } // Shift_JIS may not be supported in some environments: // *OG* result.append(bytesToString(buffer)); } private static void decodeByteSegment(BitSource bits, StringBuffer result, int count, CharacterSetECI currentCharacterSetECI, Vector byteSegments) throws ReaderException { byte[] readBytes = new byte[count]; if (count << 3 > bits.available()) { throw ReaderException.getInstance(); } for (int i = 0; i < count; i++) { readBytes[i] = (byte) bits.readBits(8); } String encoding; if (currentCharacterSetECI == null) { // The spec isn't clear on this mode; see // section 6.4.5: t does not say which encoding to assuming // upon decoding. I have seen ISO-8859-1 used as well as // Shift_JIS -- without anything like an ECI designator to // give a hint. encoding = guessEncoding(readBytes); } else { encoding = currentCharacterSetECI.getEncodingName(); } // *OG* result.append(bytesToString(readBytes)); byteSegments.addElement(readBytes); } private static String bytesToString(byte[] bytes) { String k=""; for(int i = 0; i < bytes.length; i++) { k = k + (char)bytes[i]; } return k; } private static void decodeAlphanumericSegment(BitSource bits, StringBuffer result, int count, boolean fc1InEffect) { // Read two characters at a time int start = result.length(); while (count > 1) { int nextTwoCharsBits = bits.readBits(11); result.append(ALPHANUMERIC_CHARS[nextTwoCharsBits / 45]); result.append(ALPHANUMERIC_CHARS[nextTwoCharsBits % 45]); count -= 2; } if (count == 1) { // special case: one character left result.append(ALPHANUMERIC_CHARS[bits.readBits(6)]); } // See section 6.4.8.1, 6.4.8.2 if (fc1InEffect) { // We need to massage the result a bit if in an FNC1 mode: for (int i = start; i < result.length(); i++) { if (result.charAt(i) == '%') { if (i < result.length() - 1 && result.charAt(i + 1) == '%') { // %% is rendered as % result.deleteCharAt(i + 1); } else { // In alpha mode, % should be converted to FNC1 separator 0x1D result.setCharAt(i, (char) 0x1D); } } } } } private static void decodeNumericSegment(BitSource bits, StringBuffer result, int count) throws ReaderException { // Read three digits at a time while (count >= 3) { // Each 10 bits encodes three digits int threeDigitsBits = bits.readBits(10); if (threeDigitsBits >= 1000) { throw ReaderException.getInstance(); } result.append(ALPHANUMERIC_CHARS[threeDigitsBits / 100]); result.append(ALPHANUMERIC_CHARS[(threeDigitsBits / 10) % 10]); result.append(ALPHANUMERIC_CHARS[threeDigitsBits % 10]); count -= 3; } if (count == 2) { // Two digits left over to read, encoded in 7 bits int twoDigitsBits = bits.readBits(7); if (twoDigitsBits >= 100) { throw ReaderException.getInstance(); } result.append(ALPHANUMERIC_CHARS[twoDigitsBits / 10]); result.append(ALPHANUMERIC_CHARS[twoDigitsBits % 10]); } else if (count == 1) { // One digit left over to read int digitBits = bits.readBits(4); if (digitBits >= 10) { throw ReaderException.getInstance(); } result.append(ALPHANUMERIC_CHARS[digitBits]); } } private static String guessEncoding(byte[] bytes) { if (ASSUME_SHIFT_JIS) { return SHIFT_JIS; } // Does it start with the UTF-8 byte order mark? then guess it's UTF-8 if (bytes.length > 3 && bytes[0] == (byte) 0xEF && bytes[1] == (byte) 0xBB && bytes[2] == (byte) 0xBF) { return UTF8; } // For now, merely tries to distinguish ISO-8859-1, UTF-8 and Shift_JIS, // which should be by far the most common encodings. ISO-8859-1 // should not have bytes in the 0x80 - 0x9F range, while Shift_JIS // uses this as a first byte of a two-byte character. If we see this // followed by a valid second byte in Shift_JIS, assume it is Shift_JIS. // If we see something else in that second byte, we'll make the risky guess // that it's UTF-8. int length = bytes.length; boolean canBeISO88591 = true; boolean canBeShiftJIS = true; boolean sawDoubleByteStart = false; int maybeSingleByteKatakanaCount = 0; boolean sawLatin1Supplement = false; boolean lastWasPossibleDoubleByteStart = false; for (int i = 0; i < length && (canBeISO88591 || canBeShiftJIS); i++) { int value = bytes[i] & 0xFF; if (value == 0xC2 || value == 0xC3 && i < length - 1) { // This is really a poor hack. The slightly more exotic characters people might want to put in // a QR Code, by which I mean the Latin-1 supplement characters (e.g. u-umlaut) have encodings // that start with 0xC2 followed by [0xA0,0xBF], or start with 0xC3 followed by [0x80,0xBF]. int nextValue = bytes[i + 1] & 0xFF; if (nextValue <= 0xBF && ((value == 0xC2 && nextValue >= 0xA0) || (value == 0xC3 && nextValue >= 0x80))) { sawLatin1Supplement = true; } } if (value >= 0x7F && value <= 0x9F) { canBeISO88591 = false; } if (value >= 0xA1 && value <= 0xDF) { // count the number of characters that might be a Shift_JIS single-byte Katakana character if (!lastWasPossibleDoubleByteStart) { maybeSingleByteKatakanaCount++; } } if (!lastWasPossibleDoubleByteStart && ((value >= 0xF0 && value <= 0xFF) || value == 0x80 || value == 0xA0)) { canBeShiftJIS = false; } if (((value >= 0x81 && value <= 0x9F) || (value >= 0xE0 && value <= 0xEF)) && i < length - 1) { // These start double-byte characters in Shift_JIS. Let's see if it's followed by a valid // second byte. sawDoubleByteStart = true; if (lastWasPossibleDoubleByteStart) { // If we just checked this and the last byte for being a valid double-byte // char, don't check starting on this byte. If this and the last byte // formed a valid pair, then this shouldn't be checked to see if it starts // a double byte pair of course. lastWasPossibleDoubleByteStart = false; } else { // ... otherwise do check to see if this plus the next byte form a valid // double byte pair encoding a character. lastWasPossibleDoubleByteStart = true; int nextValue = bytes[i + 1] & 0xFF; if (nextValue < 0x40 || nextValue > 0xFC) { canBeShiftJIS = false; } // There is some conflicting information out there about which bytes can follow which in // double-byte Shift_JIS characters. The rule above seems to be the one that matches practice. } } else { lastWasPossibleDoubleByteStart = false; } } // Distinguishing Shift_JIS and ISO-8859-1 can be a little tough. The crude heuristic is: // - If we saw // - at least one byte that starts a double-byte value (bytes that are rare in ISO-8859-1), or // - over 5% of bytes that could be single-byte Katakana (also rare in ISO-8859-1), // - and, saw no sequences that are invalid in Shift_JIS, then we conclude Shift_JIS if (canBeShiftJIS && (sawDoubleByteStart || 20 * maybeSingleByteKatakanaCount > length)) { return SHIFT_JIS; } // Otherwise, we default to ISO-8859-1 unless we know it can't be if (!sawLatin1Supplement && canBeISO88591) { return ISO88591; } // Otherwise, we take a wild guess with UTF-8 return UTF8; } private static int parseECIValue(BitSource bits) { int firstByte = bits.readBits(8); if ((firstByte & 0x80) == 0) { // just one byte return firstByte & 0x7F; } else if ((firstByte & 0xC0) == 0x80) { // two bytes int secondByte = bits.readBits(8); return ((firstByte & 0x3F) << 8) | secondByte; } else if ((firstByte & 0xE0) == 0xC0) { // three bytes int secondThirdBytes = bits.readBits(16); return ((firstByte & 0x1F) << 16) | secondThirdBytes; } throw new IllegalArgumentException("Bad ECI bits starting with byte " + firstByte); } }
Java
/* * Copyright 2007 ZXing authors * * 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.onurgunduz.qrdec.client; import com.onurgunduz.qrdec.client.ReaderException; import com.onurgunduz.qrdec.client.BitMatrix; import com.onurgunduz.qrdec.client.DecoderResult; import com.onurgunduz.qrdec.client.GF256; import com.onurgunduz.qrdec.client.ReedSolomonDecoder; import com.onurgunduz.qrdec.client.ReedSolomonException; /** * <p>The main class which implements QR Code decoding -- as opposed to locating and extracting * the QR Code from an image.</p> * * @author Sean Owen */ public final class Decoder { private final ReedSolomonDecoder rsDecoder; public Decoder() { rsDecoder = new ReedSolomonDecoder(GF256.QR_CODE_FIELD); } /** * <p>Convenience method that can decode a QR Code represented as a 2D array of booleans. * "true" is taken to mean a black module.</p> * * @param image booleans representing white/black QR Code modules * @return text and bytes encoded within the QR Code * @throws ReaderException if the QR Code cannot be decoded */ public DecoderResult decode(boolean[][] image) throws ReaderException { int dimension = image.length; BitMatrix bits = new BitMatrix(dimension); for (int i = 0; i < dimension; i++) { for (int j = 0; j < dimension; j++) { if (image[i][j]) { bits.set(i, j); } } } return decode(bits); } /** * <p>Decodes a QR Code represented as a {@link BitMatrix}. A 1 or "true" is taken to mean a black module.</p> * * @param bits booleans representing white/black QR Code modules * @return text and bytes encoded within the QR Code * @throws ReaderException if the QR Code cannot be decoded */ public DecoderResult decode(BitMatrix bits) throws ReaderException { // Construct a parser and read version, error-correction level BitMatrixParser parser = new BitMatrixParser(bits); Version version = parser.readVersion(); ErrorCorrectionLevel ecLevel = parser.readFormatInformation().getErrorCorrectionLevel(); // Read codewords byte[] codewords = parser.readCodewords(); // Separate into data blocks DataBlock[] dataBlocks = DataBlock.getDataBlocks(codewords, version, ecLevel); // Count total number of data bytes int totalBytes = 0; for (int i = 0; i < dataBlocks.length; i++) { totalBytes += dataBlocks[i].getNumDataCodewords(); } byte[] resultBytes = new byte[totalBytes]; int resultOffset = 0; // Error-correct and copy data blocks together into a stream of bytes for (int j = 0; j < dataBlocks.length; j++) { DataBlock dataBlock = dataBlocks[j]; byte[] codewordBytes = dataBlock.getCodewords(); int numDataCodewords = dataBlock.getNumDataCodewords(); correctErrors(codewordBytes, numDataCodewords); for (int i = 0; i < numDataCodewords; i++) { resultBytes[resultOffset++] = codewordBytes[i]; } } // Decode the contents of that stream of bytes return DecodedBitStreamParser.decode(resultBytes, version); } /** * <p>Given data and error-correction codewords received, possibly corrupted by errors, attempts to * correct the errors in-place using Reed-Solomon error correction.</p> * * @param codewordBytes data and error correction codewords * @param numDataCodewords number of codewords that are data bytes * @throws ReaderException if error correction fails */ private void correctErrors(byte[] codewordBytes, int numDataCodewords) throws ReaderException { int numCodewords = codewordBytes.length; // First read into an array of ints int[] codewordsInts = new int[numCodewords]; for (int i = 0; i < numCodewords; i++) { codewordsInts[i] = codewordBytes[i] & 0xFF; } int numECCodewords = codewordBytes.length - numDataCodewords; try { rsDecoder.decode(codewordsInts, numECCodewords); } catch (ReedSolomonException rse) { throw ReaderException.getInstance(); } // Copy back into array of bytes -- only need to worry about the bytes that were data // We don't care about errors in the error-correction codewords for (int i = 0; i < numDataCodewords; i++) { codewordBytes[i] = (byte) codewordsInts[i]; } } }
Java
package com.onurgunduz.qrdec.client; import com.google.gwt.core.client.EntryPoint; import com.google.gwt.user.client.ui.RootPanel; import com.google.gwt.user.client.ui.HTML; import com.onurgunduz.qrdec.client.BitMatrix;; public class Qrdec implements EntryPoint { private static void decode(int[][] source) throws ReaderException { int dimension = source.length; BitMatrix bits = new BitMatrix(dimension); for( int k = 0; k < dimension; k++ ) { for( int v = 0; v < dimension; v++) { if(source != null) { if(source[k][v] == 1) { bits.set(k, v); } } } } Decoder decoder = new Decoder(); DecoderResult decoderResult = decoder.decode(bits); String decodedString = decoderResult.getText(); RootPanel.get("resultView").clear(); RootPanel.get("resultView").add(new HTML("<h2>Decoded string:</h2>")); RootPanel.get("resultView").add(new HTML("<p class='decoded'>" + decodedString +"</p>")); } private native void publish() /*-{ $wnd.decode = @com.onurgunduz.qrdec.client.Qrdec::decode([[I); }-*/; public void onModuleLoad() { publish(); } }
Java
/* * Copyright 2007 ZXing authors * * 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.onurgunduz.qrdec.client; /** * <p>See ISO 18004:2006, 6.5.1. This enum encapsulates the four error correction levels * defined by the QR code standard.</p> * * @author Sean Owen */ public final class ErrorCorrectionLevel { // No, we can't use an enum here. J2ME doesn't support it. /** * L = ~7% correction */ public static final ErrorCorrectionLevel L = new ErrorCorrectionLevel(0, 0x01, "L"); /** * M = ~15% correction */ public static final ErrorCorrectionLevel M = new ErrorCorrectionLevel(1, 0x00, "M"); /** * Q = ~25% correction */ public static final ErrorCorrectionLevel Q = new ErrorCorrectionLevel(2, 0x03, "Q"); /** * H = ~30% correction */ public static final ErrorCorrectionLevel H = new ErrorCorrectionLevel(3, 0x02, "H"); private static final ErrorCorrectionLevel[] FOR_BITS = {M, L, H, Q}; private final int ordinal; private final int bits; private final String name; private ErrorCorrectionLevel(int ordinal, int bits, String name) { this.ordinal = ordinal; this.bits = bits; this.name = name; } public int ordinal() { return ordinal; } public int getBits() { return bits; } public String getName() { return name; } public String toString() { return name; } /** * @param bits int containing the two bits encoding a QR Code's error correction level * @return {@link ErrorCorrectionLevel} representing the encoded error correction level */ public static ErrorCorrectionLevel forBits(int bits) { if (bits < 0 || bits >= FOR_BITS.length) { throw new IllegalArgumentException(); } return FOR_BITS[bits]; } }
Java
/* * Copyright 2007 ZXing authors * * 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.onurgunduz.qrdec.client; /** * <p>Implements Reed-Solomon decoding, as the name implies.</p> * * <p>The algorithm will not be explained here, but the following references were helpful * in creating this implementation:</p> * * <ul> * <li>Bruce Maggs. * <a href="http://www.cs.cmu.edu/afs/cs.cmu.edu/project/pscico-guyb/realworld/www/rs_decode.ps"> * "Decoding Reed-Solomon Codes"</a> (see discussion of Forney's Formula)</li> * <li>J.I. Hall. <a href="www.mth.msu.edu/~jhall/classes/codenotes/GRS.pdf"> * "Chapter 5. Generalized Reed-Solomon Codes"</a> * (see discussion of Euclidean algorithm)</li> * </ul> * * <p>Much credit is due to William Rucklidge since portions of this code are an indirect * port of his C++ Reed-Solomon implementation.</p> * * @author Sean Owen * @author William Rucklidge * @author sanfordsquires */ public final class ReedSolomonDecoder { private final GF256 field; public ReedSolomonDecoder(GF256 field) { this.field = field; } /** * <p>Decodes given set of received codewords, which include both data and error-correction * codewords. Really, this means it uses Reed-Solomon to detect and correct errors, in-place, * in the input.</p> * * @param received data and error-correction codewords * @param twoS number of error-correction codewords available * @throws ReedSolomonException if decoding fails for any reason */ public void decode(int[] received, int twoS) throws ReedSolomonException { GF256Poly poly = new GF256Poly(field, received); int[] syndromeCoefficients = new int[twoS]; boolean dataMatrix = field.equals(GF256.DATA_MATRIX_FIELD); boolean noError = true; for (int i = 0; i < twoS; i++) { // Thanks to sanfordsquires for this fix: int eval = poly.evaluateAt(field.exp(dataMatrix ? i + 1 : i)); syndromeCoefficients[syndromeCoefficients.length - 1 - i] = eval; if (eval != 0) { noError = false; } } if (noError) { return; } GF256Poly syndrome = new GF256Poly(field, syndromeCoefficients); GF256Poly[] sigmaOmega = runEuclideanAlgorithm(field.buildMonomial(twoS, 1), syndrome, twoS); GF256Poly sigma = sigmaOmega[0]; GF256Poly omega = sigmaOmega[1]; int[] errorLocations = findErrorLocations(sigma); int[] errorMagnitudes = findErrorMagnitudes(omega, errorLocations, dataMatrix); for (int i = 0; i < errorLocations.length; i++) { int position = received.length - 1 - field.log(errorLocations[i]); if (position < 0) { throw new ReedSolomonException("Bad error location"); } received[position] = GF256.addOrSubtract(received[position], errorMagnitudes[i]); } } private GF256Poly[] runEuclideanAlgorithm(GF256Poly a, GF256Poly b, int R) throws ReedSolomonException { // Assume a's degree is >= b's if (a.getDegree() < b.getDegree()) { GF256Poly temp = a; a = b; b = temp; } GF256Poly rLast = a; GF256Poly r = b; GF256Poly sLast = field.getOne(); GF256Poly s = field.getZero(); GF256Poly tLast = field.getZero(); GF256Poly t = field.getOne(); // Run Euclidean algorithm until r's degree is less than R/2 while (r.getDegree() >= R / 2) { GF256Poly rLastLast = rLast; GF256Poly sLastLast = sLast; GF256Poly tLastLast = tLast; rLast = r; sLast = s; tLast = t; // Divide rLastLast by rLast, with quotient in q and remainder in r if (rLast.isZero()) { // Oops, Euclidean algorithm already terminated? throw new ReedSolomonException("r_{i-1} was zero"); } r = rLastLast; GF256Poly q = field.getZero(); int denominatorLeadingTerm = rLast.getCoefficient(rLast.getDegree()); int dltInverse = field.inverse(denominatorLeadingTerm); while (r.getDegree() >= rLast.getDegree() && !r.isZero()) { int degreeDiff = r.getDegree() - rLast.getDegree(); int scale = field.multiply(r.getCoefficient(r.getDegree()), dltInverse); q = q.addOrSubtract(field.buildMonomial(degreeDiff, scale)); r = r.addOrSubtract(rLast.multiplyByMonomial(degreeDiff, scale)); } s = q.multiply(sLast).addOrSubtract(sLastLast); t = q.multiply(tLast).addOrSubtract(tLastLast); } int sigmaTildeAtZero = t.getCoefficient(0); if (sigmaTildeAtZero == 0) { throw new ReedSolomonException("sigmaTilde(0) was zero"); } int inverse = field.inverse(sigmaTildeAtZero); GF256Poly sigma = t.multiply(inverse); GF256Poly omega = r.multiply(inverse); return new GF256Poly[]{sigma, omega}; } private int[] findErrorLocations(GF256Poly errorLocator) throws ReedSolomonException { // This is a direct application of Chien's search int numErrors = errorLocator.getDegree(); if (numErrors == 1) { // shortcut return new int[] { errorLocator.getCoefficient(1) }; } int[] result = new int[numErrors]; int e = 0; for (int i = 1; i < 256 && e < numErrors; i++) { if (errorLocator.evaluateAt(i) == 0) { result[e] = field.inverse(i); e++; } } if (e != numErrors) { throw new ReedSolomonException("Error locator degree does not match number of roots"); } return result; } private int[] findErrorMagnitudes(GF256Poly errorEvaluator, int[] errorLocations, boolean dataMatrix) { // This is directly applying Forney's Formula int s = errorLocations.length; int[] result = new int[s]; for (int i = 0; i < s; i++) { int xiInverse = field.inverse(errorLocations[i]); int denominator = 1; for (int j = 0; j < s; j++) { if (i != j) { denominator = field.multiply(denominator, GF256.addOrSubtract(1, field.multiply(errorLocations[j], xiInverse))); } } result[i] = field.multiply(errorEvaluator.evaluateAt(xiInverse), field.inverse(denominator)); // Thanks to sanfordsquires for this fix: if (dataMatrix) { result[i] = field.multiply(result[i], xiInverse); } } return result; } }
Java
/* * Copyright 2007 ZXing authors * * 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.onurgunduz.qrdec.client; /** * <p>Encapsulates a block of data within a QR Code. QR Codes may split their data into * multiple blocks, each of which is a unit of data and error-correction codewords. Each * is represented by an instance of this class.</p> * * @author Sean Owen */ final class DataBlock { private final int numDataCodewords; private final byte[] codewords; private DataBlock(int numDataCodewords, byte[] codewords) { this.numDataCodewords = numDataCodewords; this.codewords = codewords; } /** * <p>When QR Codes use multiple data blocks, they are actually interleaved. * That is, the first byte of data block 1 to n is written, then the second bytes, and so on. This * method will separate the data into original blocks.</p> * * @param rawCodewords bytes as read directly from the QR Code * @param version version of the QR Code * @param ecLevel error-correction level of the QR Code * @return {@link DataBlock}s containing original bytes, "de-interleaved" from representation in the * QR Code */ static DataBlock[] getDataBlocks(byte[] rawCodewords, Version version, ErrorCorrectionLevel ecLevel) { if (rawCodewords.length != version.getTotalCodewords()) { throw new IllegalArgumentException(); } // Figure out the number and size of data blocks used by this version and // error correction level Version.ECBlocks ecBlocks = version.getECBlocksForLevel(ecLevel); // First count the total number of data blocks int totalBlocks = 0; Version.ECB[] ecBlockArray = ecBlocks.getECBlocks(); for (int i = 0; i < ecBlockArray.length; i++) { totalBlocks += ecBlockArray[i].getCount(); } // Now establish DataBlocks of the appropriate size and number of data codewords DataBlock[] result = new DataBlock[totalBlocks]; int numResultBlocks = 0; for (int j = 0; j < ecBlockArray.length; j++) { Version.ECB ecBlock = ecBlockArray[j]; for (int i = 0; i < ecBlock.getCount(); i++) { int numDataCodewords = ecBlock.getDataCodewords(); int numBlockCodewords = ecBlocks.getECCodewordsPerBlock() + numDataCodewords; result[numResultBlocks++] = new DataBlock(numDataCodewords, new byte[numBlockCodewords]); } } // All blocks have the same amount of data, except that the last n // (where n may be 0) have 1 more byte. Figure out where these start. int shorterBlocksTotalCodewords = result[0].codewords.length; int longerBlocksStartAt = result.length - 1; while (longerBlocksStartAt >= 0) { int numCodewords = result[longerBlocksStartAt].codewords.length; if (numCodewords == shorterBlocksTotalCodewords) { break; } longerBlocksStartAt--; } longerBlocksStartAt++; int shorterBlocksNumDataCodewords = shorterBlocksTotalCodewords - ecBlocks.getECCodewordsPerBlock(); // The last elements of result may be 1 element longer; // first fill out as many elements as all of them have int rawCodewordsOffset = 0; for (int i = 0; i < shorterBlocksNumDataCodewords; i++) { for (int j = 0; j < numResultBlocks; j++) { result[j].codewords[i] = rawCodewords[rawCodewordsOffset++]; } } // Fill out the last data block in the longer ones for (int j = longerBlocksStartAt; j < numResultBlocks; j++) { result[j].codewords[shorterBlocksNumDataCodewords] = rawCodewords[rawCodewordsOffset++]; } // Now add in error correction blocks int max = result[0].codewords.length; for (int i = shorterBlocksNumDataCodewords; i < max; i++) { for (int j = 0; j < numResultBlocks; j++) { int iOffset = j < longerBlocksStartAt ? i : i + 1; result[j].codewords[iOffset] = rawCodewords[rawCodewordsOffset++]; } } return result; } int getNumDataCodewords() { return numDataCodewords; } byte[] getCodewords() { return codewords; } }
Java
/* * Copyright 2008 ZXing authors * * 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.onurgunduz.qrdec.client; // import com.google.gwt.emul.java.util.*; import java.util.HashMap; /** * Encapsulates a Character Set ECI, according to "Extended Channel Interpretations" 5.3.1.1 * of ISO 18004. * * @author Sean Owen */ public final class CharacterSetECI extends ECI { private static HashMap VALUE_TO_ECI; private static HashMap NAME_TO_ECI; private static void initialize() { VALUE_TO_ECI = new HashMap(29); NAME_TO_ECI = new HashMap(29); // TODO figure out if these values are even right! addCharacterSet(0, "Cp437"); addCharacterSet(1, new String[] {"ISO8859_1", "ISO-8859-1"}); addCharacterSet(2, "Cp437"); addCharacterSet(3, new String[] {"ISO8859_1", "ISO-8859-1"}); addCharacterSet(4, "ISO8859_2"); addCharacterSet(5, "ISO8859_3"); addCharacterSet(6, "ISO8859_4"); addCharacterSet(7, "ISO8859_5"); addCharacterSet(8, "ISO8859_6"); addCharacterSet(9, "ISO8859_7"); addCharacterSet(10, "ISO8859_8"); addCharacterSet(11, "ISO8859_9"); addCharacterSet(12, "ISO8859_10"); addCharacterSet(13, "ISO8859_11"); addCharacterSet(15, "ISO8859_13"); addCharacterSet(16, "ISO8859_14"); addCharacterSet(17, "ISO8859_15"); addCharacterSet(18, "ISO8859_16"); addCharacterSet(20, new String[] {"SJIS", "Shift_JIS"}); } private final String encodingName; private CharacterSetECI(int value, String encodingName) { super(value); this.encodingName = encodingName; } public String getEncodingName() { return encodingName; } private static void addCharacterSet(int value, String encodingName) { CharacterSetECI eci = new CharacterSetECI(value, encodingName); // VALUE_TO_ECI.put(new Integer(value), eci); // NAME_TO_ECI.put(encodingName, eci); } private static void addCharacterSet(int value, String[] encodingNames) { // CharacterSetECI eci = new CharacterSetECI(value, encodingNames[0]); // VALUE_TO_ECI.put(new Integer(value), eci); // for (int i = 0; i < encodingNames.length; i++) { // NAME_TO_ECI.put(encodingNames[i], eci); // } } /** * @param value character set ECI value * @return {@link CharacterSetECI} representing ECI of given value, or null if it is legal but unsupported * @throws IllegalArgumentException if ECI value is invalid */ public static CharacterSetECI getCharacterSetECIByValue(int value) { if (VALUE_TO_ECI == null) { initialize(); } if (value < 0 || value >= 900) { throw new IllegalArgumentException("Bad ECI value: " + value); } return (CharacterSetECI) VALUE_TO_ECI.get(new Integer(value)); } /** * @param name character set ECI encoding name * @return {@link CharacterSetECI} representing ECI for character encoding, or null if it is legal but unsupported */ public static CharacterSetECI getCharacterSetECIByName(String name) { if (NAME_TO_ECI == null) { initialize(); } return (CharacterSetECI) NAME_TO_ECI.get(name); } }
Java
/* * Copyright 2007 ZXing authors * * 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.onurgunduz.qrdec.client; /** * <p>Thrown when an exception occurs during Reed-Solomon decoding, such as when * there are too many errors to correct.</p> * * @author Sean Owen */ public final class ReedSolomonException extends Exception { public ReedSolomonException(String message) { super(message); } }
Java
/* * Copyright 2007 ZXing authors * * 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.onurgunduz.qrdec.client; import java.util.Vector; /** * <p>Encapsulates the result of decoding a matrix of bits. This typically * applies to 2D barcode formats. For now it contains the raw bytes obtained, * as well as a String interpretation of those bytes, if applicable.</p> * * @author Sean Owen */ public final class DecoderResult { private final byte[] rawBytes; private final String text; private final Vector byteSegments; public DecoderResult(byte[] rawBytes, String text, Vector byteSegments) { if (rawBytes == null && text == null) { throw new IllegalArgumentException(); } this.rawBytes = rawBytes; this.text = text; this.byteSegments = byteSegments; } public byte[] getRawBytes() { return rawBytes; } public String getText() { return text; } public Vector getByteSegments() { return byteSegments; } }
Java
/* * Copyright 2007 ZXing authors * * 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.onurgunduz.qrdec.client; import com.onurgunduz.qrdec.client.ReaderException; import com.onurgunduz.qrdec.client.BitMatrix; /** * @author Sean Owen */ final class BitMatrixParser { private final BitMatrix bitMatrix; private Version parsedVersion; private FormatInformation parsedFormatInfo; /** * @param bitMatrix {@link BitMatrix} to parse * @throws ReaderException if dimension is not >= 21 and 1 mod 4 */ BitMatrixParser(BitMatrix bitMatrix) throws ReaderException { int dimension = bitMatrix.getDimension(); if (dimension < 21 || (dimension & 0x03) != 1) { throw ReaderException.getInstance(); } this.bitMatrix = bitMatrix; } /** * <p>Reads format information from one of its two locations within the QR Code.</p> * * @return {@link FormatInformation} encapsulating the QR Code's format info * @throws ReaderException if both format information locations cannot be parsed as * the valid encoding of format information */ FormatInformation readFormatInformation() throws ReaderException { if (parsedFormatInfo != null) { return parsedFormatInfo; } // Read top-left format info bits int formatInfoBits = 0; for (int j = 0; j < 6; j++) { formatInfoBits = copyBit(8, j, formatInfoBits); } // .. and skip a bit in the timing pattern ... formatInfoBits = copyBit(8, 7, formatInfoBits); formatInfoBits = copyBit(8, 8, formatInfoBits); formatInfoBits = copyBit(7, 8, formatInfoBits); // .. and skip a bit in the timing pattern ... for (int i = 5; i >= 0; i--) { formatInfoBits = copyBit(i, 8, formatInfoBits); } parsedFormatInfo = FormatInformation.decodeFormatInformation(formatInfoBits); if (parsedFormatInfo != null) { return parsedFormatInfo; } // Hmm, failed. Try the top-right/bottom-left pattern int dimension = bitMatrix.getDimension(); formatInfoBits = 0; int iMin = dimension - 8; for (int i = dimension - 1; i >= iMin; i--) { formatInfoBits = copyBit(i, 8, formatInfoBits); } for (int j = dimension - 7; j < dimension; j++) { formatInfoBits = copyBit(8, j, formatInfoBits); } parsedFormatInfo = FormatInformation.decodeFormatInformation(formatInfoBits); if (parsedFormatInfo != null) { return parsedFormatInfo; } throw ReaderException.getInstance(); } /** * <p>Reads version information from one of its two locations within the QR Code.</p> * * @return {@link Version} encapsulating the QR Code's version * @throws ReaderException if both version information locations cannot be parsed as * the valid encoding of version information */ Version readVersion() throws ReaderException { if (parsedVersion != null) { return parsedVersion; } int dimension = bitMatrix.getDimension(); int provisionalVersion = (dimension - 17) >> 2; if (provisionalVersion <= 6) { return Version.getVersionForNumber(provisionalVersion); } // Read top-right version info: 3 wide by 6 tall int versionBits = 0; for (int i = 5; i >= 0; i--) { int jMin = dimension - 11; for (int j = dimension - 9; j >= jMin; j--) { versionBits = copyBit(i, j, versionBits); } } parsedVersion = Version.decodeVersionInformation(versionBits); if (parsedVersion != null) { return parsedVersion; } // Hmm, failed. Try bottom left: 6 wide by 3 tall versionBits = 0; for (int j = 5; j >= 0; j--) { int iMin = dimension - 11; for (int i = dimension - 11; i >= iMin; i--) { versionBits = copyBit(i, j, versionBits); } } parsedVersion = Version.decodeVersionInformation(versionBits); if (parsedVersion != null) { return parsedVersion; } throw ReaderException.getInstance(); } private int copyBit(int i, int j, int versionBits) { return bitMatrix.get(i, j) ? (versionBits << 1) | 0x1 : versionBits << 1; } /** * <p>Reads the bits in the {@link BitMatrix} representing the finder pattern in the * correct order in order to reconstitute the codewords bytes contained within the * QR Code.</p> * * @return bytes encoded within the QR Code * @throws ReaderException if the exact number of bytes expected is not read */ byte[] readCodewords() throws ReaderException { FormatInformation formatInfo = readFormatInformation(); Version version = readVersion(); // Get the data mask for the format used in this QR Code. This will exclude // some bits from reading as we wind through the bit matrix. DataMask dataMask = DataMask.forReference((int) formatInfo.getDataMask()); int dimension = bitMatrix.getDimension(); dataMask.unmaskBitMatrix(bitMatrix.getBits(), dimension); BitMatrix functionPattern = version.buildFunctionPattern(); boolean readingUp = true; byte[] result = new byte[version.getTotalCodewords()]; int resultOffset = 0; int currentByte = 0; int bitsRead = 0; // Read columns in pairs, from right to left for (int j = dimension - 1; j > 0; j -= 2) { if (j == 6) { // Skip whole column with vertical alignment pattern; // saves time and makes the other code proceed more cleanly j--; } // Read alternatingly from bottom to top then top to bottom for (int count = 0; count < dimension; count++) { int i = readingUp ? dimension - 1 - count : count; for (int col = 0; col < 2; col++) { // Ignore bits covered by the function pattern if (!functionPattern.get(i, j - col)) { // Read a bit bitsRead++; currentByte <<= 1; if (bitMatrix.get(i, j - col)) { currentByte |= 1; } // If we've made a whole byte, save it off if (bitsRead == 8) { result[resultOffset++] = (byte) currentByte; bitsRead = 0; currentByte = 0; } } } } readingUp ^= true; // readingUp = !readingUp; // switch directions } if (resultOffset != version.getTotalCodewords()) { throw ReaderException.getInstance(); } return result; } }
Java
/* * Copyright 2007 ZXing authors * * 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.onurgunduz.qrdec.client; /** * <p>See ISO 18004:2006, 6.4.1, Tables 2 and 3. This enum encapsulates the various modes in which * data can be encoded to bits in the QR code standard.</p> * * @author Sean Owen */ public final class Mode { // No, we can't use an enum here. J2ME doesn't support it. public static final Mode TERMINATOR = new Mode(new int[]{0, 0, 0}, 0x00, "TERMINATOR"); // Not really a mode... public static final Mode NUMERIC = new Mode(new int[]{10, 12, 14}, 0x01, "NUMERIC"); public static final Mode ALPHANUMERIC = new Mode(new int[]{9, 11, 13}, 0x02, "ALPHANUMERIC"); public static final Mode STRUCTURED_APPEND = new Mode(new int[]{0, 0, 0}, 0x03, "STRUCTURED_APPEND"); // Not supported public static final Mode BYTE = new Mode(new int[]{8, 16, 16}, 0x04, "BYTE"); public static final Mode ECI = new Mode(null, 0x07, "ECI"); // character counts don't apply public static final Mode KANJI = new Mode(new int[]{8, 10, 12}, 0x08, "KANJI"); public static final Mode FNC1_FIRST_POSITION = new Mode(null, 0x05, "FNC1_FIRST_POSITION"); public static final Mode FNC1_SECOND_POSITION = new Mode(null, 0x09, "FNC1_SECOND_POSITION"); private final int[] characterCountBitsForVersions; private final int bits; private final String name; private Mode(int[] characterCountBitsForVersions, int bits, String name) { this.characterCountBitsForVersions = characterCountBitsForVersions; this.bits = bits; this.name = name; } /** * @param bits four bits encoding a QR Code data mode * @return {@link Mode} encoded by these bits * @throws IllegalArgumentException if bits do not correspond to a known mode */ public static Mode forBits(int bits) { switch (bits) { case 0x0: return TERMINATOR; case 0x1: return NUMERIC; case 0x2: return ALPHANUMERIC; case 0x3: return STRUCTURED_APPEND; case 0x4: return BYTE; case 0x5: return FNC1_FIRST_POSITION; case 0x7: return ECI; case 0x8: return KANJI; case 0x9: return FNC1_SECOND_POSITION; default: throw new IllegalArgumentException(); } } /** * @param version version in question * @return number of bits used, in this QR Code symbol {@link Version}, to encode the * count of characters that will follow encoded in this {@link Mode} */ public int getCharacterCountBits(Version version) { if (characterCountBitsForVersions == null) { throw new IllegalArgumentException("Character count doesn't apply to this mode"); } int number = version.getVersionNumber(); int offset; if (number <= 9) { offset = 0; } else if (number <= 26) { offset = 1; } else { offset = 2; } return characterCountBitsForVersions[offset]; } public int getBits() { return bits; } public String getName() { return name; } public String toString() { return name; } }
Java
/* * Copyright 2007 ZXing authors * * 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.onurgunduz.qrdec.client; /** * <p>Represents a polynomial whose coefficients are elements of GF(256). * Instances of this class are immutable.</p> * * <p>Much credit is due to William Rucklidge since portions of this code are an indirect * port of his C++ Reed-Solomon implementation.</p> * * @author Sean Owen */ final class GF256Poly { private final GF256 field; private final int[] coefficients; /** * @param field the {@link GF256} instance representing the field to use * to perform computations * @param coefficients coefficients as ints representing elements of GF(256), arranged * from most significant (highest-power term) coefficient to least significant * @throws IllegalArgumentException if argument is null or empty, * or if leading coefficient is 0 and this is not a * constant polynomial (that is, it is not the monomial "0") */ GF256Poly(GF256 field, int[] coefficients) { if (coefficients == null || coefficients.length == 0) { throw new IllegalArgumentException(); } this.field = field; int coefficientsLength = coefficients.length; if (coefficientsLength > 1 && coefficients[0] == 0) { // Leading term must be non-zero for anything except the constant polynomial "0" int firstNonZero = 1; while (firstNonZero < coefficientsLength && coefficients[firstNonZero] == 0) { firstNonZero++; } if (firstNonZero == coefficientsLength) { this.coefficients = field.getZero().coefficients; } else { this.coefficients = new int[coefficientsLength - firstNonZero]; System.arraycopy(coefficients, firstNonZero, this.coefficients, 0, this.coefficients.length); } } else { this.coefficients = coefficients; } } int[] getCoefficients() { return coefficients; } /** * @return degree of this polynomial */ int getDegree() { return coefficients.length - 1; } /** * @return true iff this polynomial is the monomial "0" */ boolean isZero() { return coefficients[0] == 0; } /** * @return coefficient of x^degree term in this polynomial */ int getCoefficient(int degree) { return coefficients[coefficients.length - 1 - degree]; } /** * @return evaluation of this polynomial at a given point */ int evaluateAt(int a) { if (a == 0) { // Just return the x^0 coefficient return getCoefficient(0); } int size = coefficients.length; if (a == 1) { // Just the sum of the coefficients int result = 0; for (int i = 0; i < size; i++) { result = GF256.addOrSubtract(result, coefficients[i]); } return result; } int result = coefficients[0]; for (int i = 1; i < size; i++) { result = GF256.addOrSubtract(field.multiply(a, result), coefficients[i]); } return result; } GF256Poly addOrSubtract(GF256Poly other) { if (!field.equals(other.field)) { throw new IllegalArgumentException("GF256Polys do not have same GF256 field"); } if (isZero()) { return other; } if (other.isZero()) { return this; } int[] smallerCoefficients = this.coefficients; int[] largerCoefficients = other.coefficients; if (smallerCoefficients.length > largerCoefficients.length) { int[] temp = smallerCoefficients; smallerCoefficients = largerCoefficients; largerCoefficients = temp; } int[] sumDiff = new int[largerCoefficients.length]; int lengthDiff = largerCoefficients.length - smallerCoefficients.length; // Copy high-order terms only found in higher-degree polynomial's coefficients System.arraycopy(largerCoefficients, 0, sumDiff, 0, lengthDiff); for (int i = lengthDiff; i < largerCoefficients.length; i++) { sumDiff[i] = GF256.addOrSubtract(smallerCoefficients[i - lengthDiff], largerCoefficients[i]); } return new GF256Poly(field, sumDiff); } GF256Poly multiply(GF256Poly other) { if (!field.equals(other.field)) { throw new IllegalArgumentException("GF256Polys do not have same GF256 field"); } if (isZero() || other.isZero()) { return field.getZero(); } int[] aCoefficients = this.coefficients; int aLength = aCoefficients.length; int[] bCoefficients = other.coefficients; int bLength = bCoefficients.length; int[] product = new int[aLength + bLength - 1]; for (int i = 0; i < aLength; i++) { int aCoeff = aCoefficients[i]; for (int j = 0; j < bLength; j++) { product[i + j] = GF256.addOrSubtract(product[i + j], field.multiply(aCoeff, bCoefficients[j])); } } return new GF256Poly(field, product); } GF256Poly multiply(int scalar) { if (scalar == 0) { return field.getZero(); } if (scalar == 1) { return this; } int size = coefficients.length; int[] product = new int[size]; for (int i = 0; i < size; i++) { product[i] = field.multiply(coefficients[i], scalar); } return new GF256Poly(field, product); } GF256Poly multiplyByMonomial(int degree, int coefficient) { if (degree < 0) { throw new IllegalArgumentException(); } if (coefficient == 0) { return field.getZero(); } int size = coefficients.length; int[] product = new int[size + degree]; for (int i = 0; i < size; i++) { product[i] = field.multiply(coefficients[i], coefficient); } return new GF256Poly(field, product); } GF256Poly[] divide(GF256Poly other) { if (!field.equals(other.field)) { throw new IllegalArgumentException("GF256Polys do not have same GF256 field"); } if (other.isZero()) { throw new IllegalArgumentException("Divide by 0"); } GF256Poly quotient = field.getZero(); GF256Poly remainder = this; int denominatorLeadingTerm = other.getCoefficient(other.getDegree()); int inverseDenominatorLeadingTerm = field.inverse(denominatorLeadingTerm); while (remainder.getDegree() >= other.getDegree() && !remainder.isZero()) { int degreeDifference = remainder.getDegree() - other.getDegree(); int scale = field.multiply(remainder.getCoefficient(remainder.getDegree()), inverseDenominatorLeadingTerm); GF256Poly term = other.multiplyByMonomial(degreeDifference, scale); GF256Poly iterationQuotient = field.buildMonomial(degreeDifference, scale); quotient = quotient.addOrSubtract(iterationQuotient); remainder = remainder.addOrSubtract(term); } return new GF256Poly[] { quotient, remainder }; } public String toString() { StringBuffer result = new StringBuffer(8 * getDegree()); for (int degree = getDegree(); degree >= 0; degree--) { int coefficient = getCoefficient(degree); if (coefficient != 0) { if (coefficient < 0) { result.append(" - "); coefficient = -coefficient; } else { if (result.length() > 0) { result.append(" + "); } } if (degree == 0 || coefficient != 1) { int alphaPower = field.log(coefficient); if (alphaPower == 0) { result.append('1'); } else if (alphaPower == 1) { result.append('a'); } else { result.append("a^"); result.append(alphaPower); } } if (degree != 0) { if (degree == 1) { result.append('x'); } else { result.append("x^"); result.append(degree); } } } } return result.toString(); } }
Java
package com.androidsaga; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Color; import android.util.Log; public class ConstantUtil{ public static final Integer NORMAL_SAGA = 0; public static final Integer GOODMAN_SAGA = 1; public static final Integer SCIENCE_SAGA = 2; public static final Integer OTAKU_SAGA = 3; public static final Integer UNCLE_SAGA = 4; public static final Integer GOKATERA_SAGA = 5; public static final Integer STATUS_DEAD = -1; public static final Integer STATUS_NORMAL = 0; public static final Integer STATUS_SLEEP = 1; public static final Integer STATUS_BATH = 2; public static final Integer STATUS_EXERCISE = 3; public static final Integer BLUE_THRSHOLD = 60; public static final Integer BLACK_THRESHOLD = 40; public static final Integer PRESENT_MOVE_STEP = 1; public static final Float SATISFACTION_DEFAULT = 80.f; public static final String ENCODING = "UTF-8"; public static final Float OTAKU_TIME = 7200.f; //2 hours public static final Float[] SATISFY_STEP = {-0.005f, 0.f, 0.05f, -0.005f}; public static final Float[] SICK_STEP = {0.0045f, -0.001f, -0.05f, -0.1f}; public static final Float[] HUNGRY_STEP = {0.005f, 0.0005f, 0.005f, 0.05f}; public static final Float[] DIRTY_STEP = {0.01f, 0.f, -0.2f, 0.05f}; public static final Float[] OTAKU_STEP = {0.005f, 0.005f, 0.005f, -0.1f}; public static final Integer AUTO_SLEEP_TIME = 1800; public static final Float DIRTY_AFFECT_SICK = 50.f; public static final Float HUNGRY_AFFECT_SICK = 50.f; public static final Float DIRTY_AFFECT_SATISFY = 40.f; public static final Float HUNGRY_AFFECT_SATISFY = 30.f; public static final Float SICK_AFFECT_SATISFY = 40.f; public static final String DATA_PATH = "saga.dat"; public static final String DEFAULT_SHARED_PREF = "com.androidsaga_preferences"; public static final String KEY_CHARACTOR = "charactor"; public static final String KEY_STATUS = "status"; public static final String KEY_TOTAL_TIME = "total_time"; public static final String KEY_LEVEL = "level"; public static final String KEY_SATISFY = "satisfy"; public static final String KEY_HUNGRY = "hungry"; public static final String KEY_DIRTY = "dirty"; public static final String KEY_SICK = "sick"; public static final String KEY_OTAKU = "otaku"; public static final String KEY_INELEGANT = "inelegant"; public static final String KEY_SCIENTIST = "scientist"; public static final String KEY_STRANGE = "strange"; public static final String KEY_IDLE_SECONDS = "idle_seconds"; public static final String KEY_AFTER_EXERCISE = "after_exercise"; public static final String KEY_SLEEP_SECONDS = "sleep_seconds"; public static final String KEY_IS_RUNNING = "is_running"; public static final String KEY_LAST_CLOSE = "last_close"; public static final Float FEED_VALUE = -15.f; public static final int[] NOTICE_ID = {1222, 1223, 1224}; public static int CUR_NOTICE = 0; public static final int NOTICE_DEAD = 1; public static final int NOTICE_HUNGRY = 2; public static final int NOTICE_SICK = 3; public static Bitmap scaleButtonBitmap(Context ctx, int resourceID, int scaleWidth, int scaleHeight){ Bitmap origBitmap = BitmapFactory.decodeResource( ctx.getResources(), resourceID); Log.i("saga", Integer.toString(scaleWidth)+","+ Integer.toString(origBitmap.getWidth())); if(scaleWidth >= origBitmap.getWidth()){ return origBitmap; } Bitmap scaledBitmap = Bitmap.createScaledBitmap(origBitmap, scaleWidth, scaleHeight, true); return scaledBitmap; } public static void setNotify(Context ctx, Data data){ final NotificationManager manager = (NotificationManager)ctx.getSystemService(Context.NOTIFICATION_SERVICE); SharedPreferences prefs = ctx.getSharedPreferences( ConstantUtil.DEFAULT_SHARED_PREF, Context.MODE_PRIVATE); if(!prefs.getBoolean(ctx.getString(R.string.allow_notify_key), true)){ return; } Notification notify = new Notification(); if(CUR_NOTICE != 0) manager.cancel(NOTICE_ID[CUR_NOTICE-1]); PendingIntent intent = PendingIntent.getActivity(ctx, 0, new Intent(ctx, SagaActivity.class), 0); notify.icon = R.drawable.homebtn; notify.when = System.currentTimeMillis(); notify.ledARGB = Color.RED; notify.ledOnMS = 1000; notify.flags = Notification.FLAG_SHOW_LIGHTS; if(data.status == ConstantUtil.STATUS_DEAD){ notify.ledOffMS = 0; notify.tickerText = ctx.getString(R.string.notify_dead); notify.setLatestEventInfo(ctx, ctx.getString(R.string.notify_title), ctx.getString(R.string.notify_dead), intent); CUR_NOTICE = NOTICE_DEAD; manager.notify(NOTICE_ID[CUR_NOTICE-1], notify); return; } if(data.hungry > 80){ notify.ledOffMS = 2000; notify.tickerText = ctx.getString(R.string.notify_hungry); notify.setLatestEventInfo(ctx, ctx.getString(R.string.notify_title), ctx.getString(R.string.notify_hungry), intent); CUR_NOTICE = NOTICE_HUNGRY; manager.notify(NOTICE_ID[CUR_NOTICE-1], notify); return; } if(data.sick > 80){ notify.ledOffMS = 2000; notify.tickerText = ctx.getString(R.string.notify_sick); notify.setLatestEventInfo(ctx, ctx.getString(R.string.notify_title), ctx.getString(R.string.notify_sick), intent); CUR_NOTICE = NOTICE_SICK; manager.notify(NOTICE_ID[CUR_NOTICE-1], notify); return; } } }
Java
package com.androidsaga; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Random; import android.content.Context; import android.content.SharedPreferences; import android.util.Log; public class Data extends Object{ public Integer charactor; public Integer status; public Integer totalTime; public Integer level; public Float satisfaction; public Float hungry; public Float dirty; public Float sick; public Float otaku; public Float inelegant; public Float scientist; public Float strange; public Float hungryStep; public Float sickStep; public Float dirtyStep; public Float satisfyStep; public Float otakuStep; protected HashMap<String, Integer> materialList = new HashMap<String, Integer>(); public Integer idleSeconds = 0; public Integer afterLastExercise = 0; public Integer sleepSeconds = 0; private Integer prefSleepPeriod; Context ctx; Random rnd = new Random(); public Data(Context ctx){ this.ctx = ctx; loadData(); } public void clearIdleSeconds(){ idleSeconds = 0; } public void clearOtakuSeconds(){ afterLastExercise = 0; } public void setDirtyStep(Float step){ dirtyStep = step; } public void setSickStep(Float step){ sickStep = step; } public void setHungryStep(Float step){ hungryStep = step; } public void updateSatisfaction(Float delta){ if(hungry > ConstantUtil.HUNGRY_AFFECT_SATISFY){ delta -= hungryStep*0.5f; } if(sick > ConstantUtil.SICK_AFFECT_SATISFY){ delta -= sickStep*0.5f; } if(dirty > ConstantUtil.DIRTY_AFFECT_SATISFY){ delta -= dirtyStep*0.5f; } satisfaction += delta; if(satisfaction < 0.f){ satisfaction = 0.f; } else if(satisfaction > 100.f){ satisfaction = 100.f; } } public void updateSick(float delta){ if(hungry > ConstantUtil.HUNGRY_AFFECT_SICK){ delta += hungryStep*0.5f; } if(dirty > ConstantUtil.DIRTY_AFFECT_SICK){ delta += dirtyStep*0.5f; } sick += delta; if(sick < 0.f){ sick = 0.f; } else if(sick > 100.f){ sick = 100.f; charactor = ConstantUtil.STATUS_DEAD; } } public void increaseTotalTime(Integer sec){ totalTime += sec; if(status == ConstantUtil.STATUS_SLEEP){ sleepSeconds += sec; } if(status == ConstantUtil.STATUS_NORMAL){ idleSeconds += sec; } //update level if(level*level*3600 < totalTime) ++level; } public void updateHungry(Float delta){ hungry += delta; if(hungry < 0.f){ hungry = 0.f; } else if(hungry > 100.f){ hungry = 100.f; charactor = ConstantUtil.STATUS_DEAD; } } public void updateDirty(Float delta){ dirty += delta; if(dirty < 0.f){ dirty = 0.f; } else if(dirty > 100.f){ dirty = 100.f; } } public void updateOtaku(Float delta){ otaku += delta; } public void updateInelegant(Float delta){ inelegant += delta; } public void updateStrange(Float delta){ strange += delta; } public void updateScientist(Float delta){ scientist += delta; } public void updatePerSecond(){ //if saga is dead, no action if(charactor == ConstantUtil.STATUS_DEAD){ return; } increaseTotalTime(1); //too much idle time updateSatisfaction(satisfyStep); updateDirty(dirtyStep); updateHungry(hungryStep); updateSick(sickStep); //to much time without exercise if(afterLastExercise >= ConstantUtil.OTAKU_TIME){ updateOtaku(otakuStep); } } public void autoSwitchStatus(){ if(status == ConstantUtil.STATUS_SLEEP && sleepSeconds > prefSleepPeriod){ status = ConstantUtil.STATUS_NORMAL; idleSeconds = 0; } else if(status == ConstantUtil.STATUS_EXERCISE){ status = ConstantUtil.NORMAL_SAGA; idleSeconds = 0; } else if(status == ConstantUtil.STATUS_NORMAL){ //auto-sleep if(idleSeconds > ConstantUtil.AUTO_SLEEP_TIME){ status = ConstantUtil.STATUS_SLEEP; idleSeconds = 0; } else if(dirty > 50){ status = ConstantUtil.STATUS_BATH; idleSeconds = 0; } } else if(status == ConstantUtil.STATUS_BATH){ if(rnd.nextBoolean()){ status = ConstantUtil.STATUS_NORMAL; idleSeconds = 0; } } setStatusStep(); } public void onHome(){ idleSeconds = 0; status = ConstantUtil.STATUS_NORMAL; setStatusStep(); } public void onFeed(){ idleSeconds = 0; updateHungry(ConstantUtil.FEED_VALUE); } public void onBath(){ idleSeconds = 0; status = ConstantUtil.STATUS_BATH; setStatusStep(); } public void onHospital(){ idleSeconds = 0; updateSick(-15.f); } public void setStatusStep(){ satisfyStep = ConstantUtil.SATISFY_STEP[status]; sickStep = ConstantUtil.SICK_STEP[status]; hungryStep = ConstantUtil.HUNGRY_STEP[status]; dirtyStep = ConstantUtil.DIRTY_STEP[status]; otakuStep = ConstantUtil.OTAKU_STEP[status]; } public void updateForPeriod(Integer period){ //if saga is dead, no action if(charactor == ConstantUtil.STATUS_DEAD){ return; } increaseTotalTime(period); //too much idle time updateSatisfaction(satisfyStep*period); updateSick(sickStep*period); updateHungry(hungryStep*period); updateDirty(dirtyStep*period); //to much time without exercise if(afterLastExercise >= ConstantUtil.OTAKU_TIME){ updateOtaku(otakuStep*period); } } public void clearData(boolean clearAll){ otaku = inelegant = scientist = strange = 0.f; if(clearAll){ charactor = ConstantUtil.NORMAL_SAGA; status = ConstantUtil.STATUS_NORMAL; totalTime = 0; level = 0; satisfaction = ConstantUtil.SATISFACTION_DEFAULT; hungry = 0.f; sick = 0.f; dirty = 0.f; } saveData(); } public void saveData(){ SharedPreferences.Editor editor = ctx.getSharedPreferences( ConstantUtil.DEFAULT_SHARED_PREF, Context.MODE_PRIVATE).edit(); editor.putInt(ConstantUtil.KEY_CHARACTOR, charactor); editor.putInt(ConstantUtil.KEY_STATUS, status); editor.putInt(ConstantUtil.KEY_TOTAL_TIME, totalTime); editor.putInt(ConstantUtil.KEY_LEVEL, level); editor.putFloat(ConstantUtil.KEY_SATISFY, satisfaction); editor.putFloat(ConstantUtil.KEY_HUNGRY, hungry); editor.putFloat(ConstantUtil.KEY_DIRTY, dirty); editor.putFloat(ConstantUtil.KEY_SICK, sick); editor.putFloat(ConstantUtil.KEY_OTAKU, otaku); editor.putFloat(ConstantUtil.KEY_INELEGANT, inelegant); editor.putFloat(ConstantUtil.KEY_SCIENTIST, scientist); editor.putFloat(ConstantUtil.KEY_STRANGE, strange); editor.putInt(ConstantUtil.KEY_AFTER_EXERCISE, afterLastExercise); editor.putInt(ConstantUtil.KEY_IDLE_SECONDS, idleSeconds); editor.putInt(ConstantUtil.KEY_SLEEP_SECONDS, sleepSeconds); editor.commit(); } public void loadData(){ SharedPreferences prefs = ctx.getSharedPreferences( ConstantUtil.DEFAULT_SHARED_PREF, Context.MODE_PRIVATE); charactor = prefs.getInt(ConstantUtil.KEY_CHARACTOR, ConstantUtil.NORMAL_SAGA); status = prefs.getInt(ConstantUtil.KEY_STATUS, ConstantUtil.STATUS_NORMAL); totalTime = prefs.getInt(ConstantUtil.KEY_TOTAL_TIME, 0); level = prefs.getInt(ConstantUtil.KEY_LEVEL, 0); satisfaction = prefs.getFloat(ConstantUtil.KEY_SATISFY, ConstantUtil.SATISFACTION_DEFAULT); hungry = prefs.getFloat(ConstantUtil.KEY_HUNGRY, 0.f); dirty = prefs.getFloat(ConstantUtil.KEY_DIRTY, 0.f); sick = prefs.getFloat(ConstantUtil.KEY_SICK, 0.f); otaku = prefs.getFloat(ConstantUtil.KEY_OTAKU, 0.f); scientist = prefs.getFloat(ConstantUtil.KEY_SCIENTIST, 0.f); inelegant = prefs.getFloat(ConstantUtil.KEY_INELEGANT, 0.f); strange = prefs.getFloat(ConstantUtil.KEY_STRANGE, 0.f); idleSeconds = prefs.getInt(ConstantUtil.KEY_IDLE_SECONDS, 0); afterLastExercise = prefs.getInt(ConstantUtil.KEY_AFTER_EXERCISE, 0); sleepSeconds = prefs.getInt(ConstantUtil.KEY_SLEEP_SECONDS, 0); prefSleepPeriod = Integer.parseInt(prefs.getString(ctx.getString(R.string.selected_sleep_option), ctx.getString(R.string.sleep_default_value))); setStatusStep(); Boolean allowRunBackground = prefs.getBoolean(ctx.getString(R.string.run_background_key), true); Boolean isRunning = prefs.getBoolean(ConstantUtil.KEY_IS_RUNNING, false); if((!isRunning) && allowRunBackground){ Long elapsedTime = prefs.getLong(ConstantUtil.KEY_LAST_CLOSE, System.currentTimeMillis()); elapsedTime = (System.currentTimeMillis() - elapsedTime) / 1000; updateForPeriod(elapsedTime.intValue()); } } public void setRunningFlag(boolean isRunning){ SharedPreferences.Editor editor = ctx.getSharedPreferences( ConstantUtil.DEFAULT_SHARED_PREF, Context.MODE_PRIVATE).edit(); if(isRunning){ editor.putBoolean(ConstantUtil.KEY_IS_RUNNING, true); } else { editor.putBoolean(ConstantUtil.KEY_IS_RUNNING, false); editor.putLong(ConstantUtil.KEY_LAST_CLOSE, System.currentTimeMillis()); } editor.commit(); } public Integer getMaterialCount(String name){ if(!materialList.containsKey(name)){ return -1; } return (materialList.get(name)); } public void addMaterial(String name){ if(materialList.containsKey(name)){ Integer curAmount = materialList.remove(name); materialList.put(name, curAmount+1); } else{ materialList.put(name, 1); } } public Integer useMaterial(String name, Integer amount){ if(getMaterialCount(name) < amount){ return -1; } Integer curAmount = materialList.remove(name); curAmount -= amount; if(curAmount > 0){ materialList.put(name, curAmount); } return 1; } }
Java
package com.androidsaga; import android.app.PendingIntent; import android.appwidget.AppWidgetManager; import android.appwidget.AppWidgetProvider; import android.content.Context; import android.content.Intent; import android.util.Log; import android.widget.RemoteViews; public class SagaWidget extends AppWidgetProvider{ @Override public void onUpdate(Context context, AppWidgetManager appWidgetManager,int[] appWidgetIds) { UpdateService.updateAppWidgetIds(appWidgetIds); context.startService(new Intent(context, UpdateService.class)); Log.v("tag", "update"); } @Override public void onReceive(Context context, Intent intent){ super.onReceive(context, intent); } public static RemoteViews updateAppWidget(Context context) { RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.saga_widget_layout); Data data = new Data(context); data.autoSwitchStatus(); views.setTextViewText(R.id.widget_level, data.level.toString()); views.setTextViewText(R.id.widget_satisfy, data.satisfaction.toString()); views.setTextViewText(R.id.widget_hungry, data.hungry.toString()); views.setTextViewText(R.id.widget_dirty, data.dirty.toString()); views.setTextViewText(R.id.widget_sick, data.sick.toString()); data.saveData(); data.setRunningFlag(false); ConstantUtil.setNotify(context, data); Intent detailIntent = new Intent(context, SagaActivity.class); PendingIntent pending = PendingIntent.getActivity(context, 0, detailIntent, 0); views.setOnClickPendingIntent(R.id.widget_saga_imageView, pending); data = null; return views; } }
Java
package com.androidsaga; import android.os.Bundle; import android.preference.PreferenceActivity; public class SagaPreferenceActivity extends PreferenceActivity { @Override protected void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); this.addPreferencesFromResource(R.xml.preference); } }
Java
package com.androidsaga; import android.graphics.Bitmap; public class AutoPresent { //present id, each present has its own identical id //this id is used as key to search in the database public Integer presentID; //present pic and gray-level pic public Bitmap presentPic = null; public Bitmap presentGrayPic = null; //current place: will be moved every frame public Integer x; public Integer y; public Float rotation; public Boolean hasPresentNow = false; }
Java
package com.androidsaga; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; public class Alert{ public static void showAlert(String title, String msg, Context ctx) { AlertDialog.Builder builder = new AlertDialog.Builder(ctx); builder.setMessage(msg); builder.setTitle(title); builder.setPositiveButton("OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { // TODO Auto-generated method stub } }); builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { // TODO Auto-generated method stub } }); AlertDialog ad = builder.create(); ad.show(); } }
Java
package com.androidsaga; import android.app.Activity; import android.app.NotificationManager; import android.content.Context; import android.content.Intent; import android.content.res.Configuration; import android.graphics.*; import android.os.Bundle; import android.util.DisplayMetrics; import android.util.Log; import android.view.View.*; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.MotionEvent; import android.view.View; import android.view.Window; import android.widget.*; public class SagaActivity extends Activity { /** Called when the activity is first created. **/ private ImageView MainView; private ImageView HomeBtn; private ImageView BathBtn; private ImageView FeedBtn; private ImageView ExerciseBtn; private ImageView QABtn; private ImageView SleepBtn; private ImageView HospitalBtn; private ImageView PresentBtn; private TextView SayView; private Integer width; private Integer height; private Bitmap MainImage; private Data sagaData; private Thread updateThr; boolean running = false; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); this.requestWindowFeature( Window.FEATURE_NO_TITLE ); setContentView(R.layout.main); MainView = (ImageView)findViewById(R.id.MainView); SayView = (TextView)findViewById(R.id.SayView); SayView.setText("Hello"); DisplayMetrics dm = new DisplayMetrics(); getWindowManager().getDefaultDisplay().getMetrics(dm); width = dm.widthPixels; height = dm.heightPixels; int btnSize = width / 8; SayView.setHeight(height / 6); SayView.setWidth(7*width / 8); height -= (40 + height/6 + btnSize); //set main view size according to resolution MainImage = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); MainView.setImageBitmap(MainImage); HomeBtn = (ImageView)findViewById(R.id.HomeButton); BathBtn = (ImageView)findViewById(R.id.BathButton); FeedBtn = (ImageView)findViewById(R.id.FeedButton); ExerciseBtn = (ImageView)findViewById(R.id.ExerciseButton); QABtn = (ImageView)findViewById(R.id.QAButton); SleepBtn = (ImageView)findViewById(R.id.SleepButton); HospitalBtn = (ImageView)findViewById(R.id.HospitalButton); PresentBtn = (ImageView)findViewById(R.id.PresentButton); //add button image HomeBtn.setImageBitmap(ConstantUtil.scaleButtonBitmap( this, R.drawable.homebtn, btnSize, btnSize)); BathBtn.setImageBitmap(ConstantUtil.scaleButtonBitmap( this, R.drawable.bathbtn, btnSize, btnSize)); FeedBtn.setImageBitmap(ConstantUtil.scaleButtonBitmap( this, R.drawable.feedbtn, btnSize, btnSize)); ExerciseBtn.setImageBitmap(ConstantUtil.scaleButtonBitmap( this, R.drawable.exercisebtn, btnSize, btnSize)); QABtn.setImageBitmap(ConstantUtil.scaleButtonBitmap( this, R.drawable.qabtn, btnSize, btnSize)); SleepBtn.setImageBitmap(ConstantUtil.scaleButtonBitmap( this, R.drawable.sleepbtn, btnSize, btnSize)); HospitalBtn.setImageBitmap(ConstantUtil.scaleButtonBitmap( this, R.drawable.hospitalbtn, btnSize, btnSize)); PresentBtn.setImageBitmap(ConstantUtil.scaleButtonBitmap( this, R.drawable.presentbtn, btnSize, btnSize)); sagaData = new Data(this); sagaData.setRunningFlag(true); running = true; updateThr = new Thread(){ @Override public void run(){ while(true){ if(running){ sagaData.updatePerSecond(); Log.i("Saga", "update"); } try{ Thread.sleep(1000); } catch(Exception e){ e.printStackTrace(); } } } }; updateThr.start(); ConstantUtil.setNotify(this, sagaData); Alert.showAlert("Saga", sagaData.totalTime.toString(), this); } @Override public boolean onCreateOptionsMenu(Menu menu){ MenuInflater inflater = this.getMenuInflater(); inflater.inflate(R.menu.mainmenu, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item){ if(item.getItemId() == R.id.menu_prefs){ Intent intent = new Intent() .setClass(this, com.androidsaga.SagaPreferenceActivity.class); this.startActivityForResult(intent, 0); } else if(item.getItemId() == R.id.menu_clearall){ sagaData.clearData(true); } return true; } @Override public void onActivityResult(int reqCode, int resCode, Intent data){ super.onActivityResult(reqCode, resCode, data); } @Override public void onPause(){ super.onPause(); running = false; sagaData.saveData(); sagaData.setRunningFlag(false); } @Override public void onResume(){ super.onResume(); if(ConstantUtil.CUR_NOTICE != 0){ final NotificationManager manager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE); manager.cancel(ConstantUtil.NOTICE_ID[ConstantUtil.CUR_NOTICE-1]); ConstantUtil.CUR_NOTICE = 0; } sagaData.loadData(); running = true; sagaData.setRunningFlag(true); } @Override public void onDestroy(){ super.onDestroy(); updateThr = null; } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); } public void clickHome(View target) { Alert.showAlert("Saga", "Home", this); sagaData.onHome(); } public void clickBath(View target) { Alert.showAlert("Saga", "Bath", this); sagaData.onBath(); } public void clickHospital(View target) { Alert.showAlert("Saga", "Hospital", this); sagaData.onHospital(); } public void clickFeed(View target) { Alert.showAlert("Saga", "Feed", this); sagaData.onFeed(); } public void clickPresent(View target) { Alert.showAlert("Saga", "Present", this); } public void clickExercise(View target) { Alert.showAlert("Saga", "Exercise", this); } public void clickQA(View target) { Alert.showAlert("Saga", "Answer Question", this); } public void clickSleep(View target) { Alert.showAlert("Saga", "Sleep", this); } }
Java
package com.androidsaga; import java.util.LinkedList; import java.util.Queue; import android.app.AlarmManager; import android.app.PendingIntent; import android.app.Service; import android.appwidget.AppWidgetManager; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.os.IBinder; import android.text.format.Time; import android.widget.RemoteViews; public class UpdateService extends Service implements Runnable { private static Queue<Integer> sAppWidgetIds = new LinkedList<Integer>(); public static final String ACTION_UPDATE_ALL = "com.androidsaga.UPDATE_ALL"; private static boolean sThreadRunning = false; private static Object sLock = new Object(); @Override public IBinder onBind(Intent arg0) { // TODO Auto-generated method stub return null; } public static void updateAppWidgetIds(int[] appWidgetIds){ synchronized (sLock) { for (int appWidgetId : appWidgetIds) { sAppWidgetIds.add(appWidgetId); } } } public static int getNextWidgetId(){ synchronized (sLock) { if (sAppWidgetIds.peek() == null) { return AppWidgetManager.INVALID_APPWIDGET_ID; } else { return sAppWidgetIds.poll(); } } } private static boolean hasMoreUpdates() { synchronized (sLock) { boolean hasMore = !sAppWidgetIds.isEmpty(); if (!hasMore) { sThreadRunning = false; } return hasMore; } } @Override public void onCreate() { super.onCreate(); } @Override public void onStart(Intent intent, int startId) { super.onStart(intent, startId); if (null != intent) { if (ACTION_UPDATE_ALL.equals(intent.getAction())) { AppWidgetManager widget = AppWidgetManager.getInstance(this); updateAppWidgetIds(widget.getAppWidgetIds(new ComponentName(this, SagaWidget.class))); } } synchronized (sLock) { if (!sThreadRunning) { sThreadRunning=true; new Thread(this).start(); } } } public void run() { AppWidgetManager appWidgetManager=AppWidgetManager.getInstance(this); RemoteViews updateViews=null; while (hasMoreUpdates()) { int appWidgetId=getNextWidgetId(); updateViews = SagaWidget.updateAppWidget(this); if (updateViews != null) { appWidgetManager.updateAppWidget(appWidgetId, updateViews); } } Intent updateIntent=new Intent(ACTION_UPDATE_ALL); updateIntent.setClass(this, UpdateService.class); PendingIntent pending=PendingIntent.getService(this, 0, updateIntent, 0); Time time = new Time(); long nowMillis = System.currentTimeMillis(); long updatePeriod = Long.parseLong(getSharedPreferences( ConstantUtil.DEFAULT_SHARED_PREF, Context.MODE_PRIVATE). getString(getString(R.string.selected_auto_update_option), getString(R.string.auto_update_default_value))); time.set(nowMillis+updatePeriod); long updateTimes = time.toMillis(true); AlarmManager alarm=(AlarmManager)getSystemService(Context.ALARM_SERVICE); alarm.set(AlarmManager.RTC_WAKEUP, updateTimes, pending); stopSelf(); } }
Java
package com.androidsaga; import android.app.Activity; import android.os.Bundle; import android.view.Window; public class QuizActivity extends Activity{ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); this.requestWindowFeature( Window.FEATURE_NO_TITLE ); setContentView(R.layout.main); } }
Java
/* * Copyright (C) 2009 Google Inc. * * 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.ch_linghu.fanfoudroid; import android.content.SharedPreferences; import android.content.pm.ActivityInfo; import android.os.Bundle; import android.preference.Preference; import android.preference.PreferenceActivity; import android.preference.PreferenceScreen; import android.util.Log; import com.ch_linghu.fanfoudroid.app.Preferences; import com.ch_linghu.fanfoudroid.http.HttpClient; import com.ch_linghu.fanfoudroid.ui.module.MyTextView; public class PreferencesActivity extends PreferenceActivity implements SharedPreferences.OnSharedPreferenceChangeListener { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //禁止横屏 if (TwitterApplication.mPref.getBoolean( Preferences.FORCE_SCREEN_ORIENTATION_PORTRAIT, false)) { setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); } // TODO: is this a hack? setResult(RESULT_OK); addPreferencesFromResource(R.xml.preferences); } @Override protected void onResume() { super.onResume(); // Set up a listener whenever a key changes getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this); } @Override public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen, Preference preference) { return super.onPreferenceTreeClick(preferenceScreen, preference); } public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { if ( key.equalsIgnoreCase(Preferences.NETWORK_TYPE) ) { HttpClient httpClient = TwitterApplication.mApi.getHttpClient(); String type = sharedPreferences.getString(Preferences.NETWORK_TYPE, ""); if (type.equalsIgnoreCase(getString(R.string.pref_network_type_cmwap))) { Log.d("LDS", "Set proxy for cmwap mode."); httpClient.setProxy("10.0.0.172", 80, "http"); } else { Log.d("LDS", "No proxy."); httpClient.removeProxy(); } } else if ( key.equalsIgnoreCase(Preferences.UI_FONT_SIZE)) { MyTextView.setFontSizeChanged(true); } } }
Java
package com.ch_linghu.fanfoudroid.app; import java.util.HashMap; import android.graphics.Bitmap; public class MemoryImageCache implements ImageCache { private HashMap<String, Bitmap> mCache; public MemoryImageCache() { mCache = new HashMap<String, Bitmap>(); } @Override public Bitmap get(String url) { synchronized(this) { Bitmap bitmap = mCache.get(url); if (bitmap == null){ return mDefaultBitmap; }else{ return bitmap; } } } @Override public void put(String url, Bitmap bitmap) { synchronized(this) { mCache.put(url, bitmap); } } public void putAll(MemoryImageCache imageCache) { synchronized(this) { // TODO: is this thread safe? mCache.putAll(imageCache.mCache); } } }
Java
/* * Copyright (C) 2009 Google Inc. * * 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.ch_linghu.fanfoudroid.app; public class Preferences { public static final String USERNAME_KEY = "username"; public static final String PASSWORD_KEY = "password"; public static final String CHECK_UPDATES_KEY = "check_updates"; public static final String CHECK_UPDATE_INTERVAL_KEY = "check_update_interval"; public static final String VIBRATE_KEY = "vibrate"; public static final String TIMELINE_ONLY_KEY = "timeline_only"; public static final String REPLIES_ONLY_KEY = "replies_only"; public static final String DM_ONLY_KEY = "dm_only"; public static String RINGTONE_KEY = "ringtone"; public static final String RINGTONE_DEFAULT_KEY = "content://settings/system/notification_sound"; public static final String LAST_TWEET_REFRESH_KEY = "last_tweet_refresh"; public static final String LAST_DM_REFRESH_KEY = "last_dm_refresh"; public static final String LAST_FOLLOWERS_REFRESH_KEY = "last_followers_refresh"; public static final String TWITTER_ACTIVITY_STATE_KEY = "twitter_activity_state"; public static final String USE_PROFILE_IMAGE = "use_profile_image"; public static final String PHOTO_PREVIEW = "photo_preview"; public static final String FORCE_SHOW_ALL_IMAGE = "force_show_all_image"; public static final String RT_PREFIX_KEY = "rt_prefix"; public static final String RT_INSERT_APPEND = "rt_insert_append"; // 转发时光标放置在开始还是结尾 public static final String NETWORK_TYPE = "network_type"; // DEBUG标记 public static final String DEBUG = "debug"; // 当前用户相关信息 public static final String CURRENT_USER_ID = "current_user_id"; public static final String CURRENT_USER_SCREEN_NAME = "current_user_screenname"; public static final String UI_FONT_SIZE = "ui_font_size"; public static final String USE_ENTER_SEND = "use_enter_send"; public static final String USE_GESTRUE = "use_gestrue"; public static final String USE_SHAKE = "use_shake"; public static final String FORCE_SCREEN_ORIENTATION_PORTRAIT = "force_screen_orientation_portrait"; }
Java
package com.ch_linghu.fanfoudroid.app; import android.text.Spannable; import android.text.method.LinkMovementMethod; import android.text.method.MovementMethod; import android.view.MotionEvent; import android.widget.TextView; public class TestMovementMethod extends LinkMovementMethod { private double mY; private boolean mIsMoving = false; @Override public boolean onTouchEvent(TextView widget, Spannable buffer, MotionEvent event) { /* int action = event.getAction(); if (action == MotionEvent.ACTION_MOVE) { double deltaY = mY - event.getY(); mY = event.getY(); Log.d("foo", deltaY + ""); if (Math.abs(deltaY) > 1) { mIsMoving = true; } } else if (action == MotionEvent.ACTION_DOWN) { mIsMoving = false; mY = event.getY(); } else if (action == MotionEvent.ACTION_UP) { boolean wasMoving = mIsMoving; mIsMoving = false; if (wasMoving) { return true; } } */ return super.onTouchEvent(widget, buffer, event); } public static MovementMethod getInstance() { if (sInstance == null) sInstance = new TestMovementMethod(); return sInstance; } private static TestMovementMethod sInstance; }
Java
package com.ch_linghu.fanfoudroid.app; import android.app.Activity; import android.content.Intent; import android.widget.Toast; import com.ch_linghu.fanfoudroid.LoginActivity; import com.ch_linghu.fanfoudroid.R; import com.ch_linghu.fanfoudroid.fanfou.RefuseError; import com.ch_linghu.fanfoudroid.http.HttpAuthException; import com.ch_linghu.fanfoudroid.http.HttpException; import com.ch_linghu.fanfoudroid.http.HttpRefusedException; import com.ch_linghu.fanfoudroid.http.HttpServerException; public class ExceptionHandler { private Activity mActivity; public ExceptionHandler(Activity activity) { mActivity = activity; } public void handle(HttpException e) { Throwable cause = e.getCause(); if (null == cause) return; // Handle Different Exception if (cause instanceof HttpAuthException) { // 用户名/密码错误 Toast.makeText(mActivity, R.string.error_not_authorized, Toast.LENGTH_LONG).show(); Intent intent = new Intent(mActivity, LoginActivity.class); mActivity.startActivity(intent); // redirect to the login activity } else if (cause instanceof HttpServerException) { // 服务器暂时无法响应 Toast.makeText(mActivity, R.string.error_not_authorized, Toast.LENGTH_LONG).show(); } else if (cause instanceof HttpAuthException) { //FIXME: 集中处理用户名/密码验证错误,返回到登录界面 } else if (cause instanceof HttpRefusedException) { // 服务器拒绝请求,如没有权限查看某用户信息 RefuseError error = ((HttpRefusedException) cause).getError(); switch (error.getErrorCode()) { // TODO: finish it case -1: default: Toast.makeText(mActivity, error.getMessage(), Toast.LENGTH_LONG).show(); break; } } } private void handleCause() { } }
Java
/* * Copyright (C) 2009 Google Inc. * * 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.ch_linghu.fanfoudroid.app; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.lang.ref.SoftReference; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.PixelFormat; import android.graphics.drawable.Drawable; import android.util.Log; import com.ch_linghu.fanfoudroid.TwitterApplication; import com.ch_linghu.fanfoudroid.http.HttpException; import com.ch_linghu.fanfoudroid.http.Response; /** * Manages retrieval and storage of icon images. Use the put method to download * and store images. Use the get method to retrieve images from the manager. */ public class ImageManager implements ImageCache { private static final String TAG = "ImageManager"; // 饭否目前最大宽度支持596px, 超过则同比缩小 // 最大高度为1192px, 超过从中截取 public static final int DEFAULT_COMPRESS_QUALITY = 90; public static final int IMAGE_MAX_WIDTH = 596; public static final int IMAGE_MAX_HEIGHT = 1192; private Context mContext; // In memory cache. private Map<String, SoftReference<Bitmap>> mCache; // MD5 hasher. private MessageDigest mDigest; public static Bitmap drawableToBitmap(Drawable drawable) { Bitmap bitmap = Bitmap .createBitmap( drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565); Canvas canvas = new Canvas(bitmap); drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable .getIntrinsicHeight()); drawable.draw(canvas); return bitmap; } public ImageManager(Context context) { mContext = context; mCache = new HashMap<String, SoftReference<Bitmap>>(); try { mDigest = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { // This shouldn't happen. throw new RuntimeException("No MD5 algorithm."); } } public void setContext(Context context) { mContext = context; } private String getHashString(MessageDigest digest) { StringBuilder builder = new StringBuilder(); for (byte b : digest.digest()) { builder.append(Integer.toHexString((b >> 4) & 0xf)); builder.append(Integer.toHexString(b & 0xf)); } return builder.toString(); } // MD5 hases are used to generate filenames based off a URL. private String getMd5(String url) { mDigest.update(url.getBytes()); return getHashString(mDigest); } // Looks to see if an image is in the file system. private Bitmap lookupFile(String url) { String hashedUrl = getMd5(url); FileInputStream fis = null; try { fis = mContext.openFileInput(hashedUrl); return BitmapFactory.decodeStream(fis); } catch (FileNotFoundException e) { // Not there. return null; } finally { if (fis != null) { try { fis.close(); } catch (IOException e) { // Ignore. } } } } /** * Downloads a file * @param url * @return * @throws HttpException */ public Bitmap downloadImage(String url) throws HttpException { Log.d(TAG, "Fetching image: " + url); Response res = TwitterApplication.mApi.getHttpClient().get(url); return BitmapFactory.decodeStream(new BufferedInputStream(res.asStream())); } public Bitmap downloadImage2(String url) throws HttpException { Log.d(TAG, "[NEW]Fetching image: " + url); final Response res = TwitterApplication.mApi.getHttpClient().get(url); String file = writeToFile(res.asStream(), getMd5(url)); return BitmapFactory.decodeFile(file); } /** * 下载远程图片 -> 转换为Bitmap -> 写入缓存器. * @param url * @param quality image quality 1~100 * @throws HttpException */ public void put(String url, int quality, boolean forceOverride) throws HttpException { if (!forceOverride && contains(url)) { // Image already exists. return; // TODO: write to file if not present. } Bitmap bitmap = downloadImage(url); if (bitmap != null) { put(url, bitmap, quality); // file cache } else { Log.w(TAG, "Retrieved bitmap is null."); } } /** * 重载 put(String url, int quality) * @param url * @throws HttpException */ public void put(String url) throws HttpException { put(url, DEFAULT_COMPRESS_QUALITY, false); } /** * 将本地File -> 转换为Bitmap -> 写入缓存器. * 如果图片大小超过MAX_WIDTH/MAX_HEIGHT, 则将会对图片缩放. * * @param file * @param quality 图片质量(0~100) * @param forceOverride * @throws IOException */ public void put(File file, int quality, boolean forceOverride) throws IOException { if (!file.exists()) { Log.w(TAG, file.getName() + " is not exists."); return; } if (!forceOverride && contains(file.getPath())) { // Image already exists. Log.d(TAG, file.getName() + " is exists"); return; // TODO: write to file if not present. } Bitmap bitmap = BitmapFactory.decodeFile(file.getPath()); //bitmap = resizeBitmap(bitmap, MAX_WIDTH, MAX_HEIGHT); if (bitmap == null) { Log.w(TAG, "Retrieved bitmap is null."); } else { put(file.getPath(), bitmap, quality); } } /** * 将Bitmap写入缓存器. * @param filePath file path * @param bitmap * @param quality 1~100 */ public void put(String file, Bitmap bitmap, int quality) { synchronized (this) { mCache.put(file, new SoftReference<Bitmap>(bitmap)); } writeFile(file, bitmap, quality); } /** * 重载 put(String file, Bitmap bitmap, int quality) * @param filePath file path * @param bitmap * @param quality 1~100 */ @Override public void put(String file, Bitmap bitmap) { put(file, bitmap, DEFAULT_COMPRESS_QUALITY); } /** * 将Bitmap写入本地缓存文件. * @param file URL/PATH * @param bitmap * @param quality */ private void writeFile(String file, Bitmap bitmap, int quality) { if (bitmap == null) { Log.w(TAG, "Can't write file. Bitmap is null."); return; } BufferedOutputStream bos = null; try { String hashedUrl = getMd5(file); bos = new BufferedOutputStream( mContext.openFileOutput(hashedUrl, Context.MODE_PRIVATE)); bitmap.compress(Bitmap.CompressFormat.JPEG, quality, bos); // PNG Log.d(TAG, "Writing file: " + file); } catch (IOException ioe) { Log.e(TAG, ioe.getMessage()); } finally { try { if (bos != null) { bitmap.recycle(); bos.flush(); bos.close(); } //bitmap.recycle(); } catch (IOException e) { Log.e(TAG, "Could not close file."); } } } private String writeToFile(InputStream is, String filename) { Log.d("LDS", "new write to file"); BufferedInputStream in = null; BufferedOutputStream out = null; try { in = new BufferedInputStream(is); out = new BufferedOutputStream( mContext.openFileOutput(filename, Context.MODE_PRIVATE)); byte[] buffer = new byte[1024]; int l; while ((l = in.read(buffer)) != -1) { out.write(buffer, 0, l); } } catch (IOException ioe) { ioe.printStackTrace(); } finally { try { if (in != null) in.close(); if (out != null) { Log.d("LDS", "new write to file to -> " + filename); out.flush(); out.close(); } } catch (IOException ioe) { ioe.printStackTrace(); } } return mContext.getFilesDir() + "/" + filename; } public Bitmap get(File file) { return get(file.getPath()); } /** * 判断缓存着中是否存在该文件对应的bitmap */ public boolean isContains(String file) { return mCache.containsKey(file); } /** * 获得指定file/URL对应的Bitmap,首先找本地文件,如果有直接使用,否则去网上获取 * @param file file URL/file PATH * @param bitmap * @param quality * @throws HttpException */ public Bitmap safeGet(String file) throws HttpException { Bitmap bitmap = lookupFile(file); // first try file. if (bitmap != null) { synchronized (this) { // memory cache mCache.put(file, new SoftReference<Bitmap>(bitmap)); } return bitmap; } else { //get from web String url = file; bitmap = downloadImage2(url); // 注释掉以测试新的写入文件方法 //put(file, bitmap); // file Cache return bitmap; } } /** * 从缓存器中读取文件 * @param file file URL/file PATH * @param bitmap * @param quality */ public Bitmap get(String file) { SoftReference<Bitmap> ref; Bitmap bitmap; // Look in memory first. synchronized (this) { ref = mCache.get(file); } if (ref != null) { bitmap = ref.get(); if (bitmap != null) { return bitmap; } } // Now try file. bitmap = lookupFile(file); if (bitmap != null) { synchronized (this) { mCache.put(file, new SoftReference<Bitmap>(bitmap)); } return bitmap; } //TODO: why? //upload: see profileImageCacheManager line 96 Log.w(TAG, "Image is missing: " + file); // return the default photo return mDefaultBitmap; } public boolean contains(String url) { return get(url) != mDefaultBitmap; } public void clear() { String[] files = mContext.fileList(); for (String file : files) { mContext.deleteFile(file); } synchronized (this) { mCache.clear(); } } public void cleanup(HashSet<String> keepers) { String[] files = mContext.fileList(); HashSet<String> hashedUrls = new HashSet<String>(); for (String imageUrl : keepers) { hashedUrls.add(getMd5(imageUrl)); } for (String file : files) { if (!hashedUrls.contains(file)) { Log.d(TAG, "Deleting unused file: " + file); mContext.deleteFile(file); } } } /** * Compress and resize the Image * * <br /> * 因为不论图片大小和尺寸如何, 饭否都会对图片进行一次有损压缩, 所以本地压缩应该 * 考虑图片将会被二次压缩所造成的图片质量损耗 * * @param targetFile * @param quality, 0~100, recommend 100 * @return * @throws IOException */ public File compressImage(File targetFile, int quality) throws IOException { String filepath = targetFile.getAbsolutePath(); // 1. Calculate scale int scale = 1; BitmapFactory.Options o = new BitmapFactory.Options(); o.inJustDecodeBounds = true; BitmapFactory.decodeFile(filepath, o); if (o.outWidth > IMAGE_MAX_WIDTH || o.outHeight > IMAGE_MAX_HEIGHT) { scale = (int) Math.pow( 2.0, (int) Math.round(Math.log(IMAGE_MAX_WIDTH / (double) Math.max(o.outHeight, o.outWidth)) / Math.log(0.5))); //scale = 2; } Log.d(TAG, scale + " scale"); // 2. File -> Bitmap (Returning a smaller image) o.inJustDecodeBounds = false; o.inSampleSize = scale; Bitmap bitmap = BitmapFactory.decodeFile(filepath, o); // 2.1. Resize Bitmap //bitmap = resizeBitmap(bitmap, IMAGE_MAX_WIDTH, IMAGE_MAX_HEIGHT); // 3. Bitmap -> File writeFile(filepath, bitmap, quality); // 4. Get resized Image File String filePath = getMd5(targetFile.getPath()); File compressedImage = mContext.getFileStreamPath(filePath); return compressedImage; } /** * 保持长宽比缩小Bitmap * * @param bitmap * @param maxWidth * @param maxHeight * @param quality 1~100 * @return */ public Bitmap resizeBitmap(Bitmap bitmap, int maxWidth, int maxHeight) { int originWidth = bitmap.getWidth(); int originHeight = bitmap.getHeight(); // no need to resize if (originWidth < maxWidth && originHeight < maxHeight) { return bitmap; } int newWidth = originWidth; int newHeight = originHeight; // 若图片过宽, 则保持长宽比缩放图片 if (originWidth > maxWidth) { newWidth = maxWidth; double i = originWidth * 1.0 / maxWidth; newHeight = (int) Math.floor(originHeight / i); bitmap = Bitmap.createScaledBitmap(bitmap, newWidth, newHeight, true); } // 若图片过长, 则从中部截取 if (newHeight > maxHeight) { newHeight = maxHeight; int half_diff = (int)((originHeight - maxHeight) / 2.0); bitmap = Bitmap.createBitmap(bitmap, 0, half_diff, newWidth, newHeight); } Log.d(TAG, newWidth + " width"); Log.d(TAG, newHeight + " height"); return bitmap; } }
Java
package com.ch_linghu.fanfoudroid.app; import android.graphics.Bitmap; import android.widget.ImageView; import com.ch_linghu.fanfoudroid.TwitterApplication; import com.ch_linghu.fanfoudroid.app.LazyImageLoader.ImageLoaderCallback; public class SimpleImageLoader { public static void display(final ImageView imageView, String url) { imageView.setTag(url); imageView.setImageBitmap(TwitterApplication.mImageLoader .get(url, createImageViewCallback(imageView, url))); } public static ImageLoaderCallback createImageViewCallback(final ImageView imageView, String url) { return new ImageLoaderCallback() { @Override public void refresh(String url, Bitmap bitmap) { if (url.equals(imageView.getTag())) { imageView.setImageBitmap(bitmap); } } }; } }
Java
package com.ch_linghu.fanfoudroid.app; import java.lang.Thread.State; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.TimeUnit; import android.graphics.Bitmap; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.util.Log; import com.ch_linghu.fanfoudroid.TwitterApplication; import com.ch_linghu.fanfoudroid.http.HttpException; public class LazyImageLoader { private static final String TAG = "ProfileImageCacheManager"; public static final int HANDLER_MESSAGE_ID = 1; public static final String EXTRA_BITMAP = "extra_bitmap"; public static final String EXTRA_IMAGE_URL = "extra_image_url"; private ImageManager mImageManager = new ImageManager( TwitterApplication.mContext); private BlockingQueue<String> mUrlList = new ArrayBlockingQueue<String>(50); private CallbackManager mCallbackManager = new CallbackManager(); private GetImageTask mTask = new GetImageTask(); /** * 取图片, 可能直接从cache中返回, 或下载图片后返回 * * @param url * @param callback * @return */ public Bitmap get(String url, ImageLoaderCallback callback) { Bitmap bitmap = ImageCache.mDefaultBitmap; if (mImageManager.isContains(url)) { bitmap = mImageManager.get(url); } else { // bitmap不存在,启动Task进行下载 mCallbackManager.put(url, callback); startDownloadThread(url); } return bitmap; } private void startDownloadThread(String url) { if (url != null) { addUrlToDownloadQueue(url); } // Start Thread State state = mTask.getState(); if (Thread.State.NEW == state) { mTask.start(); // first start } else if (Thread.State.TERMINATED == state) { mTask = new GetImageTask(); // restart mTask.start(); } } private void addUrlToDownloadQueue(String url) { if (!mUrlList.contains(url)) { try { mUrlList.put(url); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } // Low-level interface to get ImageManager public ImageManager getImageManager() { return mImageManager; } private class GetImageTask extends Thread { private volatile boolean mTaskTerminated = false; private static final int TIMEOUT = 3 * 60; private boolean isPermanent = true; @Override public void run() { try { while (!mTaskTerminated) { String url; if (isPermanent) { url = mUrlList.take(); } else { url = mUrlList.poll(TIMEOUT, TimeUnit.SECONDS); // waiting if (null == url) { break; } // no more, shutdown } // Bitmap bitmap = ImageCache.mDefaultBitmap; final Bitmap bitmap = mImageManager.safeGet(url); // use handler to process callback final Message m = handler.obtainMessage(HANDLER_MESSAGE_ID); Bundle bundle = m.getData(); bundle.putString(EXTRA_IMAGE_URL, url); bundle.putParcelable(EXTRA_BITMAP, bitmap); handler.sendMessage(m); } } catch (HttpException ioe) { Log.e(TAG, "Get Image failed, " + ioe.getMessage()); } catch (InterruptedException e) { Log.w(TAG, e.getMessage()); } finally { Log.v(TAG, "Get image task terminated."); mTaskTerminated = true; } } @SuppressWarnings("unused") public boolean isPermanent() { return isPermanent; } @SuppressWarnings("unused") public void setPermanent(boolean isPermanent) { this.isPermanent = isPermanent; } @SuppressWarnings("unused") public void shutDown() throws InterruptedException { mTaskTerminated = true; } } Handler handler = new Handler() { @Override public void handleMessage(Message msg) { switch (msg.what) { case HANDLER_MESSAGE_ID: final Bundle bundle = msg.getData(); String url = bundle.getString(EXTRA_IMAGE_URL); Bitmap bitmap = (Bitmap) (bundle.get(EXTRA_BITMAP)); // callback mCallbackManager.call(url, bitmap); break; default: // do nothing. } } }; public interface ImageLoaderCallback { void refresh(String url, Bitmap bitmap); } public static class CallbackManager { private static final String TAG = "CallbackManager"; private ConcurrentHashMap<String, List<ImageLoaderCallback>> mCallbackMap; public CallbackManager() { mCallbackMap = new ConcurrentHashMap<String, List<ImageLoaderCallback>>(); } public void put(String url, ImageLoaderCallback callback) { Log.v(TAG, "url=" + url); if (!mCallbackMap.containsKey(url)) { Log.v(TAG, "url does not exist, add list to map"); mCallbackMap.put(url, new ArrayList<ImageLoaderCallback>()); //mCallbackMap.put(url, Collections.synchronizedList(new ArrayList<ImageLoaderCallback>())); } mCallbackMap.get(url).add(callback); Log.v(TAG, "Add callback to list, count(url)=" + mCallbackMap.get(url).size()); } public void call(String url, Bitmap bitmap) { Log.v(TAG, "call url=" + url); List<ImageLoaderCallback> callbackList = mCallbackMap.get(url); if (callbackList == null) { // FIXME: 有时会到达这里,原因我还没想明白 Log.e(TAG, "callbackList=null"); return; } for (ImageLoaderCallback callback : callbackList) { if (callback != null) { callback.refresh(url, bitmap); } } callbackList.clear(); mCallbackMap.remove(url); } } }
Java
package com.ch_linghu.fanfoudroid.app; import android.graphics.Bitmap; import com.ch_linghu.fanfoudroid.R; import com.ch_linghu.fanfoudroid.TwitterApplication; public interface ImageCache { public static Bitmap mDefaultBitmap = ImageManager.drawableToBitmap(TwitterApplication.mContext.getResources().getDrawable(R.drawable.user_default_photo)); public Bitmap get(String url); public void put(String url, Bitmap bitmap); }
Java
/* * Copyright (C) 2009 Google Inc. * * 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.ch_linghu.fanfoudroid.data; import java.util.Date; import org.json.JSONException; import org.json.JSONObject; import android.os.Parcel; import android.os.Parcelable; import android.text.TextUtils; import com.ch_linghu.fanfoudroid.R; import com.ch_linghu.fanfoudroid.TwitterApplication; import com.ch_linghu.fanfoudroid.fanfou.Status; import com.ch_linghu.fanfoudroid.util.DateTimeHelper; import com.ch_linghu.fanfoudroid.util.TextHelper; public class Tweet extends Message implements Parcelable { private static final String TAG = "Tweet"; public com.ch_linghu.fanfoudroid.fanfou.User user; public String source; public String prevId; private int statusType = -1; // @see StatusTable#TYPE_* public void setStatusType(int type) { statusType = type; } public int getStatusType() { return statusType; } public Tweet(){} public static Tweet create(Status status){ Tweet tweet = new Tweet(); tweet.id = status.getId(); //转义符放到getSimpleTweetText里去处理,这里不做处理 tweet.text = status.getText(); tweet.createdAt = status.getCreatedAt(); tweet.favorited = status.isFavorited()?"true":"false"; tweet.truncated = status.isTruncated()?"true":"false"; tweet.inReplyToStatusId = status.getInReplyToStatusId(); tweet.inReplyToUserId = status.getInReplyToUserId(); tweet.inReplyToScreenName = status.getInReplyToScreenName(); tweet.screenName = TextHelper.getSimpleTweetText(status.getUser().getScreenName()); tweet.profileImageUrl = status.getUser().getProfileImageURL().toString(); tweet.userId = status.getUser().getId(); tweet.user = status.getUser(); tweet.thumbnail_pic = status.getThumbnail_pic(); tweet.bmiddle_pic = status.getBmiddle_pic(); tweet.original_pic = status.getOriginal_pic(); tweet.source = TextHelper.getSimpleTweetText(status.getSource()); return tweet; } public static Tweet createFromSearchApi(JSONObject jsonObject) throws JSONException { Tweet tweet = new Tweet(); tweet.id = jsonObject.getString("id") + ""; //转义符放到getSimpleTweetText里去处理,这里不做处理 tweet.text = jsonObject.getString("text"); tweet.createdAt = DateTimeHelper.parseSearchApiDateTime(jsonObject.getString("created_at")); tweet.favorited = jsonObject.getString("favorited"); tweet.truncated = jsonObject.getString("truncated"); tweet.inReplyToStatusId = jsonObject.getString("in_reply_to_status_id"); tweet.inReplyToUserId = jsonObject.getString("in_reply_to_user_id"); tweet.inReplyToScreenName = jsonObject.getString("in_reply_to_screen_name"); tweet.screenName = TextHelper.getSimpleTweetText(jsonObject.getString("from_user")); tweet.profileImageUrl = jsonObject.getString("profile_image_url"); tweet.userId = jsonObject.getString("from_user_id"); tweet.source = TextHelper.getSimpleTweetText(jsonObject.getString("source")); return tweet; } public static String buildMetaText(StringBuilder builder, Date createdAt, String source, String replyTo) { builder.setLength(0); builder.append(DateTimeHelper.getRelativeDate(createdAt)); builder.append(" "); builder.append(TwitterApplication.mContext.getString(R.string.tweet_source_prefix)); builder.append(source); if (!TextUtils.isEmpty(replyTo)) { builder.append(" " + TwitterApplication.mContext.getString(R.string.tweet_reply_to_prefix)); builder.append(replyTo); builder.append(TwitterApplication.mContext.getString(R.string.tweet_reply_to_suffix)); } return builder.toString(); } // For interface Parcelable public int describeContents() { return 0; } public void writeToParcel(Parcel out, int flags) { out.writeString(id); out.writeString(text); out.writeValue(createdAt); //Date out.writeString(screenName); out.writeString(favorited); out.writeString(inReplyToStatusId); out.writeString(inReplyToUserId); out.writeString(inReplyToScreenName); out.writeString(screenName); out.writeString(profileImageUrl); out.writeString(thumbnail_pic); out.writeString(bmiddle_pic); out.writeString(original_pic); out.writeString(userId); out.writeString(source); } public static final Parcelable.Creator<Tweet> CREATOR = new Parcelable.Creator<Tweet>() { public Tweet createFromParcel(Parcel in) { return new Tweet(in); } public Tweet[] newArray(int size) { // return new Tweet[size]; throw new UnsupportedOperationException(); } }; public Tweet(Parcel in) { id = in.readString(); text = in.readString(); createdAt = (Date) in.readValue(Date.class.getClassLoader()); screenName = in.readString(); favorited = in.readString(); inReplyToStatusId = in.readString(); inReplyToUserId = in.readString(); inReplyToScreenName = in.readString(); screenName = in.readString(); profileImageUrl = in.readString(); thumbnail_pic = in.readString(); bmiddle_pic = in.readString(); original_pic = in.readString(); userId = in.readString(); source = in.readString(); } @Override public String toString() { return "Tweet [source=" + source + ", id=" + id + ", screenName=" + screenName + ", text=" + text + ", profileImageUrl=" + profileImageUrl + ", createdAt=" + createdAt + ", userId=" + userId + ", favorited=" + favorited + ", inReplyToStatusId=" + inReplyToStatusId + ", inReplyToUserId=" + inReplyToUserId + ", inReplyToScreenName=" + inReplyToScreenName + "]"; } }
Java
package com.ch_linghu.fanfoudroid.data; import android.database.Cursor; public interface BaseContent { long insert(); int delete(); int update(); Cursor select(); }
Java
package com.ch_linghu.fanfoudroid.data; import com.ch_linghu.fanfoudroid.fanfou.DirectMessage; import com.ch_linghu.fanfoudroid.fanfou.User; import com.ch_linghu.fanfoudroid.util.TextHelper; public class Dm extends Message { @SuppressWarnings("unused") private static final String TAG = "Dm"; public boolean isSent; public static Dm create(DirectMessage directMessage, boolean isSent){ Dm dm = new Dm(); dm.id = directMessage.getId(); dm.text = directMessage.getText(); dm.createdAt = directMessage.getCreatedAt(); dm.isSent = isSent; User user = dm.isSent ? directMessage.getRecipient() : directMessage.getSender(); dm.screenName = TextHelper.getSimpleTweetText(user.getScreenName()); dm.userId = user.getId(); dm.profileImageUrl = user.getProfileImageURL().toString(); return dm; } }
Java
package com.ch_linghu.fanfoudroid.data; import java.util.Date; import android.os.Parcel; import android.os.Parcelable; public class User implements Parcelable { public String id; public String name; public String screenName; public String location; public String description; public String profileImageUrl; public String url; public boolean isProtected; public int followersCount; public String lastStatus; public int friendsCount; public int favoritesCount; public int statusesCount; public Date createdAt; public boolean isFollowing; // public boolean notifications; // public utc_offset public User() {} public static User create(com.ch_linghu.fanfoudroid.fanfou.User u) { User user = new User(); user.id = u.getId(); user.name = u.getName(); user.screenName = u.getScreenName(); user.location = u.getLocation(); user.description = u.getDescription(); user.profileImageUrl = u.getProfileImageURL().toString(); if (u.getURL() != null) { user.url = u.getURL().toString(); } user.isProtected = u.isProtected(); user.followersCount = u.getFollowersCount(); user.lastStatus = u.getStatusText(); user.friendsCount = u.getFriendsCount(); user.favoritesCount = u.getFavouritesCount(); user.statusesCount = u.getStatusesCount(); user.createdAt = u.getCreatedAt(); user.isFollowing = u.isFollowing(); return user; } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel out, int flags) { boolean[] boolArray = new boolean[] { isProtected, isFollowing }; out.writeString(id); out.writeString(name); out.writeString(screenName); out.writeString(location); out.writeString(description); out.writeString(profileImageUrl); out.writeString(url); out.writeBooleanArray(boolArray); out.writeInt(friendsCount); out.writeInt(followersCount); out.writeInt(statusesCount); } public static final Parcelable.Creator<User> CREATOR = new Parcelable.Creator<User>() { public User createFromParcel(Parcel in) { return new User(in); } public User[] newArray(int size) { // return new User[size]; throw new UnsupportedOperationException(); } }; public User(Parcel in){ boolean[] boolArray = new boolean[]{isProtected, isFollowing}; id = in.readString(); name = in.readString(); screenName = in.readString(); location = in.readString(); description = in.readString(); profileImageUrl = in.readString(); url = in.readString(); in.readBooleanArray(boolArray); friendsCount = in.readInt(); followersCount = in.readInt(); statusesCount = in.readInt(); isProtected = boolArray[0]; isFollowing = boolArray[1]; } }
Java
package com.ch_linghu.fanfoudroid.data; import java.util.Date; public class Message { public String id; public String screenName; public String text; public String profileImageUrl; public Date createdAt; public String userId; public String favorited; public String truncated; public String inReplyToStatusId; public String inReplyToUserId; public String inReplyToScreenName; public String thumbnail_pic; public String bmiddle_pic; public String original_pic; }
Java