code
stringlengths
3
1.18M
language
stringclasses
1 value
/* * 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
/**************************************************************************** * Copyright 2009 kraigs.android@gmail.com * 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.angrydoughnuts.android.brightprof; import java.math.BigDecimal; import android.content.ContentResolver; import android.provider.Settings; import android.provider.Settings.SettingNotFoundException; import android.view.Window; import android.view.WindowManager; public class Util { /** * Calculates the current application-defined brightness value of the phone. * This is done by taking the actual system brightness (a value from 0 to 255) * and normalizing it to a scale of 0 to 100. The actual brightness percentage * is calculated on the scale of minimumBrightness to 255, though. * * @param resolver * The ContentResolver. * @param db * A database accessor pointing to a DB with the minimum * brightness setting in it. * @return A value between 0 and 100. */ static int getPhoneBrighness(ContentResolver resolver, DbAccessor db) { int systemBrightness = getSystemBrightness(resolver); int minValue = db.getMinimumBrightness(); // The system brightness can range from 0 to 255. To normalize this // to the application's 0 to 100 brightness values, we lookup the // configured minimum value and then normalize for the range // minValue to 255. BigDecimal d = new BigDecimal((systemBrightness - minValue) / (255.0 - minValue) * 100.0); d = d.setScale(0, BigDecimal.ROUND_HALF_EVEN); int normalizedBrightness = d.intValue(); if (normalizedBrightness < 0) { // This can happen if another application sets the phone's brightness // to a value lower than our configured minimum. return 0; } else { return normalizedBrightness; } } /** * Finds the phone's system brightness setting. Returns 0 if there is an error * getting this setting. * * @param resolver * The ContentResolver. * @return A value between 0 and 255. */ static int getSystemBrightness(ContentResolver resolver) { // Lookup the initial system brightness. int systemBrightness = 0; try { systemBrightness = Settings.System.getInt(resolver, Settings.System.SCREEN_BRIGHTNESS); } catch (SettingNotFoundException e) { // TODO Log an error message. } return systemBrightness; } /** * Sets the brightness for the activity supplied as well as the system * brightness level. The brightness value passed in should be an integer * between 0 and 100. This method will translate that number into a normalized * value using the devices actual maximum brightness level and the minimum * brightness level calibrated via the CalibrateActivity activity. * * @param resolver * The ContentResolver. * @param window * The activity Window. * @param brightnessPercentage * An integer between 0 and 100. */ static void setPhoneBrightness(ContentResolver resolver, Window window, DbAccessor db, int brightnessPercentage) { // Lookup the minimum acceptable brightness set by the CalibrationActivity. int min_value = db.getMinimumBrightness(); // Convert the normalized application brightness to a system value (between // min_value and 255). BigDecimal d = new BigDecimal((brightnessPercentage / 100.0) * (255 - min_value) + min_value); d = d.setScale(0, BigDecimal.ROUND_HALF_EVEN); int brightnessUnits = d.intValue(); if (brightnessUnits < min_value) { brightnessUnits = min_value; } else if (brightnessUnits > 255) { brightnessUnits = 255; } setSystemBrightness(resolver, brightnessUnits); setActivityBrightness(window, brightnessUnits); } /** * Sets the phone's global brightness level. This does not change the screen's * brightness immediately. Valid brightnesses range from 0 to 255. * * @param resolver * The ContentResolver. * @param brightnessUnits * An integer between 0 and 255. */ static void setSystemBrightness(ContentResolver resolver, int brightnessUnits) { // Change the system brightness setting. This doesn't change the // screen brightness immediately. (Scale 0 - 255). Settings.System.putInt(resolver, Settings.System.SCREEN_BRIGHTNESS, brightnessUnits); } /** * Sets the screen brightness for this activity. The screen brightness will * change immediately. As soon as the activity terminates, the brightness will * return to the system brightness. Valid brightnesses range from 0 to 255. * * @param window * The activity window. * @param brightnessUnits * An integer between 0 and 255. */ static void setActivityBrightness(Window window, int brightnessUnits) { // Set the brightness of the current window. This takes effect immediately. // When the window is closed, the new system brightness is used. // (Scale 0.0 - 1.0). WindowManager.LayoutParams lp = window.getAttributes(); lp.screenBrightness = brightnessUnits / 255.0f; window.setAttributes(lp); } // These constants are not exposed through the API, but are defined in // Settings.System: // http://android.git.kernel.org/?p=platform/frameworks/base.git;a=blob;f=core/java/android/provider/Settings.java;h=f7e55db80b8849c023152ad06d97040199c4e8c5;hb=HEAD private static final String SCREEN_BRIGHTNESS_MODE = "screen_brightness_mode"; private static final int SCREEN_BRIGHTNESS_MODE_MANUAL = 0; private static final int SCREEN_BRIGHTNESS_MODE_AUTOMATIC = 1; static boolean supportsAutoBrightness(ContentResolver resolver) { // This is probably not the best way to do this. The actual capability // is stored in // com.android.internal.R.bool.config_automatic_brightness_available // which is not available through the API. try { Settings.System.getInt(resolver, SCREEN_BRIGHTNESS_MODE); return true; } catch (SettingNotFoundException e) { return false; } } static boolean getAutoBrightnessEnabled(ContentResolver resolver) { try { int autobright = Settings.System.getInt(resolver, SCREEN_BRIGHTNESS_MODE); return autobright == SCREEN_BRIGHTNESS_MODE_AUTOMATIC; } catch (SettingNotFoundException e) { return false; } } static void setAutoBrightnessEnabled(ContentResolver resolver, boolean enabled) { if (enabled) { Settings.System.putInt(resolver, SCREEN_BRIGHTNESS_MODE, SCREEN_BRIGHTNESS_MODE_AUTOMATIC); } else { Settings.System.putInt(resolver, SCREEN_BRIGHTNESS_MODE, SCREEN_BRIGHTNESS_MODE_MANUAL); } } }
Java
/**************************************************************************** * Copyright 2009 kraigs.android@gmail.com * 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.angrydoughnuts.android.brightprof; import android.app.Activity; import android.content.Intent; import android.database.Cursor; import android.os.Bundle; import android.view.ContextMenu; import android.view.KeyEvent; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ContextMenu.ContextMenuInfo; import android.widget.AdapterView; import android.widget.Button; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.ListView; import android.widget.SeekBar; import android.widget.SimpleCursorAdapter; import android.widget.TextView; import android.widget.AdapterView.AdapterContextMenuInfo; import android.widget.AdapterView.OnItemClickListener; public class BrightnessProfiles extends Activity { private static final int ACTIVITY_EDIT = 0; private static final int ACTIVITY_CALIBRATE = 1; private static final int MENU_EDIT = 0; private static final int MENU_DELETE = 1; private static final int OPTION_CALIBRATE = 0; private int appBrightness; private DbAccessor dbAccessor; private Cursor listViewCursor; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Initialize the database helper. dbAccessor = new DbAccessor(this); setContentView(R.layout.main); // Button to close the main window. Button closeBtn = (Button) findViewById(R.id.close_button); closeBtn.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { finish(); } }); // Button to open the edit dialog (in add mode). Button addBtn = (Button) findViewById(R.id.add_button); addBtn.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { Intent i = new Intent(getApplication(), EditActivity.class); startActivityForResult(i, ACTIVITY_EDIT); } }); // Setup auto brightness checkbox handler. CheckBox checkbox = (CheckBox) findViewById(R.id.auto_brightness); checkbox.setOnCheckedChangeListener(new CheckBox.OnCheckedChangeListener() { public void onCheckedChanged( CompoundButton buttonView, boolean isChecked) { Util.setAutoBrightnessEnabled(getContentResolver(), isChecked); lockBrightnessControls(isChecked); // Update the app brightness in case auto brightness changed it. appBrightness = Util.getPhoneBrighness(getContentResolver(), dbAccessor); setBrightness(appBrightness); refreshDisplay(); } }); // Setup slider. SeekBar slider = (SeekBar) findViewById(R.id.slider); slider.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { public void onProgressChanged(SeekBar seekBar, int progress, boolean fromTouch) { if (fromTouch) { setBrightness(progress); refreshDisplay(); } } public void onStartTrackingTouch(SeekBar seekBar) { } public void onStopTrackingTouch(SeekBar seekBar) { } }); // Get a database cursor. listViewCursor = dbAccessor.getAllProfiles(); startManagingCursor(listViewCursor); // Populate the list view using the Cursor. String[] from = new String[] { "name" }; int[] to = new int[] { R.id.profile_name }; SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.profile, listViewCursor, from, to); ListView profileList = (ListView) findViewById(R.id.profile_list); profileList.setAdapter(adapter); // Set the per-item click handler. profileList.setOnItemClickListener(new OnItemClickListener() { public void onItemClick(AdapterView<?> parent, View view, int position, long id) { listViewCursor.moveToPosition(position); int brightness = listViewCursor.getInt(listViewCursor .getColumnIndexOrThrow(DbHelper.PROF_VALUE_COL)); setBrightness(brightness); // TODO(cgallek): This will terminate the application after a profile // is selected. Consider making this a configurable option. finish(); } }); registerForContextMenu(profileList); } @Override protected void onDestroy() { dbAccessor.closeConnections(); super.onDestroy(); } @Override protected void onResume() { // Lookup the initial system brightness and set our app's brightness // percentage appropriately. appBrightness = Util.getPhoneBrighness(getContentResolver(), dbAccessor); // Set the value for the brightness text field and slider. refreshDisplay(); super.onResume(); } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { menu.add(Menu.NONE, MENU_EDIT, Menu.NONE, R.string.edit); menu.add(Menu.NONE, MENU_DELETE, Menu.NONE, R.string.delete); } @Override public boolean onContextItemSelected(MenuItem item) { AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo(); switch (item.getItemId()) { case MENU_EDIT: listViewCursor.moveToPosition(info.position); Intent i = new Intent(getApplication(), EditActivity.class); i.putExtra(DbHelper.PROF_ID_COL, listViewCursor.getInt(listViewCursor .getColumnIndexOrThrow(DbHelper.PROF_ID_COL))); i.putExtra(DbHelper.PROF_NAME_COL, listViewCursor .getString(listViewCursor .getColumnIndexOrThrow(DbHelper.PROF_NAME_COL))); i.putExtra(DbHelper.PROF_VALUE_COL, listViewCursor .getInt(listViewCursor .getColumnIndexOrThrow(DbHelper.PROF_VALUE_COL))); startActivityForResult(i, ACTIVITY_EDIT); return true; case MENU_DELETE: listViewCursor.moveToPosition(info.position); int id = listViewCursor.getInt(listViewCursor .getColumnIndexOrThrow(DbHelper.PROF_ID_COL)); dbAccessor.deletProfile(id); listViewCursor.requery(); return true; default: return super.onContextItemSelected(item); } } @Override public boolean onCreateOptionsMenu(Menu menu) { boolean result = super.onCreateOptionsMenu(menu); MenuItem calibrate = menu.add(0, OPTION_CALIBRATE, 0, R.string.calibrate); calibrate.setIcon(android.R.drawable.ic_menu_preferences); return result; } @Override public boolean onPrepareOptionsMenu(Menu menu) { boolean result = super.onPrepareOptionsMenu(menu); // Don't setup the calibrate menu item if auto brightness is enabled. // Trying to calibrate while it's on is weird... MenuItem calibrate = menu.findItem(OPTION_CALIBRATE); if (Util.supportsAutoBrightness(getContentResolver()) && Util.getAutoBrightnessEnabled(getContentResolver())) { calibrate.setEnabled(false); } else { calibrate.setEnabled(true); } return result; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case OPTION_CALIBRATE: Intent i = new android.content.Intent(getApplicationContext(), CalibrateActivity.class); startActivityForResult(i, ACTIVITY_CALIBRATE); break; } return super.onOptionsItemSelected(item); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { switch (keyCode) { case KeyEvent.KEYCODE_VOLUME_DOWN: setBrightness(getBrightness() - 10); return true; case KeyEvent.KEYCODE_VOLUME_UP: setBrightness(getBrightness() + 10); return true; default: return super.onKeyDown(keyCode, event); } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (resultCode == RESULT_CANCELED) { return; } if (requestCode != ACTIVITY_EDIT) { return; } Bundle extras = data.getExtras(); int id = extras.getInt(DbHelper.PROF_ID_COL); switch (resultCode) { case Activity.RESULT_OK: String name = extras.getString(DbHelper.PROF_NAME_COL); int brightness = extras.getInt(DbHelper.PROF_VALUE_COL); dbAccessor.updateProfile(id, name, brightness); listViewCursor.requery(); break; } } private void refreshDisplay() { TextView brightnessText = (TextView) findViewById(R.id.brightness); brightnessText.setText(getString(R.string.brightness) + " " + getBrightness() + "%"); SeekBar slider = (SeekBar) findViewById(R.id.slider); slider.setProgress(getBrightness()); // Show/Hide the auto brightness check box. CheckBox checkbox = (CheckBox) findViewById(R.id.auto_brightness); if (Util.supportsAutoBrightness(getContentResolver())) { checkbox.setVisibility(View.VISIBLE); if (Util.getAutoBrightnessEnabled(getContentResolver())) { checkbox.setChecked(true); lockBrightnessControls(true); } else { checkbox.setChecked(false); lockBrightnessControls(false); } } else { checkbox.setVisibility(View.GONE); lockBrightnessControls(false); } } private int getBrightness() { return appBrightness; } private void setBrightness(int brightness) { // Don't try to adjust brightness if auto brightness is enabled. if (Util.supportsAutoBrightness(getContentResolver()) && Util.getAutoBrightnessEnabled(getContentResolver())) { return; } if (brightness < 0) { appBrightness = 0; } else if (brightness > 100) { appBrightness = 100; } else { appBrightness = brightness; } Util.setPhoneBrightness(getContentResolver(), getWindow(), dbAccessor, appBrightness); refreshDisplay(); } private void lockBrightnessControls(boolean lock) { SeekBar slider = (SeekBar) findViewById(R.id.slider); ListView profileList = (ListView) findViewById(R.id.profile_list); // Note: setEnabled() doesn't seem to work with this ListView, nor does // calling setEnabled() on the individual children of the ListView. // The items become grayed out, but the click handlers are still registered. // As a work around, simply hide the entire list view. if (lock) { profileList.setVisibility(View.GONE); slider.setEnabled(false); } else { profileList.setVisibility(View.VISIBLE); slider.setEnabled(true); } } }
Java
/**************************************************************************** * Copyright 2009 kraigs.android@gmail.com * 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.angrydoughnuts.android.brightprof; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; public class EditActivity extends Activity { private static final int UNKNOWN_ID = -1; private int profile_id_ = UNKNOWN_ID; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.edit); Button okButton = (Button) findViewById(R.id.ok_button); Button cancelButton = (Button) findViewById(R.id.cancel_button); cancelButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { setResult(RESULT_CANCELED); finish(); } }); final EditText nameBox = (EditText) findViewById(R.id.edit_name); final EditText brightnessBox = (EditText) findViewById(R.id.edit_brightness); final String name; final int brightness; Bundle extras = getIntent().getExtras(); if (extras == null) { profile_id_ = UNKNOWN_ID; name = ""; brightness = -1; } else { profile_id_ = extras.getInt(DbHelper.PROF_ID_COL); name = extras.getString(DbHelper.PROF_NAME_COL); brightness = extras.getInt(DbHelper.PROF_VALUE_COL); nameBox.setText(name); brightnessBox.setText(Integer.toString(brightness)); } okButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { String newName = nameBox.getText().toString(); String brightnessText = brightnessBox.getText().toString(); int newBrightness = brightness; try { newBrightness = Integer.parseInt(brightnessText); } catch (NumberFormatException e) { newBrightness = -1; } if (newName.length() == 0 || newBrightness < 0 || newBrightness > 100) { // TODO display some kind of error message? return; } // If nothing changed, act as though cancel was pressed. if (name.equals(newName) && brightness == newBrightness) { setResult(RESULT_CANCELED); finish(); } // Bundle up the new values. Bundle bundle = new Bundle(); bundle.putInt(DbHelper.PROF_ID_COL, profile_id_); bundle.putString(DbHelper.PROF_NAME_COL, newName); bundle.putInt(DbHelper.PROF_VALUE_COL, newBrightness); Intent intent = new Intent(); intent.putExtras(bundle); setResult(RESULT_OK, intent); finish(); } }); } }
Java
/**************************************************************************** * Copyright 2009 kraigs.android@gmail.com * 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.angrydoughnuts.android.brightprof; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; public class DbAccessor { private DbHelper db; private SQLiteDatabase rDb; private SQLiteDatabase rwDb; public DbAccessor(Context context) { db = new DbHelper(context); rDb = db.getReadableDatabase(); rwDb = db.getWritableDatabase(); } public void closeConnections() { rDb.close(); rwDb.close(); } public Cursor getAllProfiles() { return rDb.query(DbHelper.DB_TABLE_PROFILES, new String[] { DbHelper.PROF_ID_COL, DbHelper.PROF_NAME_COL, DbHelper.PROF_VALUE_COL }, null, null, null, null, null); } public void updateProfile(int rowId, String name, int brightness) { ContentValues values = new ContentValues(2); values.put(DbHelper.PROF_NAME_COL, name); values.put(DbHelper.PROF_VALUE_COL, brightness); // If this is an unknown row id, create a new row. if (rowId < 0) { rwDb.insert(DbHelper.DB_TABLE_PROFILES, null, values); // Otherwise, update the supplied row id. } else { String where = DbHelper.PROF_ID_COL + " = " + rowId; rwDb.update(DbHelper.DB_TABLE_PROFILES, values, where, null); } } public void deletProfile(int rowId) { String where = DbHelper.PROF_ID_COL + " = " + rowId; rwDb.delete(DbHelper.DB_TABLE_PROFILES, where, null); } public int getMinimumBrightness() { Cursor c = rDb.query(DbHelper.DB_TABLE_CALIBRATE, new String[] { DbHelper.CALIB_MIN_BRIGHT_COL }, null, null, null, null, null); c.moveToFirst(); int b = c.getInt(c.getColumnIndexOrThrow(DbHelper.CALIB_MIN_BRIGHT_COL)); c.deactivate(); c.close(); return b; } public void setMinimumBrightness(int brightness) { ContentValues values = new ContentValues(1); values.put(DbHelper.CALIB_MIN_BRIGHT_COL, brightness); rwDb.update(DbHelper.DB_TABLE_CALIBRATE, values, null, null); } }
Java
/**************************************************************************** * Copyright 2009 kraigs.android@gmail.com * 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.angrydoughnuts.android.brightprof; import android.app.Activity; import android.os.Bundle; import android.view.KeyEvent; import android.view.View; import android.widget.Button; import android.widget.TextView; public class CalibrateActivity extends Activity { private int minBrightness = 20; private DbAccessor db; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.calibrate); Button okButton = (Button) findViewById(R.id.ok_button); Button cancelButton = (Button) findViewById(R.id.cancel_button); db = new DbAccessor(this); okButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { db.setMinimumBrightness(minBrightness); // If the new minimum brightness is greater than the current screen // setting, update the setting. if (minBrightness > Util.getSystemBrightness(getContentResolver())) { Util.setSystemBrightness(getContentResolver(), minBrightness); } setResult(RESULT_OK); finish(); } }); cancelButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { setResult(RESULT_CANCELED); finish(); } }); } @Override protected void onDestroy() { db.closeConnections(); super.onDestroy(); } @Override protected void onResume() { super.onResume(); updateDisplay(); Util.setActivityBrightness(getWindow(), minBrightness); TextView current_minimum_brightness = (TextView) findViewById(R.id.current_min_brightness); current_minimum_brightness.setText("" + db.getMinimumBrightness()); } @Override protected void onPause() { // Return the brightness to it's previous state when the dialog closes. Util.setActivityBrightness(getWindow(), -1); super.onPause(); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { switch (keyCode) { case KeyEvent.KEYCODE_VOLUME_DOWN: // Don't allow this value to go to 0. It shuts the screen off. if (minBrightness > 1) { minBrightness -= 1; updateDisplay(); Util.setActivityBrightness(getWindow(), minBrightness); } return true; case KeyEvent.KEYCODE_VOLUME_UP: if (minBrightness < 255) { minBrightness += 1; updateDisplay(); Util.setActivityBrightness(getWindow(), minBrightness); } return true; default: return super.onKeyDown(keyCode, event); } } private void updateDisplay() { TextView test_min_brightness = (TextView) findViewById(R.id.test_min_brightness); test_min_brightness.setText("" + minBrightness); } }
Java
/**************************************************************************** * Copyright 2009 kraigs.android@gmail.com * 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.angrydoughnuts.android.brightprof; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; public class DbHelper extends SQLiteOpenHelper { public static final String DB_NAME = "brightprof"; public static final String DB_TABLE_PROFILES = "profiles"; public static final String DB_TABLE_CALIBRATE = "calibrate"; public static final int DB_VERSION = 3; public static final String PROF_ID_COL = "_id"; public static final String PROF_NAME_COL = "name"; public static final String PROF_VALUE_COL = "value"; public static final String CALIB_MIN_BRIGHT_COL = "min_bright"; public DbHelper(Context context) { super(context, DB_NAME, null, DB_VERSION); } @Override public void onCreate(SQLiteDatabase db) { // Table to hold information for each profile. db.execSQL("CREATE TABLE " + DB_TABLE_PROFILES + " (" + PROF_ID_COL + " INTEGER PRIMARY KEY AUTOINCREMENT, " + PROF_NAME_COL + " TEXT NOT NULL," + PROF_VALUE_COL + " UNSIGNED INTEGER (0, 100))"); db.execSQL("INSERT INTO " + DB_TABLE_PROFILES + "( " + PROF_NAME_COL + ", " + PROF_VALUE_COL + ") VALUES ('Low', 0)"); db.execSQL("INSERT INTO " + DB_TABLE_PROFILES + "( " + PROF_NAME_COL + ", " + PROF_VALUE_COL + ") VALUES ('Normal', 15)"); db.execSQL("INSERT INTO " + DB_TABLE_PROFILES + "( " + PROF_NAME_COL + ", " + PROF_VALUE_COL + ") VALUES ('High', 100)"); createCalibrationTable(db); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { // DB version 3 added a table for keeping track of minimum brightness. // It is no longer necessary to enforce this minimum in the profile table // (as values 0 through 100 are now valid). // This creates the new minimum brightness table for old installs. if (oldVersion < 3) { createCalibrationTable(db); } } void createCalibrationTable(SQLiteDatabase db) { // Table to hold calibration settings. db.execSQL("CREATE TABLE " + DB_TABLE_CALIBRATE + " (" + CALIB_MIN_BRIGHT_COL + " UNSIGNED INTEGER (1, 255))"); db.execSQL("INSERT INTO " + DB_TABLE_CALIBRATE + "( " + CALIB_MIN_BRIGHT_COL + ") VALUES (10)"); } }
Java
/**************************************************************************** * Copyright 2010 kraigs.android@gmail.com * 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.angrydoughnuts.android.alarmclock; import java.util.Calendar; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.os.Handler; import android.text.format.DateFormat; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.ViewStub; import android.view.View.OnFocusChangeListener; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.TextView.OnEditorActionListener; /** * This class is a slight improvement over the android time picker dialog. * It allows the user to select hour, minute, and second (the android picker * does not support seconds). It also has a configurable increment feature * (30, 5, and 1). */ public final class TimePickerDialog extends AlertDialog { public interface OnTimeSetListener { public void onTimeSet(int hourOfDay, int minute, int second); } private static final String PICKER_PREFS = "TimePickerPreferences"; private static final String INCREMENT_PREF = "increment"; private OnTimeSetListener listener; private SharedPreferences prefs; private Calendar calendar; private TextView timeText; private Button amPmButton; private PickerView hourPicker; private PickerView minutePicker; private PickerView secondPicker; /** * Construct a time picker with the supplied hour minute and second. * @param context * @param title Dialog title. * @param hourOfDay 0 to 23. * @param minute 0 to 60. * @param second 0 to 60. * @param showSeconds Show/hide the seconds field. * @param setListener Callback for when the user selects 'OK'. */ public TimePickerDialog(Context context, String title, int hourOfDay, int minute, int second, final boolean showSeconds, OnTimeSetListener setListener) { this(context, title, showSeconds, setListener); calendar.set(Calendar.HOUR_OF_DAY, hourOfDay); hourPicker.pickerRefresh(); calendar.set(Calendar.MINUTE, minute); minutePicker.pickerRefresh(); calendar.set(Calendar.SECOND, second); if (showSeconds) { secondPicker.pickerRefresh(); } dialogRefresh(); } /** * Construct a time picker with 'now' as the starting time. * @param context * @param title Dialog title. * @param showSeconds Show/hid the seconds field. * @param setListener Callback for when the user selects 'OK'. */ public TimePickerDialog(Context context, String title, final boolean showSeconds, OnTimeSetListener setListener) { super(context); listener = setListener; prefs = context.getSharedPreferences(PICKER_PREFS, Context.MODE_PRIVATE); calendar = Calendar.getInstance(); // The default increment amount is stored in a shared preference. Look // it up. final int incPref = prefs.getInt(INCREMENT_PREF, IncrementValue.FIVE.ordinal()); final IncrementValue defaultIncrement = IncrementValue.values()[incPref]; // OK button setup. setButton(AlertDialog.BUTTON_POSITIVE, context.getString(R.string.ok), new OnClickListener(){ public void onClick(DialogInterface dialog, int which) { if (listener == null) { return; } int seconds = showSeconds ? calendar.get(Calendar.SECOND) : 0; listener.onTimeSet( calendar.get(Calendar.HOUR_OF_DAY), calendar.get(Calendar.MINUTE), seconds); } }); // Cancel button setup. setButton(AlertDialog.BUTTON_NEGATIVE, context.getString(R.string.cancel), new OnClickListener(){ public void onClick(DialogInterface dialog, int which) { cancel(); } }); // Set title and icon. if (title.length() != 0) { setTitle(title); setIcon(R.drawable.ic_dialog_time); } // Set the view for the body section of the AlertDialog. final LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); final View body_view = inflater.inflate(R.layout.time_picker_dialog, null); setView(body_view); // Setup each of the components of the body section. timeText = (TextView) body_view.findViewById(R.id.picker_text); amPmButton = (Button) body_view.findViewById(R.id.picker_am_pm); amPmButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (calendar.get(Calendar.AM_PM) == Calendar.AM) { calendar.set(Calendar.AM_PM, Calendar.PM); } else { calendar.set(Calendar.AM_PM, Calendar.AM); } dialogRefresh(); } }); // Setup the three time fields. if (DateFormat.is24HourFormat(getContext())) { body_view.findViewById(R.id.picker_am_pm_layout).setVisibility(View.GONE); hourPicker = new PickerView(Calendar.HOUR_OF_DAY, "%02d"); } else { body_view.findViewById(R.id.picker_am_pm_layout).setVisibility(View.VISIBLE); hourPicker = new PickerView(Calendar.HOUR, "%d"); } hourPicker.inflate(body_view, R.id.picker_hour, false, IncrementValue.ONE); minutePicker = new PickerView(Calendar.MINUTE, "%02d"); minutePicker.inflate(body_view, R.id.picker_minute, true, defaultIncrement); if (showSeconds) { secondPicker = new PickerView(Calendar.SECOND, "%02d"); secondPicker.inflate(body_view, R.id.picker_second, true, defaultIncrement); } dialogRefresh(); } private void dialogRefresh() { AlarmTime time = new AlarmTime( calendar.get(Calendar.HOUR_OF_DAY), calendar.get(Calendar.MINUTE), calendar.get(Calendar.SECOND)); timeText.setText(time.timeUntilString(getContext())); if (calendar.get(Calendar.AM_PM) == Calendar.AM) { amPmButton.setText(getContext().getString(R.string.am)); } else { amPmButton.setText(getContext().getString(R.string.pm)); } } /** * Enum that represents the states of the increment picker button. */ private enum IncrementValue { FIVE(5), ONE(1); private int value; IncrementValue(int value) { this.value = value; } public int value() { return value; } } /** * Helper class that wraps up the view elements of each number picker * (plus/minus button, text field, increment picker). */ private final class PickerView { private int calendarField; private String formatString; private EditText text = null; private Increment increment = null; private Button incrementValueButton = null; private Button plus = null; private Button minus = null; /** * Construct a numeric picker for the supplied calendar field and formats * it according to the supplied format string. * @param calendarField * @param formatString */ public PickerView(int calendarField, String formatString) { this.calendarField = calendarField; this.formatString = formatString; } /** * Inflates the ViewStub for this numeric picker. * @param parentView * @param resourceId * @param showIncrement * @param defaultIncrement */ public void inflate(View parentView, int resourceId, boolean showIncrement, IncrementValue defaultIncrement) { final ViewStub stub = (ViewStub) parentView.findViewById(resourceId); final View view = stub.inflate(); text = (EditText) view.findViewById(R.id.time_value); text.setOnFocusChangeListener(new TextChangeListener()); text.setOnEditorActionListener(new TextChangeListener()); increment = new Increment(defaultIncrement); incrementValueButton = (Button) view.findViewById(R.id.time_increment); incrementValueButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { increment.cycleToNext(); Editor editor = prefs.edit(); editor.putInt(INCREMENT_PREF, increment.value.ordinal()); editor.commit(); pickerRefresh(); } }); if (showIncrement) { incrementValueButton.setVisibility(View.VISIBLE); } else { incrementValueButton.setVisibility(View.GONE); } plus = (Button) view.findViewById(R.id.time_plus); TimeIncrementListener incrementListener = new TimeIncrementListener(); plus.setOnClickListener(incrementListener); plus.setOnTouchListener(incrementListener); plus.setOnLongClickListener(incrementListener); minus = (Button) view.findViewById(R.id.time_minus); TimeDecrementListener decrementListener= new TimeDecrementListener(); minus.setOnClickListener(decrementListener); minus.setOnTouchListener(decrementListener); minus.setOnLongClickListener(decrementListener); pickerRefresh(); } public void pickerRefresh() { int fieldValue = calendar.get(calendarField); if (calendarField == Calendar.HOUR && fieldValue == 0) { fieldValue = 12; } text.setText(String.format(formatString, fieldValue)); incrementValueButton.setText("+/- " + increment.nextValue().value()); plus.setText("+" + increment.value()); minus.setText("-" + increment.value()); dialogRefresh(); } private final class Increment { private IncrementValue value; public Increment(IncrementValue value) { this.value = value; } public IncrementValue nextValue() { int nextIndex = (value.ordinal() + 1) % IncrementValue.values().length; return IncrementValue.values()[nextIndex]; } public void cycleToNext() { value = nextValue(); } public int value() { return value.value(); } } /** * Listener that figures out what the next value should be when a numeric * picker plus/minus button is clicked. It will round up/down to the next * interval increment then increment by the increment amount on subsequent * clicks. */ private abstract class TimeAdjustListener implements View.OnClickListener, View.OnTouchListener, View.OnLongClickListener { protected abstract int sign(); private void adjust() { int currentValue = calendar.get(calendarField); int remainder = currentValue % increment.value(); if (remainder == 0) { calendar.roll(calendarField, sign() * increment.value()); } else { int difference; if (sign() > 0) { difference = increment.value() - remainder; } else { difference = -1 * remainder; } calendar.roll(calendarField, difference); } pickerRefresh(); } private Handler handler = new Handler(); private Runnable delayedAdjust = new Runnable() { @Override public void run() { adjust(); handler.postDelayed(delayedAdjust, 150); } }; @Override public void onClick(View v) { adjust(); } @Override public boolean onLongClick(View v) { delayedAdjust.run(); return false; } @Override public boolean onTouch(View v, MotionEvent event) { if (event.getAction() == MotionEvent.ACTION_UP) { handler.removeCallbacks(delayedAdjust); } return false; } } private final class TimeIncrementListener extends TimeAdjustListener { @Override protected int sign() { return 1; } } private final class TimeDecrementListener extends TimeAdjustListener { @Override protected int sign() { return -1; } } /** * Listener to handle direct user input into the time picker text fields. * Updates after the editor confirmation button is picked or when the * text field loses focus. */ private final class TextChangeListener implements OnFocusChangeListener, OnEditorActionListener { private void handleChange() { try { int newValue = Integer.parseInt(text.getText().toString()); if (calendarField == Calendar.HOUR && newValue == 12 && calendar.get(Calendar.AM_PM) == Calendar.AM) { calendar.set(Calendar.HOUR_OF_DAY, 0); } else if (calendarField == Calendar.HOUR && newValue == 12 && calendar.get(Calendar.AM_PM) == Calendar.PM) { calendar.set(Calendar.HOUR_OF_DAY, 12); } else { calendar.set(calendarField, newValue); } } catch (NumberFormatException e) {} pickerRefresh(); } @Override public void onFocusChange(View v, boolean hasFocus) { handleChange(); } @Override public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { handleChange(); return false; } } } }
Java
/**************************************************************************** * Copyright 2010 kraigs.android@gmail.com * 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.angrydoughnuts.android.alarmclock; import android.app.Activity; import android.content.Context; import android.media.MediaPlayer; import android.net.Uri; import android.provider.MediaStore.Audio.Albums; import android.provider.MediaStore.Audio.ArtistColumns; import android.util.AttributeSet; import android.view.View; import android.widget.AdapterView; import android.widget.ViewFlipper; public class MediaArtistsView extends MediaListView { private final String[] artistsColumns = new String[] { ArtistColumns.ARTIST, ArtistColumns.ARTIST_KEY }; private final int[] artistsResIDs = new int[] { R.id.media_value, R.id.media_key }; private MediaAlbumsView albumsView; public MediaArtistsView(Context context) { this(context, null); } public MediaArtistsView(Context context, AttributeSet attrs) { this(context, attrs, 0); } public MediaArtistsView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); albumsView = new MediaAlbumsView(context); } @Override public void setCursorManager(Activity activity) { super.setCursorManager(activity); albumsView.setCursorManager(activity); } @Override public void addToFlipper(ViewFlipper flipper) { super.addToFlipper(flipper); albumsView.addToFlipper(flipper); } public void setMediaPlayer(MediaPlayer mPlayer) { albumsView.setMediaPlayer(mPlayer); } public void query(Uri contentUri) { query(contentUri, null); } public void query(Uri contentUri, String selection) { super.query(contentUri, ArtistColumns.ARTIST_KEY, selection, R.layout.media_picker_row, artistsColumns, artistsResIDs); } @Override public void setMediaPickListener(OnItemPickListener listener) { albumsView.setMediaPickListener(listener); } @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { super.onItemClick(parent, view, position, id); albumsView.query(Albums.EXTERNAL_CONTENT_URI, ArtistColumns.ARTIST_KEY + " = '" + getLastSelectedName() + "'"); getFlipper().setInAnimation(getContext(), R.anim.slide_in_left); getFlipper().setOutAnimation(getContext(), R.anim.slide_out_left); getFlipper().showNext(); } }
Java
/**************************************************************************** * Copyright 2010 kraigs.android@gmail.com * 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.angrydoughnuts.android.alarmclock; import java.util.Calendar; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.content.DialogInterface; import android.content.Intent; import android.content.DialogInterface.OnCancelListener; import android.os.Bundle; import android.os.Handler; import android.os.RemoteException; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.widget.AdapterView; import android.widget.Button; import android.widget.ListView; import android.widget.TextView; import android.widget.AdapterView.OnItemClickListener; /** * This is the main Activity for the application. It contains a ListView * for displaying all alarms, a simple clock, and a button for adding new * alarms. The context menu allows the user to edit default settings. Long- * clicking on the clock will trigger a dialog for enabling/disabling 'debug * mode.' */ public final class ActivityAlarmClock extends Activity { private enum Dialogs { TIME_PICKER, DELETE_CONFIRM }; private enum Menus { DELETE_ALL, DEFAULT_ALARM_SETTINGS, APP_SETTINGS }; private AlarmClockServiceBinder service; private NotificationServiceBinder notifyService; private DbAccessor db; private AlarmViewAdapter adapter; private TextView clock; private Button testBtn; private Button pendingBtn; private Handler handler; private Runnable tickCallback; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.alarm_list); // Access to in-memory and persistent data structures. service = new AlarmClockServiceBinder(getApplicationContext()); db = new DbAccessor(getApplicationContext()); handler = new Handler(); notifyService = new NotificationServiceBinder(getApplicationContext()); // Setup individual UI elements. // A simple clock. clock = (TextView) findViewById(R.id.clock); // Used in debug mode. Schedules an alarm for 5 seconds in the future // when clicked. testBtn = (Button) findViewById(R.id.test_alarm); testBtn.setOnClickListener(new OnClickListener() { public void onClick(View view) { final Calendar testTime = Calendar.getInstance(); testTime.add(Calendar.SECOND, 5); service.createAlarm(new AlarmTime(testTime.get( Calendar.HOUR_OF_DAY), testTime.get(Calendar.MINUTE), testTime.get(Calendar.SECOND))); adapter.requery(); } }); // Displays a list of pending alarms (only visible in debug mode). pendingBtn = (Button) findViewById(R.id.pending_alarms); pendingBtn.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { startActivity( new Intent(getApplicationContext(), ActivityPendingAlarms.class)); } }); // Opens the time picker dialog and allows the user to schedule a new alarm. Button addBtn = (Button) findViewById(R.id.add_alarm); addBtn.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { showDialog(Dialogs.TIME_PICKER.ordinal()); } }); // Setup the alarm list and the underlying adapter. Clicking an individual // item will start the settings activity. final ListView alarmList = (ListView) findViewById(R.id.alarm_list); adapter = new AlarmViewAdapter(this, db, service); alarmList.setAdapter(adapter); alarmList.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapter, View view, int position, long id) { final AlarmInfo info = (AlarmInfo) adapter.getItemAtPosition(position); final Intent i = new Intent(getApplicationContext(), ActivityAlarmSettings.class); i.putExtra(ActivityAlarmSettings.EXTRAS_ALARM_ID, info.getAlarmId()); startActivity(i); } }); // This is a self-scheduling callback that is responsible for refreshing // the screen. It is started in onResume() and stopped in onPause(). tickCallback = new Runnable() { @Override public void run() { // Redraw the screen. redraw(); // Schedule the next update on the next interval boundary. AlarmUtil.Interval interval = AlarmUtil.Interval.MINUTE; if (AppSettings.isDebugMode(getApplicationContext())) { interval = AlarmUtil.Interval.SECOND; } long next = AlarmUtil.millisTillNextInterval(interval); handler.postDelayed(tickCallback, next); } }; } @Override protected void onResume() { super.onResume(); service.bind(); handler.post(tickCallback); adapter.requery(); notifyService.bind(); notifyService.call(new NotificationServiceBinder.ServiceCallback() { @Override public void run(NotificationServiceInterface service) { int count; try { count = service.firingAlarmCount(); } catch (RemoteException e) { return; } finally { handler.post(new Runnable() { @Override public void run() { notifyService.unbind(); } }); } if (count > 0) { Intent notifyActivity = new Intent(getApplicationContext(), ActivityAlarmNotification.class); notifyActivity.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(notifyActivity); } } }); } @Override protected void onPause() { super.onPause(); handler.removeCallbacks(tickCallback); service.unbind(); } @Override protected void onDestroy() { super.onDestroy(); db.closeConnections(); } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuItem delete_all = menu.add(0, Menus.DELETE_ALL.ordinal(), 0, R.string.delete_all); delete_all.setIcon(android.R.drawable.ic_menu_close_clear_cancel); MenuItem alarm_settings = menu.add(0, Menus.DEFAULT_ALARM_SETTINGS.ordinal(), 0, R.string.default_settings); alarm_settings.setIcon(android.R.drawable.ic_lock_idle_alarm); MenuItem app_settings = menu.add(0, Menus.APP_SETTINGS.ordinal(), 0, R.string.app_settings); app_settings.setIcon(android.R.drawable.ic_menu_preferences); return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (Menus.values()[item.getItemId()]) { case DELETE_ALL: showDialog(Dialogs.DELETE_CONFIRM.ordinal()); break; case DEFAULT_ALARM_SETTINGS: Intent alarm_settings = new Intent(getApplicationContext(), ActivityAlarmSettings.class); alarm_settings.putExtra( ActivityAlarmSettings.EXTRAS_ALARM_ID, AlarmSettings.DEFAULT_SETTINGS_ID); startActivity(alarm_settings); break; case APP_SETTINGS: Intent app_settings = new Intent(getApplicationContext(), ActivityAppSettings.class); startActivity(app_settings); break; } return super.onOptionsItemSelected(item); } private final void redraw() { // Show/hide debug buttons. if (AppSettings.isDebugMode(getApplicationContext())) { testBtn.setVisibility(View.VISIBLE); pendingBtn.setVisibility(View.VISIBLE); } else { testBtn.setVisibility(View.GONE); pendingBtn.setVisibility(View.GONE); } // Recompute expiration times in the list view adapter.notifyDataSetChanged(); // Update clock Calendar c = Calendar.getInstance(); AlarmTime time = new AlarmTime( c.get(Calendar.HOUR_OF_DAY), c.get(Calendar.MINUTE), c.get(Calendar.SECOND)); clock.setText(time.localizedString(getApplicationContext())); } @Override protected Dialog onCreateDialog(int id) { switch (Dialogs.values()[id]) { case TIME_PICKER: Dialog picker = new TimePickerDialog( this, getString(R.string.add_alarm), AppSettings.isDebugMode(this), new TimePickerDialog.OnTimeSetListener() { @Override public void onTimeSet(int hourOfDay, int minute, int second) { // When a time is selected, create it via the service and // force the list view to re-query the alarm list. service.createAlarm(new AlarmTime(hourOfDay, minute, second)); adapter.requery(); // Destroy this dialog so that it does not save its state. removeDialog(Dialogs.TIME_PICKER.ordinal()); } }); picker.setOnCancelListener(new OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { removeDialog(Dialogs.TIME_PICKER.ordinal()); } }); return picker; case DELETE_CONFIRM: final AlertDialog.Builder deleteConfirmBuilder = new AlertDialog.Builder(this); deleteConfirmBuilder.setTitle(R.string.delete_all); deleteConfirmBuilder.setMessage(R.string.confirm_delete); deleteConfirmBuilder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { service.deleteAllAlarms(); adapter.requery(); dismissDialog(Dialogs.DELETE_CONFIRM.ordinal()); } }); deleteConfirmBuilder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dismissDialog(Dialogs.DELETE_CONFIRM.ordinal()); } }); return deleteConfirmBuilder.create(); default: return super.onCreateDialog(id); } } }
Java
/**************************************************************************** * Copyright 2010 kraigs.android@gmail.com * 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.angrydoughnuts.android.alarmclock; import android.app.Activity; import android.content.Context; import android.media.MediaPlayer; import android.net.Uri; import android.provider.MediaStore.Audio.AlbumColumns; import android.provider.MediaStore.Audio.Media; import android.util.AttributeSet; import android.view.View; import android.widget.AdapterView; import android.widget.ViewFlipper; public class MediaAlbumsView extends MediaListView { private final String[] albumsColumns = new String[] { AlbumColumns.ALBUM, AlbumColumns.ALBUM_KEY }; private final int[] albumsResIDs = new int[] { R.id.media_value, R.id.media_key }; private MediaSongsView songsView; public MediaAlbumsView(Context context) { this(context, null); } public MediaAlbumsView(Context context, AttributeSet attrs) { this(context, attrs, 0); } public MediaAlbumsView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); overrideSortOrder(AlbumColumns.ALBUM + " ASC"); songsView = new MediaSongsView(context); songsView.overrideSortOrder(null); } @Override public void setCursorManager(Activity activity) { super.setCursorManager(activity); songsView.setCursorManager(activity); } @Override public void addToFlipper(ViewFlipper flipper) { super.addToFlipper(flipper); songsView.addToFlipper(flipper); } public void setMediaPlayer(MediaPlayer mPlayer) { songsView.setMediaPlayer(mPlayer); } public void query(Uri contentUri) { query(contentUri, null); } public void query(Uri contentUri, String selection) { super.query(contentUri, AlbumColumns.ALBUM_KEY, selection, R.layout.media_picker_row, albumsColumns, albumsResIDs); } @Override public void setMediaPickListener(OnItemPickListener listener) { songsView.setMediaPickListener(listener); } @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { super.onItemClick(parent, view, position, id); songsView.query(Media.EXTERNAL_CONTENT_URI, AlbumColumns.ALBUM_KEY + " = '" + getLastSelectedName() + "'"); getFlipper().setInAnimation(getContext(), R.anim.slide_in_left); getFlipper().setOutAnimation(getContext(), R.anim.slide_out_left); getFlipper().showNext(); } }
Java
/**************************************************************************** * Copyright 2010 kraigs.android@gmail.com * 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.angrydoughnuts.android.alarmclock; import java.util.LinkedList; import com.angrydoughnuts.android.alarmclock.WakeLock.WakeLockException; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.app.Service; import android.content.Context; import android.content.Intent; import android.media.AudioManager; import android.media.MediaPlayer; import android.media.Ringtone; import android.media.RingtoneManager; import android.net.Uri; import android.os.Handler; import android.os.IBinder; import android.os.Vibrator; /** * This service is responsible for notifying the user when an alarm is * triggered. The pending intent delivered by the alarm manager service * will trigger the alarm receiver. This receiver will in turn start * this service, passing the appropriate alarm url as data in the intent. * This service is capable of receiving multiple alarm notifications * without acknowledgments and will queue them until they are sequentially * acknowledged. The service is capable of playing a sound, triggering * the vibrator and displaying the notification activity (used to acknowledge * alarms). */ public class NotificationService extends Service { public class NoAlarmsException extends Exception { private static final long serialVersionUID = 1L; } // Since the media player objects are expensive to create and destroy, // share them across invocations of this service (there should never be // more than one instance of this class in a given application). private enum MediaSingleton { INSTANCE; private MediaPlayer mediaPlayer = null; private Ringtone fallbackSound = null; private Vibrator vibrator = null; private int systemNotificationVolume = 0; MediaSingleton() { mediaPlayer = new MediaPlayer(); mediaPlayer.setAudioStreamType(AudioManager.STREAM_ALARM); } // Force the alarm stream to be maximum volume. This will allow the user // to select a volume between 0 and 100 percent via the settings activity. private void normalizeVolume(Context c, float startVolume) { final AudioManager audio = (AudioManager) c.getSystemService(Context.AUDIO_SERVICE); systemNotificationVolume = audio.getStreamVolume(AudioManager.STREAM_ALARM); audio.setStreamVolume(AudioManager.STREAM_ALARM, audio.getStreamMaxVolume(AudioManager.STREAM_ALARM), 0); setVolume(startVolume); } private void setVolume(float volume) { mediaPlayer.setVolume(volume, volume); } private void resetVolume(Context c) { final AudioManager audio = (AudioManager) c.getSystemService(Context.AUDIO_SERVICE); audio.setStreamVolume( AudioManager.STREAM_ALARM, systemNotificationVolume, 0); } private void useContext(Context c) { // The media player can fail for lots of reasons. Try to setup a backup // sound for use when the media player fails. fallbackSound = RingtoneManager.getRingtone(c, AlarmUtil.getDefaultAlarmUri()); if (fallbackSound == null) { Uri superFallback = RingtoneManager.getValidRingtoneUri(c); fallbackSound = RingtoneManager.getRingtone(c, superFallback); } // Make the fallback sound use the alarm stream as well. if (fallbackSound != null) { fallbackSound.setStreamType(AudioManager.STREAM_ALARM); } // Instantiate a vibrator. That's fun to say. vibrator = (Vibrator) c.getSystemService(Context.VIBRATOR_SERVICE); } private void ensureSound() { if (!mediaPlayer.isPlaying() && fallbackSound != null && !fallbackSound.isPlaying()) { fallbackSound.play(); } } private void vibrate() { if (vibrator != null) { vibrator.vibrate(new long[] {500, 500}, 0); } } public void play(Context c, Uri tone) { mediaPlayer.reset(); mediaPlayer.setLooping(true); try { mediaPlayer.setDataSource(c, tone); mediaPlayer.prepare(); mediaPlayer.start(); } catch (Exception e) { e.printStackTrace(); } } public void stop() { mediaPlayer.stop(); if (vibrator != null) { vibrator.cancel(); } if (fallbackSound != null) { fallbackSound.stop(); } } } // Data private LinkedList<Long> firingAlarms; private AlarmClockServiceBinder service; private DbAccessor db; // Notification tools private NotificationManager manager; private Notification notification; private PendingIntent notificationActivity; private Handler handler; private VolumeIncreaser volumeIncreaseCallback; private Runnable soundCheck; private Runnable notificationBlinker; private Runnable autoCancel; @Override public IBinder onBind(Intent intent) { return new NotificationServiceInterfaceStub(this); } @Override public void onCreate() { super.onCreate(); firingAlarms = new LinkedList<Long>(); // Access to in-memory and persistent data structures. service = new AlarmClockServiceBinder(getApplicationContext()); service.bind(); db = new DbAccessor(getApplicationContext()); // Setup audio. MediaSingleton.INSTANCE.useContext(getApplicationContext()); // Setup notification bar. manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); // Use the notification activity explicitly in this intent just in case the // activity can't be viewed via the root activity. Intent intent = new Intent(getApplicationContext(), ActivityAlarmNotification.class); notificationActivity = PendingIntent.getActivity(getApplicationContext(), 0, intent, 0); notification = new Notification(R.drawable.alarmclock_notification, null, 0); notification.flags |= Notification.FLAG_ONGOING_EVENT; // Setup a self-scheduling event loops. handler = new Handler(); volumeIncreaseCallback = new VolumeIncreaser(); soundCheck = new Runnable() { @Override public void run() { // Some sound should always be playing. MediaSingleton.INSTANCE.ensureSound(); long next = AlarmUtil.millisTillNextInterval(AlarmUtil.Interval.SECOND); handler.postDelayed(soundCheck, next); } }; notificationBlinker = new Runnable() { @Override public void run() { String notifyText; try { AlarmInfo info = db.readAlarmInfo(currentAlarmId()); notifyText = info.getName(); if (notifyText.equals("")) { notifyText = info.getTime().localizedString(getApplicationContext()); } } catch (NoAlarmsException e) { return; } notification.setLatestEventInfo(getApplicationContext(), notifyText, "", notificationActivity); if (notification.icon == R.drawable.alarmclock_notification) { notification.icon = R.drawable.alarmclock_notification2; } else { notification.icon = R.drawable.alarmclock_notification; } manager.notify(AlarmClockService.NOTIFICATION_BAR_ID, notification); long next = AlarmUtil.millisTillNextInterval(AlarmUtil.Interval.SECOND); handler.postDelayed(notificationBlinker, next); } }; autoCancel = new Runnable() { @Override public void run() { try { acknowledgeCurrentNotification(0); } catch (NoAlarmsException e) { return; } Intent notifyActivity = new Intent(getApplicationContext(), ActivityAlarmNotification.class); notifyActivity.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); notifyActivity.putExtra(ActivityAlarmNotification.TIMEOUT_COMMAND, true); startActivity(notifyActivity); } }; } @Override public void onDestroy() { super.onDestroy(); db.closeConnections(); service.unbind(); boolean debug = AppSettings.isDebugMode(getApplicationContext()); if (debug && firingAlarms.size() != 0) { throw new IllegalStateException("Notification service terminated with pending notifications."); } try { WakeLock.assertNoneHeld(); } catch (WakeLockException e) { if (debug) { throw new IllegalStateException(e.getMessage()); } } } // OnStart was depreciated in SDK 5. It is here for backwards compatibility. // http://android-developers.blogspot.com/2010/02/service-api-changes-starting-with.html @Override public void onStart(Intent intent, int startId) { handleStart(intent, startId); } @Override public int onStartCommand(Intent intent, int flags, int startId) { handleStart(intent, startId); return START_NOT_STICKY; } private void handleStart(Intent intent, int startId) { // startService called from alarm receiver with an alarm id url. if (intent != null && intent.getData() != null) { long alarmId = AlarmUtil.alarmUriToId(intent.getData()); try { WakeLock.assertHeld(alarmId); } catch (WakeLockException e) { if (AppSettings.isDebugMode(getApplicationContext())) { throw new IllegalStateException(e.getMessage()); } } Intent notifyActivity = new Intent(getApplicationContext(), ActivityAlarmNotification.class); notifyActivity.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(notifyActivity); boolean firstAlarm = firingAlarms.size() == 0; if (!firingAlarms.contains(alarmId)) { firingAlarms.add(alarmId); } if (firstAlarm) { soundAlarm(alarmId); } } } public long currentAlarmId() throws NoAlarmsException { if (firingAlarms.size() == 0) { throw new NoAlarmsException(); } return firingAlarms.getFirst(); } public int firingAlarmCount() { return firingAlarms.size(); } public float volume() { return volumeIncreaseCallback.volume(); } public void acknowledgeCurrentNotification(int snoozeMinutes) throws NoAlarmsException { long alarmId = currentAlarmId(); if (firingAlarms.contains(alarmId)) { firingAlarms.remove(alarmId); if (snoozeMinutes <= 0) { service.acknowledgeAlarm(alarmId); } else { service.snoozeAlarmFor(alarmId, snoozeMinutes); } } stopNotifying(); // If this was the only alarm firing, stop the service. Otherwise, // start the next alarm in the stack. if (firingAlarms.size() == 0) { stopSelf(); } else { soundAlarm(alarmId); } try { WakeLock.release(alarmId); } catch (WakeLockException e) { if (AppSettings.isDebugMode(getApplicationContext())) { throw new IllegalStateException(e.getMessage()); } } } private void soundAlarm(long alarmId) { // Begin notifying based on settings for this alaram. AlarmSettings settings = db.readAlarmSettings(alarmId); if (settings.getVibrate()) { MediaSingleton.INSTANCE.vibrate(); } volumeIncreaseCallback.reset(settings); MediaSingleton.INSTANCE.normalizeVolume( getApplicationContext(), volumeIncreaseCallback.volume()); MediaSingleton.INSTANCE.play(getApplicationContext(), settings.getTone()); // Start periodic events for handling this notification. handler.post(volumeIncreaseCallback); handler.post(soundCheck); handler.post(notificationBlinker); // Set up a canceler if this notification isn't acknowledged by the timeout. int timeoutMillis = 60 * 1000 * AppSettings.alarmTimeOutMins(getApplicationContext()); handler.postDelayed(autoCancel, timeoutMillis); } private void stopNotifying() { // Stop periodic events. handler.removeCallbacks(volumeIncreaseCallback); handler.removeCallbacks(soundCheck); handler.removeCallbacks(notificationBlinker); handler.removeCallbacks(autoCancel); // Stop notifying. MediaSingleton.INSTANCE.stop(); MediaSingleton.INSTANCE.resetVolume(getApplicationContext()); } /** * Helper class for gradually increasing the volume of the alarm audio * stream. */ private final class VolumeIncreaser implements Runnable { float start; float end; float increment; public float volume() { return start; } public void reset(AlarmSettings settings) { start = (float) (settings.getVolumeStartPercent() / 100.0); end = (float) (settings.getVolumeEndPercent() / 100.0); increment = (end - start) / (float) settings.getVolumeChangeTimeSec(); } @Override public void run() { start += increment; if (start > end) { start = end; } MediaSingleton.INSTANCE.setVolume(start); if (Math.abs(start - end) > (float) 0.0001) { handler.postDelayed(volumeIncreaseCallback, 1000); } } } }
Java
/**************************************************************************** * Copyright 2010 kraigs.android@gmail.com * 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.angrydoughnuts.android.alarmclock; import android.app.AlertDialog; import android.app.Dialog; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.os.Bundle; import android.preference.Preference; import android.preference.PreferenceActivity; import android.preference.PreferenceManager; import android.preference.Preference.OnPreferenceChangeListener; import android.provider.Settings; import android.view.View; import android.widget.CheckBox; import android.widget.EditText; /** * Simple preferences activity to display/manage the shared preferences * that make up the global application settings. */ public class ActivityAppSettings extends PreferenceActivity { private enum Dialogs { CUSTOM_LOCK_SCREEN } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.app_settings); OnPreferenceChangeListener refreshListener = new OnPreferenceChangeListener() { @Override public boolean onPreferenceChange(Preference preference, Object newValue) { // Clear the lock screen text if the user disables the feature. if (preference.getKey().equals(AppSettings.LOCK_SCREEN)) { Settings.System.putString(getContentResolver(), Settings.System.NEXT_ALARM_FORMATTED, ""); final String custom_lock_screen = getResources().getStringArray(R.array.lock_screen_values)[4]; if (newValue.equals(custom_lock_screen)) { showDialog(Dialogs.CUSTOM_LOCK_SCREEN.ordinal()); } } final Intent causeRefresh = new Intent(getApplicationContext(), AlarmClockService.class); causeRefresh.putExtra(AlarmClockService.COMMAND_EXTRA, AlarmClockService.COMMAND_NOTIFICATION_REFRESH); startService(causeRefresh); return true; } }; // Refresh the notification icon when the user changes these preferences. final Preference notification_icon = findPreference(AppSettings.NOTIFICATION_ICON); notification_icon.setOnPreferenceChangeListener(refreshListener); final Preference lock_screen = findPreference(AppSettings.LOCK_SCREEN); lock_screen.setOnPreferenceChangeListener(refreshListener); } @Override protected Dialog onCreateDialog(int id) { switch (Dialogs.values()[id]) { case CUSTOM_LOCK_SCREEN: final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); final View lockTextView = getLayoutInflater().inflate(R.layout.custom_lock_screen_dialog, null); final EditText editText = (EditText) lockTextView.findViewById(R.id.custom_lock_screen_text); editText.setText(prefs.getString(AppSettings.CUSTOM_LOCK_SCREEN_TEXT, "")); final CheckBox persistentCheck = (CheckBox) lockTextView.findViewById(R.id.custom_lock_screen_persistent); persistentCheck.setChecked(prefs.getBoolean(AppSettings.CUSTOM_LOCK_SCREEN_PERSISTENT, false)); final AlertDialog.Builder lockTextBuilder = new AlertDialog.Builder(this); lockTextBuilder.setTitle(R.string.custom_lock_screen_text); lockTextBuilder.setView(lockTextView); lockTextBuilder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Editor editor = prefs.edit(); editor.putString(AppSettings.CUSTOM_LOCK_SCREEN_TEXT, editText.getText().toString()); editor.putBoolean(AppSettings.CUSTOM_LOCK_SCREEN_PERSISTENT, persistentCheck.isChecked()); editor.commit(); final Intent causeRefresh = new Intent(getApplicationContext(), AlarmClockService.class); causeRefresh.putExtra(AlarmClockService.COMMAND_EXTRA, AlarmClockService.COMMAND_NOTIFICATION_REFRESH); startService(causeRefresh); dismissDialog(Dialogs.CUSTOM_LOCK_SCREEN.ordinal()); } }); lockTextBuilder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dismissDialog(Dialogs.CUSTOM_LOCK_SCREEN.ordinal()); } }); return lockTextBuilder.create(); default: return super.onCreateDialog(id); } } }
Java
/**************************************************************************** * Copyright 2010 kraigs.android@gmail.com * 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.angrydoughnuts.android.alarmclock; import android.app.Activity; import android.app.Service; import android.content.ComponentName; import android.content.Intent; import android.content.ServiceConnection; import android.os.Bundle; import android.os.IBinder; import android.os.RemoteException; import android.widget.ArrayAdapter; import android.widget.ListView; /** * This is a simple activity which displays all of the scheduled (in memory) * alarms that currently exist (For debugging only). */ public final class ActivityPendingAlarms extends Activity { boolean connected; private ListView listView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.pending_alarms); connected = false; listView = (ListView) findViewById(R.id.pending_alarm_list); } @Override protected void onResume() { super.onResume(); final Intent i = new Intent(getApplicationContext(), AlarmClockService.class); if (!bindService(i, connection, Service.BIND_AUTO_CREATE)) { throw new IllegalStateException("Unable to bind to AlarmClockService."); } } @Override protected void onPause() { super.onPause(); if (connected) { unbindService(connection); } } private final ServiceConnection connection = new ServiceConnection() { @Override public void onServiceConnected(ComponentName name, IBinder service) { connected = true; AlarmClockInterface clock = AlarmClockInterface.Stub.asInterface(service); try { ArrayAdapter<AlarmTime> adapter = new ArrayAdapter<AlarmTime>( getApplicationContext(), R.layout.pending_alarms_item, clock.pendingAlarmTimes()); listView.setAdapter(adapter); } catch (RemoteException e) { e.printStackTrace(); } } @Override public void onServiceDisconnected(ComponentName name) { connected = false; } }; }
Java
/**************************************************************************** * Copyright 2010 kraigs.android@gmail.com * 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.angrydoughnuts.android.alarmclock; import com.angrydoughnuts.android.alarmclock.NotificationService.NoAlarmsException; import android.content.Context; import android.os.RemoteException; import android.widget.Toast; public class NotificationServiceInterfaceStub extends NotificationServiceInterface.Stub { private NotificationService service; public NotificationServiceInterfaceStub(NotificationService service) { this.service = service; } @Override public long currentAlarmId() throws RemoteException { try { return service.currentAlarmId(); } catch (NoAlarmsException e) { throw new RemoteException(); } } public int firingAlarmCount() throws RemoteException { return service.firingAlarmCount(); } @Override public float volume() throws RemoteException { return service.volume(); } @Override public void acknowledgeCurrentNotification(int snoozeMinutes) throws RemoteException { debugToast("STOP NOTIFICATION"); try { service.acknowledgeCurrentNotification(snoozeMinutes); } catch (NoAlarmsException e) { throw new RemoteException(); } } private void debugToast(String message) { Context context = service.getApplicationContext(); if (AppSettings.isDebugMode(context)) { Toast.makeText(context, message, Toast.LENGTH_SHORT).show(); } } }
Java
/**************************************************************************** * Copyright 2010 kraigs.android@gmail.com * 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.angrydoughnuts.android.alarmclock; import java.util.ArrayList; import java.util.Arrays; import android.content.Context; import android.database.MatrixCursor; import android.database.MatrixCursor.RowBuilder; import android.media.MediaPlayer; import android.net.Uri; import android.provider.BaseColumns; import android.provider.MediaStore.MediaColumns; import android.util.AttributeSet; import android.view.View; import android.widget.AdapterView.OnItemClickListener; import android.widget.AdapterView; public class MediaSongsView extends MediaListView implements OnItemClickListener { private final String[] songsColumns = new String[] { MediaColumns.TITLE, }; final int[] songsResIDs = new int[] { R.id.media_value, }; public MediaSongsView(Context context) { this(context, null); } public MediaSongsView(Context context, AttributeSet attrs) { this(context, attrs, 0); } public MediaSongsView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); overrideSortOrder(MediaColumns.TITLE + " ASC"); } public void query(Uri contentUri) { query(contentUri, null); } public void query(Uri contentUri, String selection) { super.query(contentUri, MediaColumns.TITLE, selection, R.layout.media_picker_row, songsColumns, songsResIDs); } @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { super.onItemClick(parent, view, position, id); MediaPlayer mPlayer = getMediaPlayer(); if (mPlayer == null) { return; } mPlayer.reset(); try { mPlayer.setDataSource(getContext(), getLastSelectedUri()); mPlayer.prepare(); mPlayer.start(); } catch (Exception e) { e.printStackTrace(); } } public void includeDefault() { final ArrayList<String> defaultColumns = new ArrayList<String>(songsColumns.length + 1); defaultColumns.addAll(Arrays.asList(songsColumns)); defaultColumns.add(BaseColumns._ID); final MatrixCursor defaultsCursor = new MatrixCursor(defaultColumns.toArray(new String[] {})); RowBuilder row = defaultsCursor.newRow(); row.add("Default"); row.add(DEFAULT_TONE_INDEX); includeStaticCursor(defaultsCursor); } }
Java
/**************************************************************************** * Copyright 2010 kraigs.android@gmail.com * 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.angrydoughnuts.android.alarmclock; import android.content.Context; import android.util.AttributeSet; import android.view.Gravity; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.view.animation.AlphaAnimation; import android.view.animation.Animation; import android.view.animation.DecelerateInterpolator; import android.view.animation.TranslateAnimation; import android.view.animation.Animation.AnimationListener; import android.widget.ImageView; import android.widget.TextView; import android.widget.ImageView.ScaleType; /** * Widget that contains a slider bar used for acknowledgments. The user * must slide an arrow sufficiently far enough across the bar in order * to trigger the acknowledgment. */ public class Slider extends ViewGroup { public interface OnCompleteListener { void complete(); } private static final int FADE_MILLIS = 200; private static final int SLIDE_MILLIS = 200; private static final float SLIDE_ACCEL = (float) 1.0; private static final double PERCENT_REQUIRED = 0.72; private ImageView dot; private TextView tray; private boolean tracking; private OnCompleteListener completeListener; public Slider(Context context) { this(context, null, 0); } public Slider(Context context, AttributeSet attrs) { this(context, attrs, 0); } public Slider(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); // Setup the background which 'holds' the slider. tray = new TextView(getContext()); tray.setBackgroundResource(R.drawable.slider_background); tray.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT)); tray.setGravity(Gravity.CENTER); tray.setTextAppearance(getContext(), R.style.SliderText); tray.setText(R.string.dismiss); addView(tray); // Setup the object which will be slid. dot = new ImageView(getContext()); dot.setImageResource(R.drawable.slider_icon); dot.setBackgroundResource(R.drawable.slider_btn); dot.setScaleType(ScaleType.CENTER); dot.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); dot.setPadding(30, 10, 25, 15); addView(dot); reset(); } public void setOnCompleteListener(OnCompleteListener listener) { completeListener = listener; } public void reset() { tracking = false; // Move the dot home and fade in. if (getVisibility() != View.VISIBLE) { dot.offsetLeftAndRight(getLeft() - dot.getLeft()); setVisibility(View.VISIBLE); Animation fadeIn = new AlphaAnimation(0, 1); fadeIn.setDuration(FADE_MILLIS); startAnimation(fadeIn); } } @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { if (!changed) { return; } // Start the dot left-aligned. dot.layout(0, 7, dot.getMeasuredWidth(), dot.getMeasuredHeight()); // Make the tray fill the background. tray.layout(0, 0, getMeasuredWidth(), getMeasuredHeight()); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { tray.measure(widthMeasureSpec, heightMeasureSpec); dot.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED), heightMeasureSpec); setMeasuredDimension( Math.max(tray.getMeasuredWidth(), dot.getMeasuredWidth()), Math.max(tray.getMeasuredHeight(), dot.getMeasuredHeight())); } private boolean withinX(View v, float x) { if (x < v.getLeft() || x > v.getRight()) { return false; } else { return true; } } private boolean withinY(View v, float y) { if (y < v.getTop() || y > v.getBottom()) { return false; } else { return true; } } private void slideDotHome() { int distanceFromStart = dot.getLeft() - getLeft(); dot.offsetLeftAndRight(-distanceFromStart); Animation slideBack = new TranslateAnimation(distanceFromStart, 0, 0, 0); slideBack.setDuration(SLIDE_MILLIS); slideBack.setInterpolator(new DecelerateInterpolator(SLIDE_ACCEL)); dot.startAnimation(slideBack); } private boolean isComplete() { double dotCenterY = dot.getLeft() + dot.getMeasuredWidth()/2.0; float progressPercent = (float)(dotCenterY - getLeft()) / (float)(getRight() - getLeft()); if (progressPercent > PERCENT_REQUIRED) { return true; } else { return false; } } private void finishSlider() { setVisibility(View.INVISIBLE); Animation fadeOut = new AlphaAnimation(1, 0); fadeOut.setDuration(FADE_MILLIS); fadeOut.setAnimationListener(new AnimationListener() { @Override public void onAnimationEnd(Animation animation) { if (completeListener != null) { completeListener.complete(); } } @Override public void onAnimationRepeat(Animation animation) {} @Override public void onAnimationStart(Animation animation) {} }); startAnimation(fadeOut); } @Override public boolean onTouchEvent(MotionEvent event) { final int action = event.getAction(); final float x = event.getX(); final float y = event.getY(); switch (action) { case MotionEvent.ACTION_DOWN: // Start tracking if the down event is in the dot. tracking = withinX(dot, x) && withinY(dot, y); return tracking || super.onTouchEvent(event); case MotionEvent.ACTION_CANCEL: case MotionEvent.ACTION_UP: // Ignore move events which did not originate in the dot. if (!tracking) { return super.onTouchEvent(event); } // The dot has been released, check to see if we've hit the threshold, // otherwise, send the dot home. tracking = false; if (isComplete()) { finishSlider(); } else { slideDotHome(); } return true; case MotionEvent.ACTION_MOVE: // Ignore move events which did not originate in the dot. if (!tracking) { return super.onTouchEvent(event); } // Update the current location. dot.offsetLeftAndRight((int) (x - dot.getLeft() - dot.getWidth()/2.0 )); // See if we have reached the threshold. if (isComplete()) { tracking = false; finishSlider(); return true; } // Otherwise, we have not yet hit the completion threshold. Make sure // the move is still within bounds of the dot and redraw. if (!withinY(dot, y)) { // Slid out of the slider, reset to the beginning. tracking = false; slideDotHome(); } else { invalidate(); } return true; default: return super.onTouchEvent(event); } } }
Java
/**************************************************************************** * Copyright 2010 kraigs.android@gmail.com * 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.angrydoughnuts.android.alarmclock; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.TreeMap; import android.app.AlarmManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; /** * This container holds a list of all currently scheduled alarms. * Adding/removing alarms to this container schedules/unschedules PendingIntents * with the android AlarmManager service. */ public final class PendingAlarmList { // Maps alarmId -> alarm. private TreeMap<Long, PendingAlarm> pendingAlarms; // Maps alarm time -> alarmId. private TreeMap<AlarmTime, Long> alarmTimes; private AlarmManager alarmManager; private Context context; public PendingAlarmList(Context context) { pendingAlarms = new TreeMap<Long, PendingAlarm>(); alarmTimes = new TreeMap<AlarmTime, Long>(); alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); this.context = context; } public int size() { if (pendingAlarms.size() != alarmTimes.size()) { throw new IllegalStateException("Inconsistent pending alarms: " + pendingAlarms.size() + " vs " + alarmTimes.size()); } return pendingAlarms.size(); } public void put(long alarmId, AlarmTime time) { // Remove this alarm if it exists already. remove(alarmId); // Intents are considered equal if they have the same action, data, type, // class, and categories. In order to schedule multiple alarms, every // pending intent must be different. This means that we must encode // the alarm id in the data section of the intent rather than in // the extras bundle. Intent notifyIntent = new Intent(context, ReceiverAlarm.class); notifyIntent.setData(AlarmUtil.alarmIdToUri(alarmId)); PendingIntent scheduleIntent = PendingIntent.getBroadcast(context, 0, notifyIntent, 0); // Schedule the alarm with the AlarmManager. // Previous instances of this intent will be overwritten in // the alarm manager. try { // In API version 19 (KitKat), the set() method of is no longer // guaranteed to have exact timing semantics. A setExact() // method is supplied, but is not available with the minimum SDK // version used by this application. Here we look for this // new method and use it if we find it. Otherwise, we fall back // to the old set() method. Method setExact = AlarmManager.class.getDeclaredMethod( "setExact", int.class, long.class, PendingIntent.class); setExact.invoke(alarmManager, AlarmManager.RTC_WAKEUP, time.calendar().getTimeInMillis(), scheduleIntent); } catch (NoSuchMethodException e) { alarmManager.set(AlarmManager.RTC_WAKEUP, time.calendar().getTimeInMillis(), scheduleIntent); } catch (IllegalAccessException e) { // TODO(cgallek) combine these all with the java 7 OR syntax. throw new RuntimeException(e); } catch (IllegalArgumentException e) { throw new RuntimeException(e); } catch (InvocationTargetException e) { throw new RuntimeException(e); } // Keep track of all scheduled alarms. pendingAlarms.put(alarmId, new PendingAlarm(time, scheduleIntent)); alarmTimes.put(time, alarmId); if (pendingAlarms.size() != alarmTimes.size()) { throw new IllegalStateException("Inconsistent pending alarms: " + pendingAlarms.size() + " vs " + alarmTimes.size()); } } public boolean remove(long alarmId) { PendingAlarm alarm = pendingAlarms.remove(alarmId); if (alarm == null) { return false; } Long expectedAlarmId = alarmTimes.remove(alarm.time()); alarmManager.cancel(alarm.pendingIntent()); alarm.pendingIntent().cancel(); if (expectedAlarmId != alarmId) { throw new IllegalStateException("Internal inconsistency in PendingAlarmList"); } if (pendingAlarms.size() != alarmTimes.size()) { throw new IllegalStateException("Inconsistent pending alarms: " + pendingAlarms.size() + " vs " + alarmTimes.size()); } return true; } public AlarmTime nextAlarmTime() { if (alarmTimes.size() == 0) { return null; } return alarmTimes.firstKey(); } public AlarmTime pendingTime(long alarmId) { PendingAlarm alarm = pendingAlarms.get(alarmId); return alarm == null ? null : alarm.time(); } public AlarmTime[] pendingTimes() { AlarmTime[] times = new AlarmTime[alarmTimes.size()]; alarmTimes.keySet().toArray(times); return times; } public Long[] pendingAlarms() { Long[] alarmIds = new Long[pendingAlarms.size()]; pendingAlarms.keySet().toArray(alarmIds); return alarmIds; } private class PendingAlarm { private AlarmTime time; private PendingIntent pendingIntent; PendingAlarm(AlarmTime time, PendingIntent pendingIntent) { this.time = time; this.pendingIntent = pendingIntent; } public AlarmTime time() { return time; } public PendingIntent pendingIntent() { return pendingIntent; } } }
Java
package com.angrydoughnuts.android.alarmclock; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; public class RecevierTimeZoneChange extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { Intent i = new Intent(context, AlarmClockService.class); i.putExtra(AlarmClockService.COMMAND_EXTRA, AlarmClockService.COMMAND_TIMEZONE_CHANGE); context.startService(i); } }
Java
/**************************************************************************** * Copyright 2010 kraigs.android@gmail.com * 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.angrydoughnuts.android.alarmclock; import java.lang.reflect.Field; import android.net.Uri; import android.provider.Settings; public final class AlarmUtil { static public Uri alarmIdToUri(long alarmId) { return Uri.parse("alarm_id:" + alarmId); } public static long alarmUriToId(Uri uri) { return Long.parseLong(uri.getSchemeSpecificPart()); } enum Interval { SECOND(1000), MINUTE(60 * 1000), HOUR(60 * 60 * 1000); private long millis; public long millis() { return millis; } Interval(long millis) { this.millis = millis; } } public static long millisTillNextInterval(Interval interval) { long now = System.currentTimeMillis(); return interval.millis() - now % interval.millis(); } public static long nextIntervalInUTC(Interval interval) { long now = System.currentTimeMillis(); return now + interval.millis() - now % interval.millis(); } public static Uri getDefaultAlarmUri() { // DEFAULT_ALARM_ALERT_URI is only available after SDK version 5. // Fall back to the default notification if the default alarm is // unavailable. try { Field f = Settings.System.class.getField("DEFAULT_ALARM_ALERT_URI"); return (Uri) f.get(null); } catch (Exception e) { return Settings.System.DEFAULT_NOTIFICATION_URI; } } }
Java
/**************************************************************************** * Copyright 2010 kraigs.android@gmail.com * 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.angrydoughnuts.android.alarmclock; import java.util.LinkedList; import android.app.Activity; import android.content.Context; import android.database.Cursor; import android.os.RemoteException; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.View.OnClickListener; import android.widget.ArrayAdapter; import android.widget.CheckBox; import android.widget.TextView; /** * This adapter is used to query the alarm database and translate each alarm * into a view which is displayed in a ListView. */ public final class AlarmViewAdapter extends ArrayAdapter<AlarmInfo> { private AlarmClockServiceBinder service; private LayoutInflater inflater; private Cursor cursor; public AlarmViewAdapter(Activity activity, DbAccessor db, AlarmClockServiceBinder service) { super(activity, 0, new LinkedList<AlarmInfo>()); this.service = service; this.inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE); this.cursor = db.readAlarmInfo(); activity.startManagingCursor(cursor); loadData(); } private void loadData() { while (cursor.moveToNext()) { add(new AlarmInfo(cursor)); } } public void requery() { clear(); cursor.requery(); loadData(); notifyDataSetChanged(); } @Override public View getView(int position, View convertView, ViewGroup parent) { View view = inflater.inflate(R.layout.alarm_list_item, null); TextView timeView = (TextView) view.findViewById(R.id.alarm_time); TextView nextView = (TextView) view.findViewById(R.id.next_alarm); TextView labelView = (TextView) view.findViewById(R.id.alarm_label); TextView repeatView = (TextView) view.findViewById(R.id.alarm_repeat); CheckBox enabledView = (CheckBox) view.findViewById(R.id.alarm_enabled); final AlarmInfo info = getItem(position); AlarmTime time = null; // See if there is an instance of this alarm scheduled. if (service.clock() != null) { try { time = service.clock().pendingAlarm(info.getAlarmId()); } catch (RemoteException e) {} } // If we couldn't find a pending alarm, display the configured time. if (time == null) { time = info.getTime(); } String timeStr = time.localizedString(getContext()); String alarmId = ""; if (AppSettings.isDebugMode(getContext())) { alarmId = " [" + info.getAlarmId() + "]"; } timeView.setText(timeStr + alarmId); enabledView.setChecked(info.enabled()); nextView.setText(time.timeUntilString(getContext())); labelView.setText(info.getName()); if (!info.getTime().getDaysOfWeek().equals(Week.NO_REPEATS)) { repeatView.setText(info.getTime().getDaysOfWeek().toString(getContext())); } enabledView.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { CheckBox check = (CheckBox) v; if (check.isChecked()) { service.scheduleAlarm(info.getAlarmId()); requery(); } else { service.unscheduleAlarm(info.getAlarmId()); requery(); } } }); return view; } }
Java
/**************************************************************************** * Copyright 2010 kraigs.android@gmail.com * 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.angrydoughnuts.android.alarmclock; import android.content.Context; import android.content.SharedPreferences; import android.content.pm.ApplicationInfo; import android.preference.PreferenceManager; /** * Utility class for accessing each of the global application settings. */ public final class AppSettings { // Some of these have an extra " in them because of an old copy/paste bug. // They are forever ingrained in the settings :-( public static final String DEBUG_MODE = "DEBUG_MODE"; public static final String NOTIFICATION_ICON = "NOTIFICATION_ICON"; public static final String LOCK_SCREEN = "LOCK_SCREEN"; public static final String CUSTOM_LOCK_SCREEN_TEXT = "CUSTOM_LOCK_SCREEN"; public static final String CUSTOM_LOCK_SCREEN_PERSISTENT = "CUSTOM_LOCK_PERSISTENT"; public static final String ALARM_TIMEOUT = "ALARM_TIMEOUT"; public static final boolean displayNotificationIcon(Context c) { final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(c); return prefs.getBoolean(NOTIFICATION_ICON, true); } private static final String FORMAT_COUNTDOWN = "%c"; private static final String FORMAT_TIME = "%t"; private static final String FORMAT_BOTH = "%c (%t)"; public static final String lockScreenString(Context c, AlarmTime nextTime) { final String[] values = c.getResources().getStringArray(R.array.lock_screen_values); final String LOCK_SCREEN_COUNTDOWN = values[0]; final String LOCK_SCREEN_TIME = values[1]; final String LOCK_SCREEN_BOTH = values[2]; final String LOCK_SCREEN_NOTHING = values[3]; final String LOCK_SCREEN_CUSTOM = values[4]; final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(c); final String value = prefs.getString(LOCK_SCREEN, LOCK_SCREEN_COUNTDOWN); final String customFormat = prefs.getString(CUSTOM_LOCK_SCREEN_TEXT, FORMAT_COUNTDOWN); // The lock screen message should be persistent iff the persistent setting // is set AND a custom lock screen message is set. final boolean persistent = prefs.getBoolean(CUSTOM_LOCK_SCREEN_PERSISTENT, false) && value.equals(LOCK_SCREEN_CUSTOM); if (value.equals(LOCK_SCREEN_NOTHING)) { return null; } // If no alarm is set and our lock message is not persistent, return // a clearing string. if (nextTime == null && !persistent) { return ""; } String time = ""; String countdown = ""; if (nextTime != null) { time = nextTime.localizedString(c); countdown = nextTime.timeUntilString(c); } String text; if (value.equals(LOCK_SCREEN_COUNTDOWN)) { text = FORMAT_COUNTDOWN; } else if (value.equals(LOCK_SCREEN_TIME)) { text = FORMAT_TIME; } else if (value.equals(LOCK_SCREEN_BOTH)) { text = FORMAT_BOTH; } else if (value.equals(LOCK_SCREEN_CUSTOM)) { text = customFormat; } else { throw new IllegalStateException("Unknown lockscreen preference: " + value); } text = text.replace("%t", time); text = text.replace("%c", countdown); return text; } public static final boolean isDebugMode(Context c) { final String[] values = c.getResources().getStringArray(R.array.debug_values); final String DEBUG_DEFAULT = values[0]; final String DEBUG_ON = values[1]; final String DEBUG_OFF = values[2]; final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(c); final String value = prefs.getString(DEBUG_MODE, DEBUG_DEFAULT); if (value.equals(DEBUG_ON)) { return true; } else if (value.equals(DEBUG_OFF)) { return false; } else if (value.equals(DEBUG_DEFAULT)) { return (c.getApplicationInfo().flags & ApplicationInfo.FLAG_DEBUGGABLE) > 0; } else { throw new IllegalStateException("Unknown debug mode setting: "+ value); } } public static final int alarmTimeOutMins(Context c) { final String[] values = c.getResources().getStringArray(R.array.time_out_values); final String ONE_MIN = values[0]; final String FIVE_MIN = values[1]; final String TEN_MIN = values[2]; final String THIRTY_MIN = values[3]; final String SIXTY_MIN = values[4]; final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(c); final String value = prefs.getString(ALARM_TIMEOUT, TEN_MIN); if (value.equals(ONE_MIN)) { return 1; } else if (value.equals(FIVE_MIN)) { return 5; } else if (value.equals(TEN_MIN)) { return 10; } else if (value.equals(THIRTY_MIN)) { return 30; } else if (value.equals(SIXTY_MIN)) { return 60; } else { return 10; } } }
Java
/**************************************************************************** * Copyright 2010 kraigs.android@gmail.com * 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.angrydoughnuts.android.alarmclock; import java.util.Map; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.app.Service; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.content.pm.PackageManager; import android.os.Bundle; import android.os.Handler; import android.os.IBinder; import android.preference.PreferenceManager; import android.provider.Settings; import android.widget.Toast; public final class AlarmClockService extends Service { public final static String COMMAND_EXTRA = "command"; public final static int COMMAND_UNKNOWN = 1; public final static int COMMAND_NOTIFICATION_REFRESH = 2; public final static int COMMAND_DEVICE_BOOT = 3; public final static int COMMAND_TIMEZONE_CHANGE = 4; public final static int NOTIFICATION_BAR_ID = 69; private DbAccessor db; private PendingAlarmList pendingAlarms; private Notification notification; @Override public void onCreate() { super.onCreate(); // Registers an exception handler of capable of writing the stack trace // to the device's SD card. This is only possible if the proper // permissions are available. if (getPackageManager().checkPermission( "android.permission.WRITE_EXTERNAL_STORAGE", getPackageName()) == PackageManager.PERMISSION_GRANTED) { Thread.setDefaultUncaughtExceptionHandler( new LoggingUncaughtExceptionHandler("/sdcard")); } // Access to in-memory and persistent data structures. db = new DbAccessor(getApplicationContext()); pendingAlarms = new PendingAlarmList(getApplicationContext()); // Schedule enabled alarms during initial startup. for (Long alarmId : db.getEnabledAlarms()) { if (pendingAlarms.pendingTime(alarmId) != null) { continue; } if (AppSettings.isDebugMode(getApplicationContext())) { Toast.makeText(getApplicationContext(), "RENABLE " + alarmId, Toast.LENGTH_SHORT).show(); } pendingAlarms.put(alarmId, db.readAlarmInfo(alarmId).getTime()); } notification = new Notification(R.drawable.alarmclock_notification, null, 0); notification.flags |= Notification.FLAG_ONGOING_EVENT; ReceiverNotificationRefresh.startRefreshing(getApplicationContext()); } // OnStart was depreciated in SDK 5. It is here for backwards compatibility. // http://android-developers.blogspot.com/2010/02/service-api-changes-starting-with.html @Override public void onStart(Intent intent, int startId) { handleStart(intent, startId); } @Override public int onStartCommand(Intent intent, int flags, int startId) { handleStart(intent, startId); return START_STICKY; } private void handleStart(Intent intent, int startId) { if (intent != null && intent.hasExtra(COMMAND_EXTRA)) { Bundle extras = intent.getExtras(); int command = extras.getInt(COMMAND_EXTRA, COMMAND_UNKNOWN); final Handler handler = new Handler(); final Runnable maybeShutdown = new Runnable() { @Override public void run() { if (pendingAlarms.size() == 0) { stopSelf(); } } }; switch (command) { case COMMAND_NOTIFICATION_REFRESH: refreshNotification(); handler.post(maybeShutdown); break; case COMMAND_DEVICE_BOOT: fixPersistentSettings(); handler.post(maybeShutdown); break; case COMMAND_TIMEZONE_CHANGE: if (AppSettings.isDebugMode(getApplicationContext())) { Toast.makeText(getApplicationContext(), "TIMEZONE CHANGE, RESCHEDULING...", Toast.LENGTH_SHORT).show(); } for (long alarmId : pendingAlarms.pendingAlarms()) { scheduleAlarm(alarmId); if (AppSettings.isDebugMode(getApplicationContext())) { Toast.makeText(getApplicationContext(), "ALARM " + alarmId, Toast.LENGTH_SHORT).show(); } } handler.post(maybeShutdown); break; default: throw new IllegalArgumentException("Unknown service command."); } } } private void refreshNotification() { AlarmTime nextTime = pendingAlarms.nextAlarmTime(); String nextString; if (nextTime != null) { nextString = getString(R.string.next_alarm) + " " + nextTime.localizedString(getApplicationContext()) + " (" + nextTime.timeUntilString(getApplicationContext()) + ")"; } else { nextString = getString(R.string.no_pending_alarms); } // Make the notification launch the UI Activity when clicked. final Intent notificationIntent = new Intent(this, ActivityAlarmClock.class); final PendingIntent launch = PendingIntent.getActivity(this, 0, notificationIntent, 0); Context c = getApplicationContext(); notification.setLatestEventInfo(c, getString(R.string.app_name), nextString, launch); final NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); if (pendingAlarms.size() > 0 && AppSettings.displayNotificationIcon(c)) { manager.notify(NOTIFICATION_BAR_ID, notification); } else { manager.cancel(NOTIFICATION_BAR_ID); } // Set the system alarm string for display on the lock screen. String lockScreenText = AppSettings.lockScreenString(getApplicationContext(), nextTime); if (lockScreenText != null) { Settings.System.putString(getContentResolver(), Settings.System.NEXT_ALARM_FORMATTED, lockScreenText); } } // This hack is necessary b/c I released a version of the code with a bunch // of errors in the settings strings. This should correct them. public void fixPersistentSettings() { final String badDebugName = "DEBUG_MODE\""; final String badNotificationName = "NOTFICATION_ICON"; final String badLockScreenName = "LOCK_SCREEN\""; final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); Map<String, ?> prefNames = prefs.getAll(); // Don't do anything if the bad preferences have already been fixed. if (!prefNames.containsKey(badDebugName) && !prefNames.containsKey(badNotificationName) && !prefNames.containsKey(badLockScreenName)) { return; } Editor editor = prefs.edit(); if (prefNames.containsKey(badDebugName)) { editor.putString(AppSettings.DEBUG_MODE, prefs.getString(badDebugName, null)); editor.remove(badDebugName); } if (prefNames.containsKey(badNotificationName)){ editor.putBoolean(AppSettings.NOTIFICATION_ICON, prefs.getBoolean(badNotificationName, true)); editor.remove(badNotificationName); } if (prefNames.containsKey(badLockScreenName)) { editor.putString(AppSettings.LOCK_SCREEN, prefs.getString(badLockScreenName, null)); editor.remove(badLockScreenName); } editor.commit(); } @Override public void onDestroy() { super.onDestroy(); db.closeConnections(); ReceiverNotificationRefresh.stopRefreshing(getApplicationContext()); final NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); manager.cancel(NOTIFICATION_BAR_ID); String lockScreenText = AppSettings.lockScreenString(getApplicationContext(), null); // Only clear the lock screen if the preference is set. if (lockScreenText != null) { Settings.System.putString(getContentResolver(), Settings.System.NEXT_ALARM_FORMATTED, lockScreenText); } } @Override public IBinder onBind(Intent intent) { return new AlarmClockInterfaceStub(getApplicationContext(), this); } @Override public boolean onUnbind(Intent intent) { // Decide if we need to explicitly shut down this service. Normally, // the service would shutdown after the last un-bind, but it was explicitly // started in onBind(). If there are no pending alarms, explicitly stop // the service. if (pendingAlarms.size() == 0) { stopSelf(); return false; } // Returning true causes the IBinder object to be re-used until the // service is actually shutdown. return true; } public AlarmTime pendingAlarm(long alarmId) { return pendingAlarms.pendingTime(alarmId); } public AlarmTime[] pendingAlarmTimes() { return pendingAlarms.pendingTimes(); } public void createAlarm(AlarmTime time) { // Store the alarm in the persistent database. long alarmId = db.newAlarm(time); scheduleAlarm(alarmId); } public void deleteAlarm(long alarmId) { pendingAlarms.remove(alarmId); db.deleteAlarm(alarmId); } public void deleteAllAlarms() { for (Long alarmId : db.getAllAlarms()) { deleteAlarm(alarmId); } } public void scheduleAlarm(long alarmId) { AlarmInfo info = db.readAlarmInfo(alarmId); if (info == null) { return; } // Schedule the next alarm. pendingAlarms.put(alarmId, info.getTime()); // Mark the alarm as enabled in the database. db.enableAlarm(alarmId, true); // Now that there is more than one pending alarm, explicitly start the // service so that it continues to run after binding. final Intent self = new Intent(getApplicationContext(), AlarmClockService.class); startService(self); refreshNotification(); } public void acknowledgeAlarm(long alarmId) { AlarmInfo info = db.readAlarmInfo(alarmId); if (info == null) { return; } pendingAlarms.remove(alarmId); AlarmTime time = info.getTime(); if (time.repeats()) { pendingAlarms.put(alarmId, time); } else { db.enableAlarm(alarmId, false); } refreshNotification(); } public void dismissAlarm(long alarmId) { AlarmInfo info = db.readAlarmInfo(alarmId); if (info == null) { return; } pendingAlarms.remove(alarmId); db.enableAlarm(alarmId, false); refreshNotification(); } public void snoozeAlarm(long alarmId) { snoozeAlarmFor(alarmId, db.readAlarmSettings(alarmId).getSnoozeMinutes()); } public void snoozeAlarmFor(long alarmId, int minutes) { // Clear the snoozed alarm. pendingAlarms.remove(alarmId); // Calculate the time for the next alarm. AlarmTime time = AlarmTime.snoozeInMillisUTC(minutes); // Schedule it. pendingAlarms.put(alarmId, time); refreshNotification(); } }
Java
package com.angrydoughnuts.android.alarmclock; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; public class ReceiverDeviceBoot extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { // There doesn't seem to be any way to filter on the scheme-specific // portion of the ACTION_PACKANGE_REPLACED intent (the package // being replaced is in the ssp). Since we can't filter for it in the // Manifest file, we get every package replaced event and cancel this // event if it's not our package. if (intent.getAction().equals(Intent.ACTION_PACKAGE_REPLACED)) { if (!intent.getData().getSchemeSpecificPart().equals(context.getPackageName())) { return; } } Intent i = new Intent(context, AlarmClockService.class); i.putExtra(AlarmClockService.COMMAND_EXTRA, AlarmClockService.COMMAND_DEVICE_BOOT); context.startService(i); } }
Java
package com.angrydoughnuts.android.alarmclock; import android.app.AlarmManager; import android.app.PendingIntent; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; public class ReceiverNotificationRefresh extends BroadcastReceiver { public static void startRefreshing(Context context) { context.sendBroadcast(intent(context)); } public static void stopRefreshing(Context context) { final AlarmManager manager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); manager.cancel(pendingIntent(context)); } private static Intent intent(Context context) { return new Intent(context, ReceiverNotificationRefresh.class); } private static PendingIntent pendingIntent(Context context) { return PendingIntent.getBroadcast(context, 0, intent(context), 0); } @Override public void onReceive(Context context, Intent intent) { final Intent causeRefresh = new Intent(context, AlarmClockService.class); causeRefresh.putExtra(AlarmClockService.COMMAND_EXTRA, AlarmClockService.COMMAND_NOTIFICATION_REFRESH); context.startService(causeRefresh); long next = AlarmUtil.nextIntervalInUTC(AlarmUtil.Interval.MINUTE); final AlarmManager manager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); manager.set(AlarmManager.RTC, next, pendingIntent(context)); } }
Java
package com.angrydoughnuts.android.alarmclock; import java.util.TreeMap; import android.content.Context; import android.os.PowerManager; public class WakeLock { public static class WakeLockException extends Exception { private static final long serialVersionUID = 1L; public WakeLockException(String e) { super(e); } } private static final TreeMap<Long, PowerManager.WakeLock> wakeLocks = new TreeMap<Long, PowerManager.WakeLock>(); public static final void acquire(Context context, long alarmId) throws WakeLockException { if (wakeLocks.containsKey(alarmId)) { throw new WakeLockException("Multiple acquisitions of wake lock for id: " + alarmId); } PowerManager powerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE); PowerManager.WakeLock wakeLock = powerManager.newWakeLock( PowerManager.SCREEN_DIM_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP, "Alarm Notification Wake Lock id " + alarmId); wakeLock.setReferenceCounted(false); wakeLock.acquire(); wakeLocks.put(alarmId, wakeLock); } public static final void assertHeld(long alarmId) throws WakeLockException { PowerManager.WakeLock wakeLock = wakeLocks.get(alarmId); if (wakeLock == null || !wakeLock.isHeld()) { throw new WakeLockException("Wake lock not held for alarm id: " + alarmId); } } public static final void assertAtLeastOneHeld() throws WakeLockException { for (PowerManager.WakeLock wakeLock : wakeLocks.values()) { if (wakeLock.isHeld()) { return; } } throw new WakeLockException("No wake locks are held."); } public static final void assertNoneHeld() throws WakeLockException { for (PowerManager.WakeLock wakeLock : wakeLocks.values()) { if (wakeLock.isHeld()) { throw new WakeLockException("No wake locks are held."); } } } public static final void release(long alarmId) throws WakeLockException { assertHeld(alarmId); PowerManager.WakeLock wakeLock = wakeLocks.remove(alarmId); wakeLock.release(); } }
Java
/**************************************************************************** * Copyright 2010 kraigs.android@gmail.com * 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.angrydoughnuts.android.alarmclock; import android.content.Context; import android.os.RemoteException; import android.widget.Toast; public final class AlarmClockInterfaceStub extends AlarmClockInterface.Stub { private Context context; private AlarmClockService service; AlarmClockInterfaceStub(Context context, AlarmClockService service) { this.context = context; this.service = service; } @Override public AlarmTime pendingAlarm(long alarmId) throws RemoteException { return service.pendingAlarm(alarmId); } @Override public AlarmTime[] pendingAlarmTimes() throws RemoteException { return service.pendingAlarmTimes(); } @Override public void createAlarm(AlarmTime time) throws RemoteException { debugToast("CREATE ALARM " + time.toString()); service.createAlarm(time); } @Override public void deleteAlarm(long alarmId) throws RemoteException { debugToast("DELETE ALARM " + alarmId); service.deleteAlarm(alarmId); } @Override public void deleteAllAlarms() throws RemoteException { debugToast("DELETE ALL ALARMS"); service.deleteAllAlarms(); } @Override public void scheduleAlarm(long alarmId) throws RemoteException { debugToast("SCHEDULE ALARM " + alarmId); service.scheduleAlarm(alarmId); } @Override public void unscheduleAlarm(long alarmId) { debugToast("UNSCHEDULE ALARM " + alarmId); service.dismissAlarm(alarmId); } public void acknowledgeAlarm(long alarmId) { debugToast("ACKNOWLEDGE ALARM " + alarmId); service.acknowledgeAlarm(alarmId); } @Override public void snoozeAlarm(long alarmId) throws RemoteException { debugToast("SNOOZE ALARM " + alarmId); service.snoozeAlarm(alarmId); } @Override public void snoozeAlarmFor(long alarmId, int minutes) throws RemoteException { debugToast("SNOOZE ALARM " + alarmId + " for " + minutes); service.snoozeAlarmFor(alarmId, minutes); } private void debugToast(String message) { if (AppSettings.isDebugMode(context)) { Toast.makeText(context, message, Toast.LENGTH_SHORT).show(); } } }
Java
/**************************************************************************** * Copyright 2010 kraigs.android@gmail.com * 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.angrydoughnuts.android.alarmclock; import com.angrydoughnuts.android.alarmclock.MediaListView.OnItemPickListener; import android.app.Activity; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.media.MediaPlayer; import android.net.Uri; import android.os.Message; import android.provider.MediaStore.Audio.Albums; import android.provider.MediaStore.Audio.Artists; import android.provider.MediaStore.Audio.Media; import android.view.LayoutInflater; import android.view.View; import android.widget.TabHost; import android.widget.TextView; import android.widget.ViewFlipper; import android.widget.TabHost.OnTabChangeListener; /** * A dialog which displays all of the audio media available on the phone. * It allows you to access media through 4 tabs: One that lists media * stored internally on the phone, and three that allow you to access * the media stored on the SD card. These three tabs allow you to browse by * artist, album, and song. */ public class MediaPickerDialog extends AlertDialog { public interface OnMediaPickListener { public void onMediaPick(String name, Uri media); } private final String INTERNAL_TAB = "internal"; private final String ARTISTS_TAB = "artists"; private final String ALBUMS_TAB = "albums"; private final String ALL_SONGS_TAB = "songs"; private String selectedName; private Uri selectedUri; private OnMediaPickListener pickListener; private MediaPlayer mediaPlayer; public MediaPickerDialog(final Activity context) { super(context); mediaPlayer = new MediaPlayer(); final LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); final View body_view = inflater.inflate(R.layout.media_picker_dialog, null); setView(body_view); TabHost tabs = (TabHost) body_view.findViewById(R.id.media_tabs); tabs.setup(); tabs.addTab(tabs.newTabSpec(INTERNAL_TAB).setContent(R.id.media_picker_internal).setIndicator(context.getString(R.string.internal))); tabs.addTab(tabs.newTabSpec(ARTISTS_TAB).setContent(R.id.media_picker_artists).setIndicator(context.getString(R.string.artists))); tabs.addTab(tabs.newTabSpec(ALBUMS_TAB).setContent(R.id.media_picker_albums).setIndicator(context.getString(R.string.albums))); tabs.addTab(tabs.newTabSpec(ALL_SONGS_TAB).setContent(R.id.media_picker_songs).setIndicator(context.getString(R.string.songs))); final TextView lastSelected = (TextView) body_view.findViewById(R.id.media_picker_status); final OnItemPickListener listener = new OnItemPickListener() { @Override public void onItemPick(Uri uri, String name) { selectedUri = uri; selectedName = name; lastSelected.setText(name); } }; final MediaSongsView internalList = (MediaSongsView) body_view.findViewById(R.id.media_picker_internal); internalList.setCursorManager(context); internalList.includeDefault(); internalList.query(Media.INTERNAL_CONTENT_URI); internalList.setMediaPlayer(mediaPlayer); internalList.setMediaPickListener(listener); final MediaSongsView songsList = (MediaSongsView) body_view.findViewById(R.id.media_picker_songs); songsList.setCursorManager(context); songsList.query(Media.EXTERNAL_CONTENT_URI); songsList.setMediaPlayer(mediaPlayer); songsList.setMediaPickListener(listener); final ViewFlipper artistsFlipper = (ViewFlipper) body_view.findViewById(R.id.media_picker_artists); final MediaArtistsView artistsList = new MediaArtistsView(context); artistsList.setCursorManager(context); artistsList.addToFlipper(artistsFlipper); artistsList.query(Artists.EXTERNAL_CONTENT_URI); artistsList.setMediaPlayer(mediaPlayer); artistsList.setMediaPickListener(listener); final ViewFlipper albumsFlipper = (ViewFlipper) body_view.findViewById(R.id.media_picker_albums); final MediaAlbumsView albumsList = new MediaAlbumsView(context); albumsList.setCursorManager(context); albumsList.addToFlipper(albumsFlipper); albumsList.query(Albums.EXTERNAL_CONTENT_URI); albumsList.setMediaPlayer(mediaPlayer); albumsList.setMediaPickListener(listener); tabs.setOnTabChangedListener(new OnTabChangeListener() { @Override public void onTabChanged(String tabId) { if (tabId.equals(ARTISTS_TAB)) { artistsFlipper.setDisplayedChild(0); } else if (tabId.equals(ALBUMS_TAB)) { albumsFlipper.setDisplayedChild(0); } } }); super.setButton(BUTTON_POSITIVE, getContext().getString(R.string.ok), new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { if (selectedUri == null || pickListener == null) { cancel(); return; } pickListener.onMediaPick(selectedName, selectedUri); } }); super.setButton(BUTTON_NEGATIVE, getContext().getString(R.string.cancel), new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { selectedName = null; selectedUri = null; lastSelected.setText(""); cancel(); } }); } public void setPickListener(OnMediaPickListener listener) { this.pickListener = listener; } @Override protected void onStop() { super.onStop(); mediaPlayer.stop(); } @Override protected void finalize() throws Throwable { mediaPlayer.release(); super.finalize(); } // Make these no-ops and final so the buttons can't be overridden buy the // user nor a child. @Override public void setButton(CharSequence text, Message msg) { } @Override public final void setButton(CharSequence text, OnClickListener listener) {} @Override public final void setButton(int whichButton, CharSequence text, Message msg) {} @Override public final void setButton(int whichButton, CharSequence text, OnClickListener listener) {} @Override public final void setButton2(CharSequence text, Message msg) {} @Override public final void setButton2(CharSequence text, OnClickListener listener) {} @Override public final void setButton3(CharSequence text, Message msg) {} @Override public final void setButton3(CharSequence text, OnClickListener listener) {} }
Java
/**************************************************************************** * Copyright 2010 kraigs.android@gmail.com * 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.angrydoughnuts.android.alarmclock; import java.util.ArrayList; import java.util.Calendar; import java.util.List; import com.angrydoughnuts.android.alarmclock.MediaPickerDialog.OnMediaPickListener; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.content.Context; import android.content.DialogInterface; import android.content.DialogInterface.OnMultiChoiceClickListener; import android.net.Uri; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.View.OnClickListener; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.ListView; import android.widget.TextView; import android.widget.AdapterView.OnItemClickListener; /** * This activity is used for editing alarm settings. Settings are broken * into two pieces: alarm information and actual settings. Every alarm will * have alarm information. Alarms will only have alarm settings if the user * has overridden the default settings for a given alarm. This dialog is used * to edit both the application default settings and individual alarm settings. * When editing the application default settings, no AlarmInfo object will * be present. When editing an alarm which hasn't yet had specific settings * set, AlarmSettings will contain the default settings. There is one required * EXTRA that must be supplied when starting this activity: EXTRAS_ALARM_ID, * which should contain a long representing the alarmId of the settings * being edited. AlarmSettings.DEFAULT_SETTINGS_ID can be used to edit the * default settings. */ public final class ActivityAlarmSettings extends Activity { public static final String EXTRAS_ALARM_ID = "alarm_id"; private final int MISSING_EXTRAS = -69; private enum SettingType { TIME, NAME, DAYS_OF_WEEK, TONE, SNOOZE, VIBRATE, VOLUME_FADE; } private enum Dialogs { TIME_PICKER, NAME_PICKER, DOW_PICKER, TONE_PICKER, SNOOZE_PICKER, VOLUME_FADE_PICKER, DELETE_CONFIRM } private long alarmId; private AlarmClockServiceBinder service; private DbAccessor db; private AlarmInfo originalInfo; private AlarmInfo info; private AlarmSettings originalSettings; private AlarmSettings settings; SettingsAdapter settingsAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.settings); // An alarm id is required in the extras bundle. alarmId = getIntent().getExtras().getLong(EXTRAS_ALARM_ID, MISSING_EXTRAS); if (alarmId == MISSING_EXTRAS) { throw new IllegalStateException("EXTRAS_ALARM_ID not supplied in intent."); } // Access to in-memory and persistent data structures. service = new AlarmClockServiceBinder(getApplicationContext()); db = new DbAccessor(getApplicationContext()); // Read the current settings from the database. Keep a copy of the // original values so that we can write new values only if they differ // from the originals. originalInfo = db.readAlarmInfo(alarmId); // Info will not be available for the default settings. if (originalInfo != null) { info = new AlarmInfo(originalInfo); } originalSettings = db.readAlarmSettings(alarmId); settings = new AlarmSettings(originalSettings); // Setup individual UI elements. // Positive acknowledgment button. final Button okButton = (Button) findViewById(R.id.settings_ok); okButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // Write AlarmInfo if it changed. if (originalInfo != null && !originalInfo.equals(info)) { db.writeAlarmInfo(alarmId, info); // Explicitly enable the alarm if the user changed the time. // This will reschedule the alarm if it was already enabled. // It's also probably the right thing to do if the alarm wasn't // enabled. if (!originalInfo.getTime().equals(info.getTime())) { service.scheduleAlarm(alarmId); } } // Write AlarmSettings if they have changed. if (!originalSettings.equals(settings)) { db.writeAlarmSettings(alarmId, settings); } finish(); } }); // Negative acknowledgment button. final Button cancelButton = (Button) findViewById(R.id.settings_cancel); cancelButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { finish(); } }); // Delete button. Simply opens a confirmation dialog (which does the // actual delete). Button deleteButton = (Button) findViewById(R.id.settings_delete); deleteButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { showDialog(Dialogs.DELETE_CONFIRM.ordinal()); } }); // Setup the list of settings. Each setting is represented by a Setting // object. Create one here for each setting type. final ArrayList<Setting> settingsObjects = new ArrayList<Setting>(SettingType.values().length); // Only display AlarmInfo if the user is editing an actual alarm (as // opposed to the default application settings). if (alarmId != AlarmSettings.DEFAULT_SETTINGS_ID) { // The alarm time. settingsObjects.add(new Setting() { @Override public String name() { return getString(R.string.time); } @Override public String value() { return info.getTime().localizedString(getApplicationContext()); } @Override public SettingType type() { return SettingType.TIME; } }); // A human-readable label for the alarm. settingsObjects.add(new Setting() { @Override public String name() { return getString(R.string.label); } @Override public String value() { return info.getName().equals("") ? getString(R.string.none) : info.getName(); } @Override public SettingType type() { return SettingType.NAME; } }); // Days of the week this alarm should repeat. settingsObjects.add(new Setting() { @Override public String name() { return getString(R.string.repeat); } @Override public String value() { return info.getTime().getDaysOfWeek().toString(getApplicationContext()); } @Override public SettingType type() { return SettingType.DAYS_OF_WEEK; } }); } // The notification tone used for this alarm. settingsObjects.add(new Setting() { @Override public String name() { return getString(R.string.tone); } @Override public String value() { String value = settings.getToneName(); if (AppSettings.isDebugMode(getApplicationContext())) { value += " " + settings.getTone().toString(); } return value; } @Override public SettingType type() { return SettingType.TONE; } }); // The snooze duration for this alarm. settingsObjects.add(new Setting() { @Override public String name() { return getString(R.string.snooze_minutes); } @Override public String value() { return "" + settings.getSnoozeMinutes(); } @Override public SettingType type() { return SettingType.SNOOZE; } }); // The vibrator setting for this alarm. settingsObjects.add(new Setting() { @Override public String name() { return getString(R.string.vibrate); } @Override public String value() { return settings.getVibrate() ? getString(R.string.enabled) : getString(R.string.disabled); } @Override public SettingType type() { return SettingType.VIBRATE; } }); // How the volume should be controlled while this alarm is triggering. settingsObjects.add(new Setting() { @Override public String name() { return getString(R.string.alarm_fade); } @Override public String value() { return getString(R.string.fade_description, settings.getVolumeStartPercent(), settings.getVolumeEndPercent(), settings.getVolumeChangeTimeSec()); } @Override public SettingType type() { return SettingType.VOLUME_FADE; } }); final ListView settingsList = (ListView) findViewById(R.id.settings_list); settingsAdapter = new SettingsAdapter(getApplicationContext(), settingsObjects); settingsList.setAdapter(settingsAdapter); settingsList.setOnItemClickListener(new SettingsListClickListener()); // The delete button should not be shown when editing the default settings. if (alarmId == AlarmSettings.DEFAULT_SETTINGS_ID) { deleteButton.setVisibility(View.GONE); } } @Override protected void onResume() { super.onResume(); service.bind(); } @Override protected void onPause() { super.onPause(); service.unbind(); } @Override protected void onDestroy() { super.onDestroy(); db.closeConnections(); } @Override protected Dialog onCreateDialog(int id) { switch (Dialogs.values()[id]) { case TIME_PICKER: final AlarmTime time = info.getTime(); int hour = time.calendar().get(Calendar.HOUR_OF_DAY); int minute = time.calendar().get(Calendar.MINUTE); int second = time.calendar().get(Calendar.SECOND); return new TimePickerDialog(this, getString(R.string.time), hour, minute, second, AppSettings.isDebugMode(this), new TimePickerDialog.OnTimeSetListener() { @Override public void onTimeSet(int hourOfDay, int minute, int second) { info.setTime(new AlarmTime(hourOfDay, minute, second, time.getDaysOfWeek())); settingsAdapter.notifyDataSetChanged(); // Destroy this dialog so that it does not save its state. removeDialog(Dialogs.TIME_PICKER.ordinal()); } }); case NAME_PICKER: final View nameView = getLayoutInflater().inflate(R.layout.name_settings_dialog, null); final TextView label = (TextView) nameView.findViewById(R.id.name_label); label.setText(info.getName()); final AlertDialog.Builder nameBuilder = new AlertDialog.Builder(this); nameBuilder.setTitle(R.string.alarm_label); nameBuilder.setView(nameView); nameBuilder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { info.setName(label.getEditableText().toString()); settingsAdapter.notifyDataSetChanged(); dismissDialog(Dialogs.NAME_PICKER.ordinal()); } }); nameBuilder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dismissDialog(Dialogs.NAME_PICKER.ordinal()); } }); return nameBuilder.create(); case DOW_PICKER: final AlertDialog.Builder dowBuilder = new AlertDialog.Builder(this); dowBuilder.setTitle(R.string.scheduled_days); dowBuilder.setMultiChoiceItems( info.getTime().getDaysOfWeek().names(getApplicationContext()), info.getTime().getDaysOfWeek().bitmask(), new OnMultiChoiceClickListener() { @Override public void onClick(DialogInterface dialog, int which, boolean isChecked) { if (isChecked) { info.getTime().getDaysOfWeek().addDay(Week.Day.values()[which]); } else { info.getTime().getDaysOfWeek().removeDay(Week.Day.values()[which]); } } }); dowBuilder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { settingsAdapter.notifyDataSetChanged(); dismissDialog(Dialogs.DOW_PICKER.ordinal()); } }); return dowBuilder.create(); case TONE_PICKER: MediaPickerDialog mediaPicker = new MediaPickerDialog(this); mediaPicker.setPickListener(new OnMediaPickListener() { @Override public void onMediaPick(String name, Uri media) { if (name.length() == 0) { name = getString(R.string.unknown_name); } settings.setTone(media, name); settingsAdapter.notifyDataSetChanged(); } }); return mediaPicker; case SNOOZE_PICKER: // This currently imposes snooze times between 1 and 60 minutes, // which isn't really necessary, but I think the picker is easier // to use than a free-text field that you have to type numbers into. final CharSequence[] items = new CharSequence[60]; // Note the array index is one-off from the value (the value of 1 is // at index 0). for (int i = 1; i <= 60; ++i) { items[i-1] = new Integer(i).toString(); } final AlertDialog.Builder snoozeBuilder = new AlertDialog.Builder(this); snoozeBuilder.setTitle(R.string.snooze_minutes); snoozeBuilder.setSingleChoiceItems(items, settings.getSnoozeMinutes() - 1, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int item) { settings.setSnoozeMinutes(item + 1); settingsAdapter.notifyDataSetChanged(); dismissDialog(Dialogs.SNOOZE_PICKER.ordinal()); } }); return snoozeBuilder.create(); case VOLUME_FADE_PICKER: final View fadeView = getLayoutInflater().inflate(R.layout.fade_settings_dialog, null); final EditText volumeStart = (EditText) fadeView.findViewById(R.id.volume_start); volumeStart.setText("" + settings.getVolumeStartPercent()); final EditText volumeEnd = (EditText) fadeView.findViewById(R.id.volume_end); volumeEnd.setText("" + settings.getVolumeEndPercent()); final EditText volumeDuration = (EditText) fadeView.findViewById(R.id.volume_duration); volumeDuration.setText("" + settings.getVolumeChangeTimeSec()); final AlertDialog.Builder fadeBuilder = new AlertDialog.Builder(this); fadeBuilder.setTitle(R.string.alarm_fade); fadeBuilder.setView(fadeView); fadeBuilder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { settings.setVolumeStartPercent(tryParseInt(volumeStart.getText().toString(), 0)); settings.setVolumeEndPercent(tryParseInt(volumeEnd.getText().toString(), 100)); settings.setVolumeChangeTimeSec(tryParseInt(volumeDuration.getText().toString(), 20)); settingsAdapter.notifyDataSetChanged(); dismissDialog(Dialogs.VOLUME_FADE_PICKER.ordinal()); } }); fadeBuilder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dismissDialog(Dialogs.VOLUME_FADE_PICKER.ordinal()); } }); return fadeBuilder.create(); case DELETE_CONFIRM: final AlertDialog.Builder deleteConfirmBuilder = new AlertDialog.Builder(this); deleteConfirmBuilder.setTitle(R.string.delete); deleteConfirmBuilder.setMessage(R.string.confirm_delete); deleteConfirmBuilder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { service.deleteAlarm(alarmId); dismissDialog(Dialogs.DELETE_CONFIRM.ordinal()); finish(); } }); deleteConfirmBuilder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dismissDialog(Dialogs.DELETE_CONFIRM.ordinal()); } }); return deleteConfirmBuilder.create(); default: return super.onCreateDialog(id); } } /** * This is a helper class for mapping SettingType to action. Each Setting * in the list view returns a unique SettingType. Trigger a dialog * based off of that SettingType. */ private final class SettingsListClickListener implements OnItemClickListener { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { final SettingsAdapter adapter = (SettingsAdapter) parent.getAdapter(); SettingType type = adapter.getItem(position).type(); switch (type) { case TIME: showDialog(Dialogs.TIME_PICKER.ordinal()); break; case NAME: showDialog(Dialogs.NAME_PICKER.ordinal()); break; case DAYS_OF_WEEK: showDialog(Dialogs.DOW_PICKER.ordinal()); break; case TONE: showDialog(Dialogs.TONE_PICKER.ordinal()); break; case SNOOZE: showDialog(Dialogs.SNOOZE_PICKER.ordinal()); break; case VIBRATE: settings.setVibrate(!settings.getVibrate()); settingsAdapter.notifyDataSetChanged(); break; case VOLUME_FADE: showDialog(Dialogs.VOLUME_FADE_PICKER.ordinal()); break; } } } private int tryParseInt(String input, int fallback) { try { return Integer.parseInt(input); } catch (Exception e) { return fallback; } } /** * A helper interface to encapsulate the data displayed in the list view of * this activity. Consists of a setting name, a setting value, and a type. * The type is used to trigger the appropriate action from the onClick * handler. */ private abstract class Setting { public abstract String name(); public abstract String value(); public abstract SettingType type(); } /** * This adapter populates the settings_items view with the data encapsulated * in the individual Setting objects. */ private final class SettingsAdapter extends ArrayAdapter<Setting> { public SettingsAdapter(Context context, List<Setting> settingsObjects) { super(context, 0, settingsObjects); } @Override public View getView(int position, View convertView, ViewGroup parent) { LayoutInflater inflater = getLayoutInflater(); View row = inflater.inflate(R.layout.settings_item, null); TextView name = (TextView) row.findViewById(R.id.setting_name); TextView value = (TextView) row.findViewById(R.id.setting_value); Setting setting = getItem(position); name.setText(setting.name()); value.setText(setting.value()); return row; } } }
Java
/**************************************************************************** * Copyright 2010 kraigs.android@gmail.com * 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.angrydoughnuts.android.alarmclock; import java.util.LinkedList; import java.util.List; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; public final class DbAccessor { private DbHelper db; private SQLiteDatabase rDb; private SQLiteDatabase rwDb; public DbAccessor(Context context) { db = new DbHelper(context); rwDb = db.getWritableDatabase(); rDb = db.getReadableDatabase(); } public void closeConnections() { rDb.close(); rwDb.close(); } public long newAlarm(AlarmTime time) { AlarmInfo info = new AlarmInfo(time, false, ""); long id = rwDb.insert(DbHelper.DB_TABLE_ALARMS, null, info.contentValues()); if (id < 0) { throw new IllegalStateException("Unable to insert into database"); } return id; } public boolean deleteAlarm(long alarmId) { int count = rDb.delete(DbHelper.DB_TABLE_ALARMS, DbHelper.ALARMS_COL__ID + " = " + alarmId, null); // This may or may not exist. We don't care about the return value. rDb.delete(DbHelper.DB_TABLE_SETTINGS, DbHelper.SETTINGS_COL_ID + " = " + alarmId, null); return count > 0; } public boolean enableAlarm(long alarmId, boolean enabled) { ContentValues values = new ContentValues(1); values.put(DbHelper.ALARMS_COL_ENABLED, enabled); int count = rwDb.update(DbHelper.DB_TABLE_ALARMS, values, DbHelper.ALARMS_COL__ID + " = " + alarmId, null); return count != 0; } public List<Long> getEnabledAlarms() { LinkedList<Long> enabled = new LinkedList<Long>(); Cursor cursor = rDb.query(DbHelper.DB_TABLE_ALARMS, new String[] { DbHelper.ALARMS_COL__ID }, DbHelper.ALARMS_COL_ENABLED + " = 1", null, null, null, null); while (cursor.moveToNext()) { long alarmId = cursor.getLong(cursor.getColumnIndex(DbHelper.ALARMS_COL__ID)); enabled.add(alarmId); } cursor.close(); return enabled; } public List<Long> getAllAlarms() { LinkedList<Long> alarms = new LinkedList<Long>(); Cursor cursor = rDb.query(DbHelper.DB_TABLE_ALARMS, new String[] { DbHelper.ALARMS_COL__ID }, null, null, null, null, null); while (cursor.moveToNext()) { long alarmId = cursor.getLong(cursor.getColumnIndex(DbHelper.ALARMS_COL__ID)); alarms.add(alarmId); } cursor.close(); return alarms; } public boolean writeAlarmInfo(long alarmId, AlarmInfo info) { return rwDb.update(DbHelper.DB_TABLE_ALARMS, info.contentValues(), DbHelper.ALARMS_COL__ID + " = " + alarmId, null) == 1; } public Cursor readAlarmInfo() { Cursor cursor = rDb.query(DbHelper.DB_TABLE_ALARMS, AlarmInfo.contentColumns(), null, null, null, null, DbHelper.ALARMS_COL_TIME + " ASC"); return cursor; } public AlarmInfo readAlarmInfo(long alarmId) { Cursor cursor = rDb.query(DbHelper.DB_TABLE_ALARMS, AlarmInfo.contentColumns(), DbHelper.ALARMS_COL__ID + " = " + alarmId, null, null, null, null); if (cursor.getCount() != 1) { cursor.close(); return null; } cursor.moveToFirst(); AlarmInfo info = new AlarmInfo(cursor); cursor.close(); return info; } public boolean writeAlarmSettings(long alarmId, AlarmSettings settings) { Cursor cursor = rDb.query(DbHelper.DB_TABLE_SETTINGS, new String[] { DbHelper.SETTINGS_COL_ID }, DbHelper.SETTINGS_COL_ID + " = " + alarmId, null, null, null, null); boolean success = false; if (cursor.getCount() < 1) { success = rwDb.insert(DbHelper.DB_TABLE_SETTINGS, null, settings.contentValues(alarmId)) >= 0; } else { success = rwDb.update(DbHelper.DB_TABLE_SETTINGS, settings.contentValues(alarmId), DbHelper.SETTINGS_COL_ID + " = " + alarmId, null) == 1; } cursor.close(); return success; } public AlarmSettings readAlarmSettings(long alarmId) { Cursor cursor = rDb.query(DbHelper.DB_TABLE_SETTINGS, AlarmSettings.contentColumns(), DbHelper.SETTINGS_COL_ID + " = " + alarmId, null, null, null, null); if (cursor.getCount() != 1) { cursor.close(); if (alarmId == AlarmSettings.DEFAULT_SETTINGS_ID) { return new AlarmSettings(); } return readAlarmSettings(AlarmSettings.DEFAULT_SETTINGS_ID); } AlarmSettings settings = new AlarmSettings(cursor); cursor.close(); return settings; } }
Java
/**************************************************************************** * Copyright 2010 kraigs.android@gmail.com * 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.angrydoughnuts.android.alarmclock; import android.content.ContentValues; import android.database.Cursor; import android.net.Uri; /** * This class contains all of the settings data for a given alarm. It also * provides the mapping from this data to the respective columns in the * persistent settings database. */ public final class AlarmSettings { static public final long DEFAULT_SETTINGS_ID = -1; private Uri tone; private String toneName; private int snoozeMinutes; private boolean vibrate; private int volumeStartPercent; private int volumeEndPercent; private int volumeChangeTimeSec; public ContentValues contentValues(long alarmId) { ContentValues values = new ContentValues(); values.put(DbHelper.SETTINGS_COL_ID, alarmId); values.put(DbHelper.SETTINGS_COL_TONE_URL, tone.toString()); values.put(DbHelper.SETTINGS_COL_TONE_NAME, toneName); values.put(DbHelper.SETTINGS_COL_SNOOZE, snoozeMinutes); values.put(DbHelper.SETTINGS_COL_VIBRATE, vibrate); values.put(DbHelper.SETTINGS_COL_VOLUME_STARTING, volumeStartPercent); values.put(DbHelper.SETTINGS_COL_VOLUME_ENDING, volumeEndPercent); values.put(DbHelper.SETTINGS_COL_VOLUME_TIME, volumeChangeTimeSec); return values; } static public String[] contentColumns() { return new String[] { DbHelper.SETTINGS_COL_ID, DbHelper.SETTINGS_COL_TONE_URL, DbHelper.SETTINGS_COL_TONE_NAME, DbHelper.SETTINGS_COL_SNOOZE, DbHelper.SETTINGS_COL_VIBRATE, DbHelper.SETTINGS_COL_VOLUME_STARTING, DbHelper.SETTINGS_COL_VOLUME_ENDING, DbHelper.SETTINGS_COL_VOLUME_TIME }; } public AlarmSettings() { tone = AlarmUtil.getDefaultAlarmUri(); toneName = "Default"; snoozeMinutes = 10; vibrate = false; volumeStartPercent = 0; volumeEndPercent = 100; volumeChangeTimeSec = 20; } public AlarmSettings(AlarmSettings rhs) { tone = rhs.tone; toneName = rhs.toneName; snoozeMinutes = rhs.snoozeMinutes; vibrate = rhs.vibrate; volumeStartPercent = rhs.volumeStartPercent; volumeEndPercent = rhs.volumeEndPercent; volumeChangeTimeSec = rhs.volumeChangeTimeSec; } public AlarmSettings(Cursor cursor) { cursor.moveToFirst(); tone = Uri.parse(cursor.getString(cursor.getColumnIndex(DbHelper.SETTINGS_COL_TONE_URL))); toneName = cursor.getString(cursor.getColumnIndex(DbHelper.SETTINGS_COL_TONE_NAME)); snoozeMinutes = cursor.getInt(cursor.getColumnIndex(DbHelper.SETTINGS_COL_SNOOZE)); vibrate = cursor.getInt(cursor.getColumnIndex(DbHelper.SETTINGS_COL_VIBRATE)) == 1; volumeStartPercent = cursor.getInt(cursor.getColumnIndex(DbHelper.SETTINGS_COL_VOLUME_STARTING)); volumeEndPercent = cursor.getInt(cursor.getColumnIndex(DbHelper.SETTINGS_COL_VOLUME_ENDING)); volumeChangeTimeSec = cursor.getInt(cursor.getColumnIndex(DbHelper.SETTINGS_COL_VOLUME_TIME)); } @Override public boolean equals(Object o) { if (!(o instanceof AlarmSettings)) { return false; } AlarmSettings rhs = (AlarmSettings) o; return tone.equals(rhs.tone) && toneName.equals(rhs.toneName) && snoozeMinutes == rhs.snoozeMinutes && vibrate == rhs.vibrate && volumeStartPercent == rhs.volumeStartPercent && volumeEndPercent == rhs.volumeEndPercent && volumeChangeTimeSec == rhs.volumeChangeTimeSec; } public Uri getTone() { return tone; } public void setTone(Uri tone, String name) { this.tone = tone; this.toneName = name; } public String getToneName() { return toneName; } public int getSnoozeMinutes() { return snoozeMinutes; } public void setSnoozeMinutes(int minutes) { if (minutes < 1) { minutes = 1; } else if (minutes > 60) { minutes = 60; } this.snoozeMinutes = minutes; } public boolean getVibrate() { return vibrate; } public void setVibrate(boolean vibrate) { this.vibrate = vibrate; } public int getVolumeStartPercent() { return volumeStartPercent; } public void setVolumeStartPercent(int volumeStartPercent) { if (volumeStartPercent < 0) { volumeStartPercent = 0; } else if (volumeStartPercent > 100) { volumeStartPercent = 100; } this.volumeStartPercent = volumeStartPercent; } public int getVolumeEndPercent() { return volumeEndPercent; } public void setVolumeEndPercent(int volumeEndPercent) { if (volumeEndPercent < 0) { volumeEndPercent = 0; } else if (volumeEndPercent > 100) { volumeEndPercent = 100; } this.volumeEndPercent = volumeEndPercent; } public int getVolumeChangeTimeSec() { return volumeChangeTimeSec; } public void setVolumeChangeTimeSec(int volumeChangeTimeSec) { if (volumeChangeTimeSec < 1) { volumeChangeTimeSec = 1; } else if (volumeChangeTimeSec > 600) { volumeChangeTimeSec = 600; } this.volumeChangeTimeSec = volumeChangeTimeSec; } }
Java
/**************************************************************************** * Copyright 2010 kraigs.android@gmail.com * 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.angrydoughnuts.android.alarmclock; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.os.RemoteException; import android.view.View; import android.view.WindowManager; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.TextView; /** * This is the activity responsible for alerting the user when an alarm goes * off. It is the activity triggered by the NotificationService. It assumes * that the intent sender has acquired a screen wake lock. * NOTE: This class assumes that it will never be instantiated nor active * more than once at the same time. (ie, it assumes * android:launchMode="singleInstance" is set in the manifest file). */ public final class ActivityAlarmNotification extends Activity { public final static String TIMEOUT_COMMAND = "timeout"; private enum Dialogs { TIMEOUT } private NotificationServiceBinder notifyService; private DbAccessor db; private Handler handler; private Runnable timeTick; // Dialog state int snoozeMinutes; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.notification); // Make sure this window always shows over the lock screen. getWindow().addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED); db = new DbAccessor(getApplicationContext()); // Start the notification service and bind to it. notifyService = new NotificationServiceBinder(getApplicationContext()); notifyService.bind(); // Setup a self-scheduling event loops. handler = new Handler(); timeTick = new Runnable() { @Override public void run() { notifyService.call(new NotificationServiceBinder.ServiceCallback() { @Override public void run(NotificationServiceInterface service) { try { TextView volume = (TextView) findViewById(R.id.volume); volume.setText("Volume: " + service.volume()); } catch (RemoteException e) {} long next = AlarmUtil.millisTillNextInterval(AlarmUtil.Interval.SECOND); handler.postDelayed(timeTick, next); } }); } }; // Setup individual UI elements. final Button snoozeButton = (Button) findViewById(R.id.notify_snooze); snoozeButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { notifyService.acknowledgeCurrentNotification(snoozeMinutes); finish(); } }); final Button decreaseSnoozeButton = (Button) findViewById(R.id.notify_snooze_minus_five); decreaseSnoozeButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { int snooze = snoozeMinutes - 5; if (snooze < 5) { snooze = 5; } snoozeMinutes = snooze; redraw(); } }); final Button increaseSnoozeButton = (Button) findViewById(R.id.notify_snooze_plus_five); increaseSnoozeButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { int snooze = snoozeMinutes + 5; if (snooze > 60) { snooze = 60; } snoozeMinutes = snooze; redraw(); } }); final Slider dismiss = (Slider) findViewById(R.id.dismiss_slider); dismiss.setOnCompleteListener(new Slider.OnCompleteListener() { @Override public void complete() { notifyService.acknowledgeCurrentNotification(0); finish(); } }); } @Override protected void onResume() { super.onResume(); handler.post(timeTick); redraw(); } @Override protected void onPause() { super.onPause(); handler.removeCallbacks(timeTick); } @Override protected void onDestroy() { super.onDestroy(); db.closeConnections(); notifyService.unbind(); } @Override protected void onNewIntent(Intent intent) { super.onNewIntent(intent); Bundle extras = intent.getExtras(); if (extras == null || extras.getBoolean(TIMEOUT_COMMAND, false) == false) { return; } // The notification service has signaled this activity for a second time. // This represents a acknowledgment timeout. Display the appropriate error. // (which also finish()es this activity. showDialog(Dialogs.TIMEOUT.ordinal()); } @Override protected Dialog onCreateDialog(int id) { switch (Dialogs.values()[id]) { case TIMEOUT: final AlertDialog.Builder timeoutBuilder = new AlertDialog.Builder(this); timeoutBuilder.setIcon(android.R.drawable.ic_dialog_alert); timeoutBuilder.setTitle(R.string.time_out_title); timeoutBuilder.setMessage(R.string.time_out_error); timeoutBuilder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener(){ @Override public void onClick(DialogInterface dialog, int which) {} }); AlertDialog dialog = timeoutBuilder.create(); dialog.setOnDismissListener(new DialogInterface.OnDismissListener() { @Override public void onDismiss(DialogInterface dialog) { finish(); }}); return dialog; default: return super.onCreateDialog(id); } } private final void redraw() { notifyService.call(new NotificationServiceBinder.ServiceCallback() { @Override public void run(NotificationServiceInterface service) { long alarmId; try { alarmId = service.currentAlarmId(); } catch (RemoteException e) { return; } AlarmInfo alarmInfo = db.readAlarmInfo(alarmId); if (snoozeMinutes == 0) { snoozeMinutes = db.readAlarmSettings(alarmId).getSnoozeMinutes(); } String info = alarmInfo.getTime().toString() + "\n" + alarmInfo.getName(); if (AppSettings.isDebugMode(getApplicationContext())) { info += " [" + alarmId + "]"; findViewById(R.id.volume).setVisibility(View.VISIBLE); } else { findViewById(R.id.volume).setVisibility(View.GONE); } TextView infoText = (TextView) findViewById(R.id.alarm_info); infoText.setText(info); TextView snoozeInfo = (TextView) findViewById(R.id.notify_snooze_time); snoozeInfo.setText(getString(R.string.snooze) + "\n" + getString(R.string.minutes, snoozeMinutes)); } }); } }
Java
package com.angrydoughnuts.android.alarmclock; import java.util.Calendar; import android.content.Context; import android.os.Parcel; import android.os.Parcelable; public class Week implements Parcelable { public static final Week NO_REPEATS = new Week(new boolean[] {false, false, false, false, false, false, false}); public static final Week EVERYDAY = new Week(new boolean[] {true, true, true, true, true, true, true}); public static final Week WEEKDAYS = new Week(new boolean[] {false, true, true, true, true, true, false}); public static final Week WEEKENDS = new Week(new boolean[] {true, false, false, false, false, false, true}); public enum Day { SUN(R.string.dow_sun), MON(R.string.dow_mon), TUE(R.string.dow_tue), WED(R.string.dow_wed), THU(R.string.dow_thu), FRI(R.string.dow_fri), SAT(R.string.dow_sat); private int stringId; Day (int stringId) { this.stringId = stringId; } public int stringId() { return stringId; } } private boolean[] bitmask; public Week(Parcel source) { bitmask = source.createBooleanArray(); } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeBooleanArray(bitmask); } public Week() { bitmask = new boolean[Day.values().length]; } public Week(Week rhs) { bitmask = rhs.bitmask.clone(); } public Week(boolean[] bitmask) { if (bitmask.length != Day.values().length) { throw new IllegalArgumentException("Wrong sized bitmask: " + bitmask.length); } this.bitmask = bitmask; } public boolean[] bitmask() { return bitmask; } public void addDay(Day day) { bitmask[day.ordinal()] = true; } public void removeDay(Day day) { bitmask[day.ordinal()] = false; } public boolean hasDay(Day day) { return bitmask[day.ordinal()]; } public CharSequence[] names(Context context) { CharSequence[] nameList = new CharSequence[Day.values().length]; for (Day day : Day.values()) { nameList[day.ordinal()] = context.getString(day.stringId()); } return nameList; } public String toString(Context context) { if (this.equals(NO_REPEATS)) { return context.getString(R.string.no_repeats); } if (this.equals(EVERYDAY)) { return context.getString(R.string.everyday); } if (this.equals(WEEKDAYS)) { return context.getString(R.string.weekdays); } if (this.equals(WEEKENDS)) { return context.getString(R.string.weekends); } String list = ""; for (Day day : Day.values()) { if (!bitmask[day.ordinal()]) { continue; } switch (day) { case SUN: list += " " + context.getString(R.string.dow_sun_short); break; case MON: list += " " + context.getString(R.string.dow_mon_short); break; case TUE: list += " " + context.getString(R.string.dow_tue_short); break; case WED: list += " " + context.getString(R.string.dow_wed_short); break; case THU: list += " " + context.getString(R.string.dow_thu_short); break; case FRI: list += " " + context.getString(R.string.dow_fri_short); break; case SAT: list += " " + context.getString(R.string.dow_sat_short); break; } } return list; } @Override public boolean equals(Object o) { if (!(o instanceof Week)) { return false; } Week rhs = (Week) o; if (bitmask.length != rhs.bitmask.length) { return false; } for (Day day : Day.values()) { if (bitmask[day.ordinal()] != rhs.bitmask[day.ordinal()]) { return false; } } return true; } @Override public int describeContents() { return 0; } public static final Parcelable.Creator<Week> CREATOR = new Parcelable.Creator<Week>() { @Override public Week createFromParcel(Parcel source) { return new Week(source); } @Override public Week[] newArray(int size) { return new Week[size]; } }; public static Day calendarToDay(int dow) { int ordinalOffset = dow - Calendar.SUNDAY; return Day.values()[ordinalOffset]; } }
Java
/**************************************************************************** * Copyright 2010 kraigs.android@gmail.com * 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.angrydoughnuts.android.alarmclock; import java.util.LinkedList; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.ServiceConnection; import android.os.IBinder; import android.os.RemoteException; public class NotificationServiceBinder { private Context context; private NotificationServiceInterface notify; private LinkedList<ServiceCallback> callbacks; NotificationServiceBinder(Context context) { this.context = context; this.callbacks = new LinkedList<ServiceCallback>(); } public void bind() { final Intent serviceIntent = new Intent(context, NotificationService.class); if (!context.bindService(serviceIntent, serviceConnection, Context.BIND_AUTO_CREATE)) { throw new IllegalStateException("Unable to bind to NotificationService."); } } public void unbind() { context.unbindService(serviceConnection); notify = null; } public interface ServiceCallback { void run(NotificationServiceInterface service); } final private ServiceConnection serviceConnection = new ServiceConnection() { @Override public void onServiceConnected(ComponentName name, IBinder service) { notify = NotificationServiceInterface.Stub.asInterface(service); while (callbacks.size() > 0) { ServiceCallback callback = callbacks.remove(); callback.run(notify); } } @Override public void onServiceDisconnected(ComponentName name) { notify = null; } }; public void call(ServiceCallback callback) { if (notify != null) { callback.run(notify); } else { callbacks.offer(callback); } } public void acknowledgeCurrentNotification(final int snoozeMinutes) { call(new ServiceCallback() { @Override public void run(NotificationServiceInterface service) { try { service.acknowledgeCurrentNotification(snoozeMinutes); } catch (RemoteException e) { e.printStackTrace(); } } }); } }
Java
/**************************************************************************** * Copyright 2010 kraigs.android@gmail.com * 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.angrydoughnuts.android.alarmclock; import java.util.Calendar; import com.angrydoughnuts.android.alarmclock.Week.Day; import android.content.ContentValues; import android.database.Cursor; /** * This class contains the data that represents an alarm. That is, a unique * numeric identifier, a time, whether or not it's enabled, and a configured * name. It also provides a mapping to and from the respective columns in * the alarm database for each of these pieces of data. */ public final class AlarmInfo { private long alarmId; private AlarmTime time; private boolean enabled; private String name; public AlarmInfo(Cursor cursor) { alarmId = cursor.getLong(cursor.getColumnIndex(DbHelper.ALARMS_COL__ID)); enabled = cursor.getInt(cursor.getColumnIndex(DbHelper.ALARMS_COL_ENABLED)) == 1; name = cursor.getString(cursor.getColumnIndex(DbHelper.ALARMS_COL_NAME)); int secondsAfterMidnight = cursor.getInt(cursor.getColumnIndex(DbHelper.ALARMS_COL_TIME)); int dowBitmask = cursor.getInt(cursor.getColumnIndex(DbHelper.ALARMS_COL_DAY_OF_WEEK)); time = BuildAlarmTime(secondsAfterMidnight, dowBitmask); } public AlarmInfo(AlarmTime time, boolean enabled, String name) { alarmId = -69; // initially invalid. this.time = time; this.enabled = enabled; this.name = name; } public AlarmInfo(AlarmInfo rhs) { alarmId = rhs.alarmId; time = new AlarmTime(rhs.time); enabled = rhs.enabled; name = rhs.name; } @Override public boolean equals(Object o) { if (!(o instanceof AlarmInfo)) { return false; } AlarmInfo rhs = (AlarmInfo) o; return alarmId == rhs.alarmId && time.equals(rhs.time) && enabled == rhs.enabled && name.equals(rhs.name); } public ContentValues contentValues() { ContentValues values = new ContentValues(); values.put(DbHelper.ALARMS_COL_TIME, TimeToInteger(time)); values.put(DbHelper.ALARMS_COL_ENABLED, enabled); values.put(DbHelper.ALARMS_COL_NAME, name); values.put(DbHelper.ALARMS_COL_DAY_OF_WEEK, WeekToInteger(time)); return values; } static public String[] contentColumns() { return new String[] { DbHelper.ALARMS_COL__ID, DbHelper.ALARMS_COL_TIME, DbHelper.ALARMS_COL_ENABLED, DbHelper.ALARMS_COL_NAME, DbHelper.ALARMS_COL_DAY_OF_WEEK }; } public long getAlarmId() { return alarmId; } public AlarmTime getTime() { return time; } public void setTime(AlarmTime time) { this.time = time; } public boolean enabled() { return enabled; } public void setEnabled(boolean enabled) { this.enabled = enabled; } public String getName() { return name; } public void setName(String name) { this.name = name; } private static int TimeToInteger(AlarmTime time) { Calendar c = time.calendar(); int hourOfDay = c.get(Calendar.HOUR_OF_DAY); int minute = c.get(Calendar.MINUTE); int second = c.get(Calendar.SECOND); return hourOfDay * 3600 + minute * 60 + second; } private static int WeekToInteger(AlarmTime time) { boolean[] bitmask = time.getDaysOfWeek().bitmask(); int dowBitmask = 0; for (Day day: Day.values()) { if (bitmask[day.ordinal()]) { dowBitmask |= 1 << day.ordinal(); } } return dowBitmask; } private static AlarmTime BuildAlarmTime(int secondsAfterMidnight, int dowBitmask) { int hours = secondsAfterMidnight % 3600; int minutes = (secondsAfterMidnight - (hours * 3600)) % 60; int seconds = (secondsAfterMidnight- (hours * 3600 + minutes * 60)); Week week = new Week(); for (Day day : Day.values()) { if ((dowBitmask & 1 << day.ordinal()) > 0) { week.addDay(day); } } return new AlarmTime(hours, minutes, seconds, week); } }
Java
/**************************************************************************** * Copyright 2010 kraigs.android@gmail.com * 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.angrydoughnuts.android.alarmclock; import java.io.BufferedWriter; import java.io.FileWriter; import java.io.PrintWriter; import java.io.StringWriter; import java.io.Writer; import java.lang.Thread.UncaughtExceptionHandler; import java.text.SimpleDateFormat; import java.util.Calendar; /** * An exception handler that writes the stact trace to a file on the * device's SD card. Make sure that the WRITE_EXTERNAL_STORAGE permission * is available before using his class. * NOTE: Mostly lifted from: * http://stackoverflow.com/questions/601503/how-do-i-obtain-crash-data-from-my-android-application */ public final class LoggingUncaughtExceptionHandler implements UncaughtExceptionHandler { private String directory; private UncaughtExceptionHandler defaultHandler; public LoggingUncaughtExceptionHandler(String directory) { this.directory = directory; this.defaultHandler = Thread.getDefaultUncaughtExceptionHandler(); } @Override public void uncaughtException(Thread thread, Throwable ex) { try { String timestamp = new SimpleDateFormat("yyyyMMdd_kkmmss.SSSS").format(Calendar.getInstance().getTime()); String filename = timestamp + "-alarmclock.txt"; Writer stacktrace = new StringWriter(); ex.printStackTrace(new PrintWriter(stacktrace)); BufferedWriter bos = new BufferedWriter(new FileWriter(directory + "/" + filename)); bos.write(stacktrace.toString()); bos.flush(); bos.close(); stacktrace.close(); } catch (Exception e) { e.printStackTrace(); } finally { defaultHandler.uncaughtException(thread, ex); } } }
Java
package com.angrydoughnuts.android.alarmclock; import com.angrydoughnuts.android.alarmclock.WakeLock.WakeLockException; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.net.Uri; public class ReceiverAlarm extends BroadcastReceiver { @Override public void onReceive(Context context, Intent recvIntent) { Uri alarmUri = recvIntent.getData(); long alarmId = AlarmUtil.alarmUriToId(alarmUri); try { WakeLock.acquire(context, alarmId); } catch (WakeLockException e) { if (AppSettings.isDebugMode(context)) { throw new IllegalStateException(e.getMessage()); } } Intent notifyService = new Intent(context, NotificationService.class); notifyService.setData(alarmUri); context.startService(notifyService); } }
Java
/**************************************************************************** * Copyright 2010 kraigs.android@gmail.com * 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.angrydoughnuts.android.alarmclock; import java.util.LinkedList; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.ServiceConnection; import android.os.IBinder; import android.os.RemoteException; /** * This class is a wrapper for the process of binding to the AlarmClockService. * It provides a seemingly synchronous semantic for the asynchronous binding * process. If the service is not properly bound, a callback is created and * registered to be run as soon as binding successfully completes. Call * bind() and unbind() to trigger these processes. */ public class AlarmClockServiceBinder { private Context context; private AlarmClockInterface clock; private LinkedList<ServiceCallback> callbacks; public AlarmClockServiceBinder(Context context) { this.context = context; this.callbacks = new LinkedList<ServiceCallback>(); } public AlarmClockInterface clock() { return clock; } public void bind() { final Intent serviceIntent = new Intent(context, AlarmClockService.class); if (!context.bindService(serviceIntent, serviceConnection, Context.BIND_AUTO_CREATE)) { throw new IllegalStateException("Unable to bind to AlarmClockService."); } } public void unbind() { context.unbindService(serviceConnection); clock = null; } private interface ServiceCallback { void run() throws RemoteException; } final private ServiceConnection serviceConnection = new ServiceConnection() { @Override public void onServiceConnected(ComponentName name, IBinder service) { clock = AlarmClockInterface.Stub.asInterface(service); while (callbacks.size() > 0) { ServiceCallback callback = callbacks.remove(); try { callback.run(); } catch (RemoteException e) { e.printStackTrace(); } } } @Override public void onServiceDisconnected(ComponentName name) { clock = null; } }; private void runOrDefer(ServiceCallback callback) { if (clock != null) { try { callback.run(); } catch (RemoteException e) { e.printStackTrace(); } } else { callbacks.offer(callback); } } public void createAlarm(final AlarmTime time) { runOrDefer(new ServiceCallback() { @Override public void run() throws RemoteException { clock.createAlarm(time); } }); } public void deleteAlarm(final long alarmId) { runOrDefer(new ServiceCallback() { @Override public void run() throws RemoteException { clock.deleteAlarm(alarmId); } }); } public void deleteAllAlarms() { runOrDefer(new ServiceCallback() { @Override public void run() throws RemoteException { clock.deleteAllAlarms(); } }); } public void scheduleAlarm(final long alarmId) { runOrDefer(new ServiceCallback() { @Override public void run() throws RemoteException { clock.scheduleAlarm(alarmId); } }); } public void unscheduleAlarm(final long alarmId) { runOrDefer(new ServiceCallback() { @Override public void run() throws RemoteException { clock.unscheduleAlarm(alarmId); } }); } public void acknowledgeAlarm(final long alarmId) { runOrDefer(new ServiceCallback() { @Override public void run() throws RemoteException { clock.acknowledgeAlarm(alarmId); } }); } public void snoozeAlarm(final long alarmId) { runOrDefer(new ServiceCallback() { @Override public void run() throws RemoteException { clock.snoozeAlarm(alarmId); } }); } public void snoozeAlarmFor(final long alarmId, final int minutes) { runOrDefer(new ServiceCallback() { @Override public void run() throws RemoteException { clock.snoozeAlarmFor(alarmId, minutes); } }); } }
Java
/**************************************************************************** * Copyright 2010 kraigs.android@gmail.com * 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.angrydoughnuts.android.alarmclock; import java.text.SimpleDateFormat; import java.util.Calendar; import com.angrydoughnuts.android.alarmclock.Week.Day; import android.content.Context; import android.os.Parcel; import android.os.Parcelable; import android.text.format.DateFormat; /** * A class that encapsulates an alarm time. It represents a time between 00:00 * and 23:59. It also contains a list of days on which this alarm should be * rescheduled. If no days are listed, the alarm is only scheduled once * per time it is enabled. The class is Parcelable so that it can be * returned as an object from the AlarmClockService and is Comparable so that * an ordered list can be created in PendingAlarmList. */ public final class AlarmTime implements Parcelable, Comparable<AlarmTime> { private Calendar calendar; private Week daysOfWeek; /** * Copy constructor. * @param rhs */ public AlarmTime(AlarmTime rhs) { calendar = (Calendar) rhs.calendar.clone(); daysOfWeek = new Week(rhs.daysOfWeek); } /** * Construct an AlarmTime for the next occurrence of this hour/minute/second. * It will not repeat. * @param hourOfDay * @param minute * @param second */ public AlarmTime(int hourOfDay, int minute, int second) { this(hourOfDay, minute, second, new Week()); } /** * Construct an AlarmTime for the next occurrence of this hour/minute/second * which occurs on the specified days of the week. * @param hourOfDay * @param minute * @param second * @param daysOfWeek */ public AlarmTime(int hourOfDay, int minute, int second, Week daysOfWeek) { this.calendar = Calendar.getInstance(); calendar.set(Calendar.HOUR_OF_DAY, hourOfDay); calendar.set(Calendar.MINUTE, minute); calendar.set(Calendar.SECOND, second); this.daysOfWeek = daysOfWeek; findNextOccurrence(); } private void findNextOccurrence() { Calendar now = Calendar.getInstance(); // If this hour/minute/second has already occurred today, move to tomorrow. if (calendar.before(now)) { calendar.add(Calendar.DATE, 1); } if (calendar.before(now)) { throw new IllegalStateException("Inconsistent calendar."); } // If there are no repeats requested, there is nothing left to do. if (daysOfWeek.equals(Week.NO_REPEATS)) { return; } // Keep incrementing days until we hit a suitable day of the week. for (int i = 0; i < Day.values().length; ++i) { Day alarmDay = Week.calendarToDay(calendar.get(Calendar.DAY_OF_WEEK)); if (daysOfWeek.hasDay(alarmDay)) { return; } calendar.add(Calendar.DATE, 1); } throw new IllegalStateException("Didn't find a suitable date for alarm."); } @Override public int compareTo(AlarmTime another) { return calendar.compareTo(another.calendar); } @Override public boolean equals(Object o) { if (!(o instanceof AlarmTime)) { return false; } AlarmTime rhs = (AlarmTime) o; if (!calendar.equals(rhs.calendar)) { return false; } return this.daysOfWeek.equals(rhs.daysOfWeek); } public String toString() { SimpleDateFormat formatter = new SimpleDateFormat("HH:mm.ss MMMM dd yyyy"); return formatter.format(calendar.getTimeInMillis()); } public String localizedString(Context context) { boolean is24HourFormat = DateFormat.is24HourFormat(context); String format = ""; String second = ""; if (AppSettings.isDebugMode(context)) { second = ".ss"; } if (is24HourFormat) { format = "HH:mm" + second; } else { format = "h:mm" + second + " aaa"; } SimpleDateFormat formatter = new SimpleDateFormat(format); return formatter.format(calendar.getTime()); } public Calendar calendar() { return calendar; } public Week getDaysOfWeek() { return daysOfWeek; } public boolean repeats() { return !daysOfWeek.equals(Week.NO_REPEATS); } public String timeUntilString(Context c) { Calendar now = Calendar.getInstance(); if (calendar.before(now)) { return c.getString(R.string.alarm_has_occurred); } long now_min = now.getTimeInMillis() / 1000 / 60; long then_min = calendar.getTimeInMillis() / 1000 / 60; long difference_minutes = then_min - now_min; long days = difference_minutes / (60 * 24); long hours = difference_minutes % (60 * 24); long minutes = hours % 60; hours = hours / 60; String value = ""; if (days == 1) { value += c.getString(R.string.day, days) + " "; } else if (days > 1) { value += c.getString(R.string.days, days) + " "; } if (hours == 1) { value += c.getString(R.string.hour, hours) + " "; } else if (hours > 1) { value += c.getString(R.string.hours, hours) + " "; } if (minutes == 1) { value += c.getString(R.string.minute, minutes) + " "; } else if (minutes > 1) { value += c.getString(R.string.minutes, minutes) + " "; } return value; } /** * A static method which generates an AlarmTime object @minutes in the future. * It first truncates seconds (rounds down to the nearest minute) before * adding @minutes * @param minutes * @return */ public static AlarmTime snoozeInMillisUTC(int minutes) { Calendar snooze = Calendar.getInstance(); snooze.set(Calendar.SECOND, 0); snooze.add(Calendar.MINUTE, minutes); return new AlarmTime( snooze.get(Calendar.HOUR_OF_DAY), snooze.get(Calendar.MINUTE), snooze.get(Calendar.SECOND)); } private AlarmTime(Parcel source) { this.calendar = (Calendar) source.readSerializable(); this.daysOfWeek = source.readParcelable(null); } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeSerializable(calendar); dest.writeParcelable(daysOfWeek, 0); } public static final Parcelable.Creator<AlarmTime> CREATOR = new Parcelable.Creator<AlarmTime>() { @Override public AlarmTime createFromParcel(Parcel source) { return new AlarmTime(source); } @Override public AlarmTime[] newArray(int size) { return new AlarmTime[size]; } }; @Override public int describeContents() { return 0; } }
Java
/**************************************************************************** * Copyright 2010 kraigs.android@gmail.com * 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.angrydoughnuts.android.alarmclock; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; public final class DbHelper extends SQLiteOpenHelper { public static final String DB_NAME = "alarmclock"; public static final int DB_VERSION = 1; public static final String DB_TABLE_ALARMS = "alarms"; public static final String ALARMS_COL__ID = "_id"; public static final String ALARMS_COL_TIME = "time"; public static final String ALARMS_COL_ENABLED = "enabled"; public static final String ALARMS_COL_NAME = "name"; public static final String ALARMS_COL_DAY_OF_WEEK = "dow"; public static final String DB_TABLE_SETTINGS = "settings"; public static final String SETTINGS_COL_ID = "id"; public static final String SETTINGS_COL_TONE_URL = "tone_url"; public static final String SETTINGS_COL_TONE_NAME = "tone_name"; public static final String SETTINGS_COL_SNOOZE = "snooze"; public static final String SETTINGS_COL_VIBRATE = "vibrate"; public static final String SETTINGS_COL_VOLUME_STARTING = "vol_start"; public static final String SETTINGS_COL_VOLUME_ENDING = "vol_end"; public static final String SETTINGS_COL_VOLUME_TIME = "vol_time"; public DbHelper(Context context) { super(context, DB_NAME, null, DB_VERSION); } @Override public void onCreate(SQLiteDatabase db) { // Alarm metadata table: // |(auto primary) | (0 to 86399) | (boolean) | (string) | (bitmask(7)) | // | _id | time | enabled | name | dow | // time is seconds past midnight. db.execSQL("CREATE TABLE " + DB_TABLE_ALARMS + " (" + ALARMS_COL__ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + ALARMS_COL_NAME + " TEXT, " + ALARMS_COL_DAY_OF_WEEK + " UNSIGNED INTEGER (0, 127), " + ALARMS_COL_TIME + " UNSIGNED INTEGER (0, 86399)," + ALARMS_COL_ENABLED + " UNSIGNED INTEGER (0, 1))"); // |(primary) | (string) | (string) | (1 to 60) | (boolean) | (0 to 100) | (0 to 100) | (0 to 60) | // | id | tone_url | tone_name | snooze | vibrate | vol_start | vol_end | vol_time | // snooze is in minutes. db.execSQL("CREATE TABLE " + DB_TABLE_SETTINGS + " (" + SETTINGS_COL_ID + " INTEGER PRIMARY KEY, " + SETTINGS_COL_TONE_URL + " TEXT," + SETTINGS_COL_TONE_NAME + " TEXT," + SETTINGS_COL_SNOOZE + " UNSIGNED INTEGER (1, 60)," + SETTINGS_COL_VIBRATE + " UNSIGNED INTEGER (0, 1)," + SETTINGS_COL_VOLUME_STARTING + " UNSIGNED INTEGER (1, 100)," + SETTINGS_COL_VOLUME_ENDING + " UNSIGNED INTEGER (1, 100)," + SETTINGS_COL_VOLUME_TIME + " UNSIGNED INTEGER (1, 60))"); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { } }
Java
/**************************************************************************** * Copyright 2010 kraigs.android@gmail.com * 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.angrydoughnuts.android.alarmclock; import java.util.ArrayList; import java.util.Arrays; import android.app.Activity; import android.content.Context; import android.database.Cursor; import android.database.MergeCursor; import android.graphics.Typeface; import android.media.MediaPlayer; import android.net.Uri; import android.provider.BaseColumns; import android.util.AttributeSet; import android.view.KeyEvent; import android.view.View; import android.widget.AdapterView; import android.widget.ListView; import android.widget.SimpleCursorAdapter; import android.widget.TextView; import android.widget.ViewFlipper; import android.widget.AdapterView.OnItemClickListener; import android.widget.SimpleCursorAdapter.ViewBinder; /** * An extension to the ListView widget specialized for selecting audio media. * Use one of the concrete implementations MediaSongsView, MediaArtistsView * or MediaAlbumsView. */ public class MediaListView extends ListView implements OnItemClickListener { public interface OnItemPickListener { public void onItemPick(Uri uri, String name); } protected static int DEFAULT_TONE_INDEX = -69; private Cursor cursor; private Cursor staticCursor; private MediaPlayer mPlayer; private ViewFlipper flipper; private Activity cursorManager; private Uri contentUri; private String nameColumn; private String sortOrder; private OnItemPickListener listener; private String selectedName; private Uri selectedUri; public MediaListView(Context context) { this(context, null); } public MediaListView(Context context, AttributeSet attrs) { this(context, attrs, 0); } public MediaListView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); setChoiceMode(CHOICE_MODE_SINGLE); setOnKeyListener(new OnKeyListener() { @Override public boolean onKey(View v, int keyCode, KeyEvent event) { if (flipper == null || flipper.getDisplayedChild() == 0) { return false; } if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) { if (event.getAction() == KeyEvent.ACTION_UP) { if (mPlayer != null) { mPlayer.stop(); } flipper.setInAnimation(getContext(), R.anim.slide_in_right); flipper.setOutAnimation(getContext(), R.anim.slide_out_right); flipper.showPrevious(); } return true; } return false; } }); } public void setMediaPlayer(MediaPlayer mPlayer) { this.mPlayer = mPlayer; } protected MediaPlayer getMediaPlayer() { return mPlayer; } public void addToFlipper(ViewFlipper flipper) { this.flipper = flipper; flipper.setAnimateFirstView(false); flipper.addView(this); } protected ViewFlipper getFlipper() { return flipper; } public void setCursorManager(Activity activity) { this.cursorManager = activity; } protected void manageCursor(Cursor cursor) { cursorManager.startManagingCursor(cursor); } protected void query(Uri contentUri, String nameColumn, int rowResId, String[] displayColumns, int[] resIDs) { query(contentUri, nameColumn, null, rowResId, displayColumns, resIDs); } protected void query(Uri contentUri, String nameColumn, String selection, int rowResId, String[] displayColumns, int[] resIDs) { this.nameColumn = nameColumn; final ArrayList<String> queryColumns = new ArrayList<String>(displayColumns.length + 1); queryColumns.addAll(Arrays.asList(displayColumns)); // The ID column is required for the SimpleCursorAdapter. Make sure to // add it if it's not already there. if (!queryColumns.contains(BaseColumns._ID)) { queryColumns.add(BaseColumns._ID); } Cursor dbCursor = getContext().getContentResolver().query( contentUri, queryColumns.toArray(new String[] {}), selection, null, sortOrder); if (staticCursor != null) { Cursor[] cursors = new Cursor[] { staticCursor, dbCursor }; cursor = new MergeCursor(cursors); } else { cursor = dbCursor; } manageCursor(cursor); this.contentUri = contentUri; final SimpleCursorAdapter adapter = new SimpleCursorAdapter( getContext(), rowResId, cursor, displayColumns, resIDs); // Use a custom binder to highlight the selected element. adapter.setViewBinder(new ViewBinder() { @Override public boolean setViewValue(View view, Cursor cursor, int columnIndex) { if (view.getVisibility() == View.VISIBLE && view instanceof TextView) { TextView text = (TextView) view; if (isItemChecked(cursor.getPosition())) { text.setTypeface(Typeface.DEFAULT_BOLD); } else { text.setTypeface(Typeface.DEFAULT); } } // Let the default binder do the real work. return false; }}); setAdapter(adapter); setOnItemClickListener(this); } public void overrideSortOrder(String sortOrder) { this.sortOrder = sortOrder; } protected void includeStaticCursor(Cursor cursor) { staticCursor = cursor; } // TODO(cgallek): get rid of these two accessor methods in favor of // onClick callbacks. public String getLastSelectedName() { return selectedName; } public Uri getLastSelectedUri() { return selectedUri; } public void setMediaPickListener(OnItemPickListener listener) { this.listener = listener; } @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { setItemChecked(position, true); cursor.moveToPosition(position); selectedName = cursor.getString(cursor.getColumnIndex(nameColumn)); final int toneIndex = cursor.getInt(cursor.getColumnIndex(BaseColumns._ID)); if (toneIndex == DEFAULT_TONE_INDEX) { selectedUri = AlarmUtil.getDefaultAlarmUri(); } else { selectedUri = Uri.withAppendedPath(contentUri, "" + toneIndex); } if (listener != null) { listener.onItemPick(selectedUri, selectedName); } } }
Java
/* * Copyright 2011 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.google.android.apps.iosched.service; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.io.LocalBlocksHandler; import com.google.android.apps.iosched.io.LocalExecutor; import com.google.android.apps.iosched.io.LocalRoomsHandler; import com.google.android.apps.iosched.io.LocalSearchSuggestHandler; import com.google.android.apps.iosched.io.LocalSessionsHandler; import com.google.android.apps.iosched.io.LocalTracksHandler; import com.google.android.apps.iosched.io.RemoteExecutor; import com.google.android.apps.iosched.io.RemoteSessionsHandler; import com.google.android.apps.iosched.io.RemoteSpeakersHandler; import com.google.android.apps.iosched.io.RemoteVendorsHandler; import com.google.android.apps.iosched.io.RemoteWorksheetsHandler; import com.google.android.apps.iosched.provider.ScheduleProvider; import org.apache.http.Header; import org.apache.http.HeaderElement; import org.apache.http.HttpEntity; import org.apache.http.HttpRequest; import org.apache.http.HttpRequestInterceptor; import org.apache.http.HttpResponse; import org.apache.http.HttpResponseInterceptor; import org.apache.http.client.HttpClient; import org.apache.http.entity.HttpEntityWrapper; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.params.BasicHttpParams; import org.apache.http.params.HttpConnectionParams; import org.apache.http.params.HttpParams; import org.apache.http.params.HttpProtocolParams; import org.apache.http.protocol.HttpContext; import android.app.IntentService; import android.app.Service; import android.content.ContentResolver; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.pm.PackageManager.NameNotFoundException; import android.content.res.Resources; import android.os.Bundle; import android.os.ResultReceiver; import android.text.format.DateUtils; import android.util.Log; import java.io.IOException; import java.io.InputStream; import java.util.zip.GZIPInputStream; /** * Background {@link Service} that synchronizes data living in * {@link ScheduleProvider}. Reads data from both local {@link Resources} and * from remote sources, such as a spreadsheet. */ public class SyncService extends IntentService { private static final String TAG = "SyncService"; public static final String EXTRA_STATUS_RECEIVER = "com.google.android.iosched.extra.STATUS_RECEIVER"; public static final int STATUS_RUNNING = 0x1; public static final int STATUS_ERROR = 0x2; public static final int STATUS_FINISHED = 0x3; private static final int SECOND_IN_MILLIS = (int) DateUtils.SECOND_IN_MILLIS; /** Root worksheet feed for online data source */ // TODO: insert your sessions/speakers/vendors spreadsheet doc URL here. private static final String WORKSHEETS_URL = "INSERT_SPREADSHEET_URL_HERE"; private static final String HEADER_ACCEPT_ENCODING = "Accept-Encoding"; private static final String ENCODING_GZIP = "gzip"; private static final int VERSION_NONE = 0; private static final int VERSION_CURRENT = 11; private LocalExecutor mLocalExecutor; private RemoteExecutor mRemoteExecutor; public SyncService() { super(TAG); } @Override public void onCreate() { super.onCreate(); final HttpClient httpClient = getHttpClient(this); final ContentResolver resolver = getContentResolver(); mLocalExecutor = new LocalExecutor(getResources(), resolver); mRemoteExecutor = new RemoteExecutor(httpClient, resolver); } @Override protected void onHandleIntent(Intent intent) { Log.d(TAG, "onHandleIntent(intent=" + intent.toString() + ")"); final ResultReceiver receiver = intent.getParcelableExtra(EXTRA_STATUS_RECEIVER); if (receiver != null) receiver.send(STATUS_RUNNING, Bundle.EMPTY); final Context context = this; final SharedPreferences prefs = getSharedPreferences(Prefs.IOSCHED_SYNC, Context.MODE_PRIVATE); final int localVersion = prefs.getInt(Prefs.LOCAL_VERSION, VERSION_NONE); try { // Bulk of sync work, performed by executing several fetches from // local and online sources. final long startLocal = System.currentTimeMillis(); final boolean localParse = localVersion < VERSION_CURRENT; Log.d(TAG, "found localVersion=" + localVersion + " and VERSION_CURRENT=" + VERSION_CURRENT); if (localParse) { // Load static local data mLocalExecutor.execute(R.xml.blocks, new LocalBlocksHandler()); mLocalExecutor.execute(R.xml.rooms, new LocalRoomsHandler()); mLocalExecutor.execute(R.xml.tracks, new LocalTracksHandler()); mLocalExecutor.execute(R.xml.search_suggest, new LocalSearchSuggestHandler()); mLocalExecutor.execute(R.xml.sessions, new LocalSessionsHandler()); // Parse values from local cache first, since spreadsheet copy // or network might be down. mLocalExecutor.execute(context, "cache-sessions.xml", new RemoteSessionsHandler()); mLocalExecutor.execute(context, "cache-speakers.xml", new RemoteSpeakersHandler()); mLocalExecutor.execute(context, "cache-vendors.xml", new RemoteVendorsHandler()); // Save local parsed version prefs.edit().putInt(Prefs.LOCAL_VERSION, VERSION_CURRENT).commit(); } Log.d(TAG, "local sync took " + (System.currentTimeMillis() - startLocal) + "ms"); // Always hit remote spreadsheet for any updates final long startRemote = System.currentTimeMillis(); mRemoteExecutor .executeGet(WORKSHEETS_URL, new RemoteWorksheetsHandler(mRemoteExecutor)); Log.d(TAG, "remote sync took " + (System.currentTimeMillis() - startRemote) + "ms"); } catch (Exception e) { Log.e(TAG, "Problem while syncing", e); if (receiver != null) { // Pass back error to surface listener final Bundle bundle = new Bundle(); bundle.putString(Intent.EXTRA_TEXT, e.toString()); receiver.send(STATUS_ERROR, bundle); } } // Announce success to any surface listener Log.d(TAG, "sync finished"); if (receiver != null) receiver.send(STATUS_FINISHED, Bundle.EMPTY); } /** * Generate and return a {@link HttpClient} configured for general use, * including setting an application-specific user-agent string. */ public static HttpClient getHttpClient(Context context) { final HttpParams params = new BasicHttpParams(); // Use generous timeouts for slow mobile networks HttpConnectionParams.setConnectionTimeout(params, 20 * SECOND_IN_MILLIS); HttpConnectionParams.setSoTimeout(params, 20 * SECOND_IN_MILLIS); HttpConnectionParams.setSocketBufferSize(params, 8192); HttpProtocolParams.setUserAgent(params, buildUserAgent(context)); final DefaultHttpClient client = new DefaultHttpClient(params); client.addRequestInterceptor(new HttpRequestInterceptor() { public void process(HttpRequest request, HttpContext context) { // Add header to accept gzip content if (!request.containsHeader(HEADER_ACCEPT_ENCODING)) { request.addHeader(HEADER_ACCEPT_ENCODING, ENCODING_GZIP); } } }); client.addResponseInterceptor(new HttpResponseInterceptor() { public void process(HttpResponse response, HttpContext context) { // Inflate any responses compressed with gzip final HttpEntity entity = response.getEntity(); final Header encoding = entity.getContentEncoding(); if (encoding != null) { for (HeaderElement element : encoding.getElements()) { if (element.getName().equalsIgnoreCase(ENCODING_GZIP)) { response.setEntity(new InflatingEntity(response.getEntity())); break; } } } } }); return client; } /** * Build and return a user-agent string that can identify this application * to remote servers. Contains the package name and version code. */ private static String buildUserAgent(Context context) { try { final PackageManager manager = context.getPackageManager(); final PackageInfo info = manager.getPackageInfo(context.getPackageName(), 0); // Some APIs require "(gzip)" in the user-agent string. return info.packageName + "/" + info.versionName + " (" + info.versionCode + ") (gzip)"; } catch (NameNotFoundException e) { return null; } } /** * Simple {@link HttpEntityWrapper} that inflates the wrapped * {@link HttpEntity} by passing it through {@link GZIPInputStream}. */ private static class InflatingEntity extends HttpEntityWrapper { public InflatingEntity(HttpEntity wrapped) { super(wrapped); } @Override public InputStream getContent() throws IOException { return new GZIPInputStream(wrappedEntity.getContent()); } @Override public long getContentLength() { return -1; } } private interface Prefs { String IOSCHED_SYNC = "iosched_sync"; String LOCAL_VERSION = "local_version"; } }
Java
/* * Copyright 2011 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.google.android.apps.iosched.ui; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.ui.widget.BlockView; import com.google.android.apps.iosched.ui.widget.BlocksLayout; import com.google.android.apps.iosched.ui.widget.ObservableScrollView; import com.google.android.apps.iosched.ui.widget.Workspace; import com.google.android.apps.iosched.util.AnalyticsUtils; import com.google.android.apps.iosched.util.Maps; import com.google.android.apps.iosched.util.MotionEventUtils; import com.google.android.apps.iosched.util.NotifyingAsyncQueryHandler; import com.google.android.apps.iosched.util.ParserUtils; import com.google.android.apps.iosched.util.UIUtils; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.database.ContentObserver; import android.database.Cursor; import android.graphics.Rect; import android.graphics.drawable.LayerDrawable; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.provider.BaseColumns; import android.support.v4.app.Fragment; import android.text.format.DateUtils; import android.util.Log; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import android.widget.Toast; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.TimeZone; /** * Shows a horizontally-pageable calendar of conference days. Horizontaly paging is achieved using * {@link Workspace}, and the primary UI classes for rendering the calendar are * {@link com.google.android.apps.iosched.ui.widget.TimeRulerView}, * {@link BlocksLayout}, and {@link BlockView}. */ public class ScheduleFragment extends Fragment implements NotifyingAsyncQueryHandler.AsyncQueryListener, ObservableScrollView.OnScrollListener, View.OnClickListener { private static final String TAG = "ScheduleFragment"; /** * Flags used with {@link android.text.format.DateUtils#formatDateRange}. */ private static final int TIME_FLAGS = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_WEEKDAY | DateUtils.FORMAT_ABBREV_WEEKDAY; private static final long TUE_START = ParserUtils.parseTime("2011-05-10T00:00:00.000-07:00"); private static final long WED_START = ParserUtils.parseTime("2011-05-11T00:00:00.000-07:00"); private static final int DISABLED_BLOCK_ALPHA = 100; private static final HashMap<String, Integer> sTypeColumnMap = buildTypeColumnMap(); // TODO: show blocks that don't fall into columns at the bottom public static final String EXTRA_TIME_START = "com.google.android.iosched.extra.TIME_START"; public static final String EXTRA_TIME_END = "com.google.android.iosched.extra.TIME_END"; private NotifyingAsyncQueryHandler mHandler; private Workspace mWorkspace; private TextView mTitle; private int mTitleCurrentDayIndex = -1; private View mLeftIndicator; private View mRightIndicator; /** * A helper class containing object references related to a particular day in the schedule. */ private class Day { private ViewGroup rootView; private ObservableScrollView scrollView; private View nowView; private BlocksLayout blocksView; private int index = -1; private String label = null; private Uri blocksUri = null; private long timeStart = -1; private long timeEnd = -1; } private List<Day> mDays = new ArrayList<Day>(); private static HashMap<String, Integer> buildTypeColumnMap() { final HashMap<String, Integer> map = Maps.newHashMap(); map.put(ParserUtils.BLOCK_TYPE_FOOD, 0); map.put(ParserUtils.BLOCK_TYPE_SESSION, 1); map.put(ParserUtils.BLOCK_TYPE_OFFICE_HOURS, 2); return map; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mHandler = new NotifyingAsyncQueryHandler(getActivity().getContentResolver(), this); setHasOptionsMenu(true); AnalyticsUtils.getInstance(getActivity()).trackPageView("/Schedule"); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { ViewGroup root = (ViewGroup) inflater.inflate(R.layout.fragment_schedule, null); mWorkspace = (Workspace) root.findViewById(R.id.workspace); mTitle = (TextView) root.findViewById(R.id.block_title); mLeftIndicator = root.findViewById(R.id.indicator_left); mLeftIndicator.setOnTouchListener(new View.OnTouchListener() { public boolean onTouch(View view, MotionEvent motionEvent) { if ((motionEvent.getAction() & MotionEventUtils.ACTION_MASK) == MotionEvent.ACTION_DOWN) { mWorkspace.scrollLeft(); return true; } return false; } }); mLeftIndicator.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { mWorkspace.scrollLeft(); } }); mRightIndicator = root.findViewById(R.id.indicator_right); mRightIndicator.setOnTouchListener(new View.OnTouchListener() { public boolean onTouch(View view, MotionEvent motionEvent) { if ((motionEvent.getAction() & MotionEventUtils.ACTION_MASK) == MotionEvent.ACTION_DOWN) { mWorkspace.scrollRight(); return true; } return false; } }); mRightIndicator.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { mWorkspace.scrollRight(); } }); setupDay(inflater, TUE_START); setupDay(inflater, WED_START); updateWorkspaceHeader(0); mWorkspace.setOnScrollListener(new Workspace.OnScrollListener() { public void onScroll(float screenFraction) { updateWorkspaceHeader(Math.round(screenFraction)); } }, true); return root; } public void updateWorkspaceHeader(int dayIndex) { if (mTitleCurrentDayIndex == dayIndex) { return; } mTitleCurrentDayIndex = dayIndex; Day day = mDays.get(dayIndex); mTitle.setText(day.label); mLeftIndicator .setVisibility((dayIndex != 0) ? View.VISIBLE : View.INVISIBLE); mRightIndicator .setVisibility((dayIndex < mDays.size() - 1) ? View.VISIBLE : View.INVISIBLE); } private void setupDay(LayoutInflater inflater, long startMillis) { Day day = new Day(); // Setup data day.index = mDays.size(); day.timeStart = startMillis; day.timeEnd = startMillis + DateUtils.DAY_IN_MILLIS; day.blocksUri = ScheduleContract.Blocks.buildBlocksBetweenDirUri( day.timeStart, day.timeEnd); // Setup views day.rootView = (ViewGroup) inflater.inflate(R.layout.blocks_content, null); day.scrollView = (ObservableScrollView) day.rootView.findViewById(R.id.blocks_scroll); day.scrollView.setOnScrollListener(this); day.blocksView = (BlocksLayout) day.rootView.findViewById(R.id.blocks); day.nowView = day.rootView.findViewById(R.id.blocks_now); day.blocksView.setDrawingCacheEnabled(true); day.blocksView.setAlwaysDrawnWithCacheEnabled(true); TimeZone.setDefault(UIUtils.CONFERENCE_TIME_ZONE); day.label = DateUtils.formatDateTime(getActivity(), startMillis, TIME_FLAGS); mWorkspace.addView(day.rootView); mDays.add(day); } @Override public void onResume() { super.onResume(); // Since we build our views manually instead of using an adapter, we // need to manually requery every time launched. requery(); getActivity().getContentResolver().registerContentObserver( ScheduleContract.Sessions.CONTENT_URI, true, mSessionChangesObserver); // Start listening for time updates to adjust "now" bar. TIME_TICK is // triggered once per minute, which is how we move the bar over time. final IntentFilter filter = new IntentFilter(); filter.addAction(Intent.ACTION_TIME_TICK); filter.addAction(Intent.ACTION_TIME_CHANGED); filter.addAction(Intent.ACTION_TIMEZONE_CHANGED); getActivity().registerReceiver(mReceiver, filter, null, new Handler()); } private void requery() { for (Day day : mDays) { mHandler.startQuery(0, day, day.blocksUri, BlocksQuery.PROJECTION, null, null, ScheduleContract.Blocks.DEFAULT_SORT); } } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); getActivity().runOnUiThread(new Runnable() { public void run() { updateNowView(true); } }); } @Override public void onPause() { super.onPause(); getActivity().unregisterReceiver(mReceiver); getActivity().getContentResolver().unregisterContentObserver(mSessionChangesObserver); } /** * {@inheritDoc} */ public void onQueryComplete(int token, Object cookie, Cursor cursor) { if (getActivity() == null) { return; } Day day = (Day) cookie; // Clear out any existing sessions before inserting again day.blocksView.removeAllBlocks(); try { while (cursor.moveToNext()) { final String type = cursor.getString(BlocksQuery.BLOCK_TYPE); final Integer column = sTypeColumnMap.get(type); // TODO: place random blocks at bottom of entire layout if (column == null) { continue; } final String blockId = cursor.getString(BlocksQuery.BLOCK_ID); final String title = cursor.getString(BlocksQuery.BLOCK_TITLE); final long start = cursor.getLong(BlocksQuery.BLOCK_START); final long end = cursor.getLong(BlocksQuery.BLOCK_END); final boolean containsStarred = cursor.getInt(BlocksQuery.CONTAINS_STARRED) != 0; final BlockView blockView = new BlockView(getActivity(), blockId, title, start, end, containsStarred, column); final int sessionsCount = cursor.getInt(BlocksQuery.SESSIONS_COUNT); if (sessionsCount > 0) { blockView.setOnClickListener(this); } else { blockView.setFocusable(false); blockView.setEnabled(false); LayerDrawable buttonDrawable = (LayerDrawable) blockView.getBackground(); buttonDrawable.getDrawable(0).setAlpha(DISABLED_BLOCK_ALPHA); buttonDrawable.getDrawable(2).setAlpha(DISABLED_BLOCK_ALPHA); } day.blocksView.addBlock(blockView); } } finally { cursor.close(); } } /** {@inheritDoc} */ public void onClick(View view) { if (view instanceof BlockView) { String title = ((BlockView)view).getText().toString(); AnalyticsUtils.getInstance(getActivity()).trackEvent( "Schedule", "Session Click", title, 0); final String blockId = ((BlockView) view).getBlockId(); final Uri sessionsUri = ScheduleContract.Blocks.buildSessionsUri(blockId); final Intent intent = new Intent(Intent.ACTION_VIEW, sessionsUri); intent.putExtra(SessionsFragment.EXTRA_SCHEDULE_TIME_STRING, ((BlockView) view).getBlockTimeString()); ((BaseActivity) getActivity()).openActivityOrFragment(intent); } } /** * Update position and visibility of "now" view. */ private boolean updateNowView(boolean forceScroll) { final long now = UIUtils.getCurrentTime(getActivity()); Day nowDay = null; // effectively Day corresponding to today for (Day day : mDays) { if (now >= day.timeStart && now <= day.timeEnd) { nowDay = day; day.nowView.setVisibility(View.VISIBLE); } else { day.nowView.setVisibility(View.GONE); } } if (nowDay != null && forceScroll) { // Scroll to show "now" in center mWorkspace.setCurrentScreen(nowDay.index); final int offset = nowDay.scrollView.getHeight() / 2; nowDay.nowView.requestRectangleOnScreen(new Rect(0, offset, 0, offset), true); nowDay.blocksView.requestLayout(); return true; } return false; } public void onScrollChanged(ObservableScrollView view) { // Keep each day view at the same vertical scroll offset. final int scrollY = view.getScrollY(); for (Day day : mDays) { if (day.scrollView != view) { day.scrollView.scrollTo(0, scrollY); } } } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { inflater.inflate(R.menu.schedule_menu_items, menu); super.onCreateOptionsMenu(menu, inflater); } @Override public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == R.id.menu_now) { if (!updateNowView(true)) { Toast.makeText(getActivity(), R.string.toast_now_not_visible, Toast.LENGTH_SHORT).show(); } return true; } return super.onOptionsItemSelected(item); } private ContentObserver mSessionChangesObserver = new ContentObserver(new Handler()) { @Override public void onChange(boolean selfChange) { requery(); } }; private BroadcastReceiver mReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { Log.d(TAG, "onReceive time update"); updateNowView(false); } }; private interface BlocksQuery { String[] PROJECTION = { BaseColumns._ID, ScheduleContract.Blocks.BLOCK_ID, ScheduleContract.Blocks.BLOCK_TITLE, ScheduleContract.Blocks.BLOCK_START, ScheduleContract.Blocks.BLOCK_END, ScheduleContract.Blocks.BLOCK_TYPE, ScheduleContract.Blocks.SESSIONS_COUNT, ScheduleContract.Blocks.CONTAINS_STARRED, }; int _ID = 0; int BLOCK_ID = 1; int BLOCK_TITLE = 2; int BLOCK_START = 3; int BLOCK_END = 4; int BLOCK_TYPE = 5; int SESSIONS_COUNT = 6; int CONTAINS_STARRED = 7; } }
Java
/* * Copyright 2011 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.google.android.apps.iosched.ui; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.util.AnalyticsUtils; import com.google.android.apps.iosched.util.NotifyingAsyncQueryHandler; import android.content.Intent; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.support.v4.app.ListFragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ListView; /** * A simple {@link ListFragment} that renders a list of tracks with available sessions or vendors * (depending on {@link TracksFragment#EXTRA_NEXT_TYPE}) using a {@link TracksAdapter}. */ public class TracksFragment extends ListFragment implements NotifyingAsyncQueryHandler.AsyncQueryListener { public static final String EXTRA_NEXT_TYPE = "com.google.android.iosched.extra.NEXT_TYPE"; public static final String NEXT_TYPE_SESSIONS = "sessions"; public static final String NEXT_TYPE_VENDORS = "vendors"; private TracksAdapter mAdapter; private NotifyingAsyncQueryHandler mHandler; private String mNextType; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); final Intent intent = BaseActivity.fragmentArgumentsToIntent(getArguments()); final Uri tracksUri = intent.getData(); mNextType = intent.getStringExtra(EXTRA_NEXT_TYPE); mAdapter = new TracksAdapter(getActivity()); setListAdapter(mAdapter); // Filter our tracks query to only include those with valid results String[] projection = TracksAdapter.TracksQuery.PROJECTION; String selection = null; if (NEXT_TYPE_SESSIONS.equals(mNextType)) { // Only show tracks with at least one session projection = TracksAdapter.TracksQuery.PROJECTION_WITH_SESSIONS_COUNT; selection = ScheduleContract.Tracks.SESSIONS_COUNT + ">0"; AnalyticsUtils.getInstance(getActivity()).trackPageView("/Tracks"); } else if (NEXT_TYPE_VENDORS.equals(mNextType)) { // Only show tracks with at least one vendor projection = TracksAdapter.TracksQuery.PROJECTION_WITH_VENDORS_COUNT; selection = ScheduleContract.Tracks.VENDORS_COUNT + ">0"; AnalyticsUtils.getInstance(getActivity()).trackPageView("/Sandbox"); } // Start background query to load tracks mHandler = new NotifyingAsyncQueryHandler(getActivity().getContentResolver(), this); mHandler.startQuery(tracksUri, projection, selection, null, ScheduleContract.Tracks.DEFAULT_SORT); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { ViewGroup root = (ViewGroup) inflater.inflate(R.layout.fragment_list_with_spinner, null); // For some reason, if we omit this, NoSaveStateFrameLayout thinks we are // FILL_PARENT / WRAP_CONTENT, making the progress bar stick to the top of the activity. root.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT)); return root; } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE); } /** {@inheritDoc} */ public void onQueryComplete(int token, Object cookie, Cursor cursor) { if (getActivity() == null) { return; } getActivity().startManagingCursor(cursor); mAdapter.setHasAllItem(true); mAdapter.setIsSessions(TracksFragment.NEXT_TYPE_SESSIONS.equals(mNextType)); mAdapter.changeCursor(cursor); } /** {@inheritDoc} */ @Override public void onListItemClick(ListView l, View v, int position, long id) { final Cursor cursor = (Cursor) mAdapter.getItem(position); final String trackId; if (cursor != null) { trackId = cursor.getString(TracksAdapter.TracksQuery.TRACK_ID); } else { trackId = ScheduleContract.Tracks.ALL_TRACK_ID; } final Intent intent = new Intent(Intent.ACTION_VIEW); final Uri trackUri = ScheduleContract.Tracks.buildTrackUri(trackId); intent.putExtra(SessionDetailFragment.EXTRA_TRACK, trackUri); if (NEXT_TYPE_SESSIONS.equals(mNextType)) { if (cursor == null) { intent.setData(ScheduleContract.Sessions.CONTENT_URI); } else { intent.setData(ScheduleContract.Tracks.buildSessionsUri(trackId)); } } else if (NEXT_TYPE_VENDORS.equals(mNextType)) { if (cursor == null) { intent.setData(ScheduleContract.Vendors.CONTENT_URI); } else { intent.setData(ScheduleContract.Tracks.buildVendorsUri(trackId)); } } ((BaseActivity) getActivity()).openActivityOrFragment(intent); getListView().setItemChecked(position, true); } }
Java
/* * Copyright 2011 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.google.android.apps.iosched.ui; import com.google.android.apps.iosched.util.ActivityHelper; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.support.v4.app.FragmentActivity; import android.view.KeyEvent; import android.view.Menu; import android.view.MenuItem; /** * A base activity that defers common functionality across app activities to an * {@link ActivityHelper}. This class shouldn't be used directly; instead, activities should * inherit from {@link BaseSinglePaneActivity} or {@link BaseMultiPaneActivity}. */ public abstract class BaseActivity extends FragmentActivity { final ActivityHelper mActivityHelper = ActivityHelper.createInstance(this); @Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); mActivityHelper.onPostCreate(savedInstanceState); } @Override public boolean onKeyLongPress(int keyCode, KeyEvent event) { return mActivityHelper.onKeyLongPress(keyCode, event) || super.onKeyLongPress(keyCode, event); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { return mActivityHelper.onKeyDown(keyCode, event) || super.onKeyDown(keyCode, event); } @Override public boolean onCreateOptionsMenu(Menu menu) { return mActivityHelper.onCreateOptionsMenu(menu) || super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { return mActivityHelper.onOptionsItemSelected(item) || super.onOptionsItemSelected(item); } /** * Returns the {@link ActivityHelper} object associated with this activity. */ protected ActivityHelper getActivityHelper() { return mActivityHelper; } /** * Takes a given intent and either starts a new activity to handle it (the default behavior), * or creates/updates a fragment (in the case of a multi-pane activity) that can handle the * intent. * * Must be called from the main (UI) thread. */ public void openActivityOrFragment(Intent intent) { // Default implementation simply calls startActivity startActivity(intent); } /** * Converts an intent into a {@link Bundle} suitable for use as fragment arguments. */ public static Bundle intentToFragmentArguments(Intent intent) { Bundle arguments = new Bundle(); if (intent == null) { return arguments; } final Uri data = intent.getData(); if (data != null) { arguments.putParcelable("_uri", data); } final Bundle extras = intent.getExtras(); if (extras != null) { arguments.putAll(intent.getExtras()); } return arguments; } /** * Converts a fragment arguments bundle into an intent. */ public static Intent fragmentArgumentsToIntent(Bundle arguments) { Intent intent = new Intent(); if (arguments == null) { return intent; } final Uri data = arguments.getParcelable("_uri"); if (data != null) { intent.setData(data); } intent.putExtras(arguments); intent.removeExtra("_uri"); return intent; } }
Java
/* * Copyright 2011 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.google.android.apps.iosched.ui; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.ui.tablet.NowPlayingMultiPaneActivity; import com.google.android.apps.iosched.util.AnalyticsUtils; import com.google.android.apps.iosched.util.UIUtils; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.support.v4.app.Fragment; import android.text.format.DateUtils; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; /** * A fragment used in {@link HomeActivity} that shows either a countdown, 'now playing' link to * current sessions, or 'thank you' text, at different times (before/during/after the conference). * It also shows a 'Realtime Search' button on phones, as a replacement for the * {@link TagStreamFragment} that is visible on tablets on the home screen. */ public class WhatsOnFragment extends Fragment { private Handler mMessageHandler = new Handler(); private TextView mCountdownTextView; private ViewGroup mRootView; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { mRootView = (ViewGroup) inflater.inflate(R.layout.fragment_whats_on, container); refresh(); return mRootView; } @Override public void onAttach(Activity activity) { super.onAttach(activity); } @Override public void onDetach() { super.onDetach(); mMessageHandler.removeCallbacks(mCountdownRunnable); } private void refresh() { mMessageHandler.removeCallbacks(mCountdownRunnable); mRootView.removeAllViews(); final long currentTimeMillis = UIUtils.getCurrentTime(getActivity()); // Show Loading... and load the view corresponding to the current state if (currentTimeMillis < UIUtils.CONFERENCE_START_MILLIS) { setupBefore(); } else if (currentTimeMillis > UIUtils.CONFERENCE_END_MILLIS) { setupAfter(); } else { setupDuring(); } if (!UIUtils.isHoneycombTablet(getActivity())) { View separator = new View(getActivity()); separator.setLayoutParams( new ViewGroup.LayoutParams(1, ViewGroup.LayoutParams.FILL_PARENT)); separator.setBackgroundResource(R.drawable.whats_on_separator); mRootView.addView(separator); View view = getActivity().getLayoutInflater().inflate( R.layout.whats_on_stream, mRootView, false); view.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { AnalyticsUtils.getInstance(getActivity()).trackEvent( "Home Screen Dashboard", "Click", "Realtime Stream", 0); Intent intent = new Intent(getActivity(), TagStreamActivity.class); startActivity(intent); } }); mRootView.addView(view); } } private void setupBefore() { // Before conference, show countdown. mCountdownTextView = (TextView) getActivity().getLayoutInflater().inflate( R.layout.whats_on_countdown, mRootView, false); mRootView.addView(mCountdownTextView); mMessageHandler.post(mCountdownRunnable); } private void setupAfter() { // After conference, show canned text. getActivity().getLayoutInflater().inflate( R.layout.whats_on_thank_you, mRootView, true); } private void setupDuring() { // Conference in progress, show "Now Playing" link. View view = getActivity().getLayoutInflater().inflate( R.layout.whats_on_now_playing, mRootView, false); view.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { if (UIUtils.isHoneycombTablet(getActivity())) { startActivity(new Intent(getActivity(), NowPlayingMultiPaneActivity.class)); } else { Intent intent = new Intent(Intent.ACTION_VIEW); intent.setData(ScheduleContract.Sessions .buildSessionsAtDirUri(System.currentTimeMillis())); intent.putExtra(Intent.EXTRA_TITLE, getString(R.string.title_now_playing)); startActivity(intent); } } }); mRootView.addView(view); } /** * Event that updates countdown timer. Posts itself again to {@link #mMessageHandler} to * continue updating time. */ private Runnable mCountdownRunnable = new Runnable() { public void run() { int remainingSec = (int) Math.max(0, (UIUtils.CONFERENCE_START_MILLIS - System.currentTimeMillis()) / 1000); final boolean conferenceStarted = remainingSec == 0; if (conferenceStarted) { // Conference started while in countdown mode, switch modes and // bail on future countdown updates. mMessageHandler.postDelayed(new Runnable() { public void run() { refresh(); } }, 100); return; } final int secs = remainingSec % 86400; final int days = remainingSec / 86400; final String str = getResources().getQuantityString( R.plurals.whats_on_countdown_title, days, days, DateUtils.formatElapsedTime(secs)); mCountdownTextView.setText(str); // Repost ourselves to keep updating countdown mMessageHandler.postDelayed(mCountdownRunnable, 1000); } }; }
Java
/* * Copyright 2011 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.google.android.apps.iosched.ui.phone; import com.google.android.apps.iosched.ui.BaseSinglePaneActivity; import com.google.android.apps.iosched.ui.SessionsFragment; import android.os.Bundle; import android.support.v4.app.Fragment; public class SessionsActivity extends BaseSinglePaneActivity { @Override protected Fragment onCreatePane() { return new SessionsFragment(); } @Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); getActivityHelper().setupSubActivity(); } }
Java
/* * Copyright 2011 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.google.android.apps.iosched.ui.phone; import com.google.android.apps.iosched.ui.BaseSinglePaneActivity; import com.google.android.apps.iosched.ui.MapFragment; import android.os.Bundle; import android.support.v4.app.Fragment; public class MapActivity extends BaseSinglePaneActivity { @Override protected Fragment onCreatePane() { return new MapFragment(); } @Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); getActivityHelper().setupSubActivity(); } }
Java
/* * Copyright 2011 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.google.android.apps.iosched.ui.phone; import com.google.android.apps.iosched.ui.BaseSinglePaneActivity; import com.google.android.apps.iosched.ui.VendorDetailFragment; import android.os.Bundle; import android.support.v4.app.Fragment; public class VendorDetailActivity extends BaseSinglePaneActivity { @Override protected Fragment onCreatePane() { return new VendorDetailFragment(); } @Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); getActivityHelper().setupSubActivity(); } }
Java
/* * Copyright 2011 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.google.android.apps.iosched.ui.phone; import com.google.android.apps.iosched.ui.BaseSinglePaneActivity; import com.google.android.apps.iosched.ui.SessionDetailFragment; import android.os.Bundle; import android.support.v4.app.Fragment; public class SessionDetailActivity extends BaseSinglePaneActivity { @Override protected Fragment onCreatePane() { return new SessionDetailFragment(); } @Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); getActivityHelper().setupSubActivity(); } }
Java
/* * Copyright 2011 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.google.android.apps.iosched.ui.phone; import com.google.android.apps.iosched.ui.BaseSinglePaneActivity; import com.google.android.apps.iosched.ui.TracksFragment; import android.os.Bundle; import android.support.v4.app.Fragment; public class TracksActivity extends BaseSinglePaneActivity { @Override protected Fragment onCreatePane() { return new TracksFragment(); } @Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); getActivityHelper().setupSubActivity(); } }
Java
/* * Copyright 2011 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.google.android.apps.iosched.ui.phone; import com.google.android.apps.iosched.ui.BaseSinglePaneActivity; import com.google.android.apps.iosched.ui.VendorsFragment; import android.os.Bundle; import android.support.v4.app.Fragment; public class VendorsActivity extends BaseSinglePaneActivity { @Override protected Fragment onCreatePane() { return new VendorsFragment(); } @Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); getActivityHelper().setupSubActivity(); } }
Java
/* * Copyright 2011 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.google.android.apps.iosched.ui.phone; import com.google.android.apps.iosched.ui.BaseSinglePaneActivity; import com.google.android.apps.iosched.ui.ScheduleFragment; import android.os.Bundle; import android.support.v4.app.Fragment; public class ScheduleActivity extends BaseSinglePaneActivity { @Override protected Fragment onCreatePane() { return new ScheduleFragment(); } @Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); getActivityHelper().setupSubActivity(); } }
Java
/* * Copyright 2011 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.google.android.apps.iosched.ui.tablet; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.ui.BaseMultiPaneActivity; import com.google.android.apps.iosched.ui.SessionDetailFragment; import com.google.android.apps.iosched.ui.SessionsFragment; import com.google.android.apps.iosched.ui.phone.SessionDetailActivity; import com.google.android.apps.iosched.ui.phone.SessionsActivity; import android.app.FragmentBreadCrumbs; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.view.View; import android.view.ViewGroup; /** * A multi-pane activity, where the primary navigation pane is a * {@link com.google.android.apps.iosched.ui.ScheduleFragment}, that * shows {@link SessionsFragment} and {@link SessionDetailFragment} as popups. * * This activity requires API level 11 or greater because of its use of {@link FragmentBreadCrumbs}. */ public class ScheduleMultiPaneActivity extends BaseMultiPaneActivity implements View.OnClickListener, FragmentManager.OnBackStackChangedListener { private FragmentManager mFragmentManager; private FragmentBreadCrumbs mFragmentBreadCrumbs; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_schedule); mFragmentManager = getSupportFragmentManager(); mFragmentBreadCrumbs = (FragmentBreadCrumbs) findViewById(R.id.breadcrumbs); mFragmentBreadCrumbs.setActivity(this); mFragmentManager.addOnBackStackChangedListener(this); updateBreadCrumb(); } @Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); getActivityHelper().setupSubActivity(); ViewGroup detailContainer = (ViewGroup) findViewById(R.id.fragment_container_schedule_detail); if (detailContainer != null && detailContainer.getChildCount() > 0) { findViewById(R.id.fragment_container_schedule_detail).setBackgroundColor(0); } } @Override public FragmentReplaceInfo onSubstituteFragmentForActivityLaunch(String activityClassName) { if (SessionsActivity.class.getName().equals(activityClassName)) { getSupportFragmentManager().popBackStack(); findViewById(R.id.fragment_container_schedule_detail).setBackgroundColor(0); return new FragmentReplaceInfo( SessionsFragment.class, "sessions", R.id.fragment_container_schedule_detail); } else if (SessionDetailActivity.class.getName().equals(activityClassName)) { findViewById(R.id.fragment_container_schedule_detail).setBackgroundColor(0); return new FragmentReplaceInfo( SessionDetailFragment.class, "session_detail", R.id.fragment_container_schedule_detail); } return null; } @Override protected void onBeforeCommitReplaceFragment(FragmentManager fm, FragmentTransaction ft, Fragment fragment) { super.onBeforeCommitReplaceFragment(fm, ft, fragment); if (fragment instanceof SessionDetailFragment) { ft.addToBackStack(null); } else if (fragment instanceof SessionsFragment) { fm.popBackStack(); } updateBreadCrumb(); } /** * Handler for the breadcrumb parent. */ public void onClick(View view) { mFragmentManager.popBackStack(); } public void onBackStackChanged() { updateBreadCrumb(); } public void updateBreadCrumb() { final String title = getString(R.string.title_sessions); final String detailTitle = getString(R.string.title_session_detail); if (mFragmentManager.getBackStackEntryCount() >= 1) { mFragmentBreadCrumbs.setParentTitle(title, title, this); mFragmentBreadCrumbs.setTitle(detailTitle, detailTitle); } else { mFragmentBreadCrumbs.setParentTitle(null, null, null); mFragmentBreadCrumbs.setTitle(title, title); } } }
Java
/* * Copyright 2011 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.google.android.apps.iosched.ui.tablet; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.ui.BaseMultiPaneActivity; import com.google.android.apps.iosched.ui.TracksFragment; import com.google.android.apps.iosched.ui.VendorDetailFragment; import com.google.android.apps.iosched.ui.VendorsFragment; import com.google.android.apps.iosched.ui.phone.VendorDetailActivity; import com.google.android.apps.iosched.ui.phone.VendorsActivity; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.FragmentManager; import android.view.ViewGroup; /** * A multi-pane activity, consisting of a {@link TracksDropdownFragment}, a * {@link VendorsFragment}, and {@link VendorDetailFragment}. This activity is very similar in * function to {@link SessionsMultiPaneActivity}. * * This activity requires API level 11 or greater because {@link TracksDropdownFragment} requires * API level 11. */ public class VendorsMultiPaneActivity extends BaseMultiPaneActivity { private TracksDropdownFragment mTracksDropdownFragment; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView( R.layout.activity_vendors); Intent intent = new Intent(); intent.setData(ScheduleContract.Tracks.CONTENT_URI); intent.putExtra(TracksFragment.EXTRA_NEXT_TYPE, TracksFragment.NEXT_TYPE_VENDORS); final FragmentManager fm = getSupportFragmentManager(); mTracksDropdownFragment = (TracksDropdownFragment) fm.findFragmentById( R.id.fragment_tracks_dropdown); mTracksDropdownFragment.reloadFromArguments(intentToFragmentArguments(intent)); } @Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); getActivityHelper().setupSubActivity(); ViewGroup detailContainer = (ViewGroup) findViewById(R.id.fragment_container_vendor_detail); if (detailContainer != null && detailContainer.getChildCount() > 0) { findViewById(R.id.fragment_container_vendor_detail).setBackgroundColor(0xffffffff); } } @Override public FragmentReplaceInfo onSubstituteFragmentForActivityLaunch(String activityClassName) { if (VendorsActivity.class.getName().equals(activityClassName)) { return new FragmentReplaceInfo( VendorsFragment.class, "vendors", R.id.fragment_container_vendors); } else if (VendorDetailActivity.class.getName().equals(activityClassName)) { findViewById(R.id.fragment_container_vendor_detail).setBackgroundColor( 0xffffffff); return new FragmentReplaceInfo( VendorDetailFragment.class, "vendor_detail", R.id.fragment_container_vendor_detail); } return null; } }
Java
/* * Copyright 2011 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.google.android.apps.iosched.ui.tablet; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.ui.BaseActivity; import com.google.android.apps.iosched.ui.SessionDetailFragment; import com.google.android.apps.iosched.ui.TracksAdapter; import com.google.android.apps.iosched.ui.TracksFragment; import com.google.android.apps.iosched.util.NotifyingAsyncQueryHandler; import com.google.android.apps.iosched.util.UIUtils; import android.content.Intent; import android.content.res.Resources; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ListPopupWindow; import android.widget.PopupWindow; import android.widget.TextView; /** * A tablet-specific fragment that is a giant {@link android.widget.Spinner}-like widget. It shows * a {@link ListPopupWindow} containing a list of tracks, using {@link TracksAdapter}. * * Requires API level 11 or later since {@link ListPopupWindow} is API level 11+. */ public class TracksDropdownFragment extends Fragment implements NotifyingAsyncQueryHandler.AsyncQueryListener, AdapterView.OnItemClickListener, PopupWindow.OnDismissListener { public static final String EXTRA_NEXT_TYPE = "com.google.android.iosched.extra.NEXT_TYPE"; public static final String NEXT_TYPE_SESSIONS = "sessions"; public static final String NEXT_TYPE_VENDORS = "vendors"; private boolean mAutoloadTarget = true; private Cursor mCursor; private TracksAdapter mAdapter; private String mNextType; private ListPopupWindow mListPopupWindow; private ViewGroup mRootView; private TextView mTitle; private TextView mAbstract; private NotifyingAsyncQueryHandler mHandler; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mHandler = new NotifyingAsyncQueryHandler(getActivity().getContentResolver(), this); mAdapter = new TracksAdapter(getActivity()); if (savedInstanceState != null) { // Prevent auto-load behavior on orientation change. mAutoloadTarget = false; } reloadFromArguments(getArguments()); } public void reloadFromArguments(Bundle arguments) { // Teardown from previous arguments if (mListPopupWindow != null) { mListPopupWindow.setAdapter(null); } if (mCursor != null) { getActivity().stopManagingCursor(mCursor); mCursor = null; } mHandler.cancelOperation(TracksAdapter.TracksQuery._TOKEN); // Load new arguments final Intent intent = BaseActivity.fragmentArgumentsToIntent(arguments); final Uri tracksUri = intent.getData(); if (tracksUri == null) { return; } mNextType = intent.getStringExtra(EXTRA_NEXT_TYPE); // Filter our tracks query to only include those with valid results String[] projection = TracksAdapter.TracksQuery.PROJECTION; String selection = null; if (TracksFragment.NEXT_TYPE_SESSIONS.equals(mNextType)) { // Only show tracks with at least one session projection = TracksAdapter.TracksQuery.PROJECTION_WITH_SESSIONS_COUNT; selection = ScheduleContract.Tracks.SESSIONS_COUNT + ">0"; } else if (TracksFragment.NEXT_TYPE_VENDORS.equals(mNextType)) { // Only show tracks with at least one vendor projection = TracksAdapter.TracksQuery.PROJECTION_WITH_VENDORS_COUNT; selection = ScheduleContract.Tracks.VENDORS_COUNT + ">0"; } // Start background query to load tracks mHandler.startQuery(TracksAdapter.TracksQuery._TOKEN, null, tracksUri, projection, selection, null, ScheduleContract.Tracks.DEFAULT_SORT); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { mRootView = (ViewGroup) inflater.inflate(R.layout.fragment_tracks_dropdown, null); mTitle = (TextView) mRootView.findViewById(R.id.track_title); mAbstract = (TextView) mRootView.findViewById(R.id.track_abstract); mRootView.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { mListPopupWindow = new ListPopupWindow(getActivity()); mListPopupWindow.setAdapter(mAdapter); mListPopupWindow.setModal(true); mListPopupWindow.setContentWidth(400); mListPopupWindow.setAnchorView(mRootView); mListPopupWindow.setOnItemClickListener(TracksDropdownFragment.this); mListPopupWindow.show(); mListPopupWindow.setOnDismissListener(TracksDropdownFragment.this); } }); return mRootView; } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); } /** {@inheritDoc} */ public void onQueryComplete(int token, Object cookie, Cursor cursor) { if (getActivity() == null || cursor == null) { return; } mCursor = cursor; getActivity().startManagingCursor(mCursor); // If there was a last-opened track, load it. Otherwise load the first track. cursor.moveToFirst(); String lastTrackID = UIUtils.getLastUsedTrackID(getActivity()); if (lastTrackID != null) { while (!cursor.isAfterLast()) { if (lastTrackID.equals(cursor.getString(TracksAdapter.TracksQuery.TRACK_ID))) { break; } cursor.moveToNext(); } if (cursor.isAfterLast()) { loadTrack(null, mAutoloadTarget); } else { loadTrack(cursor, mAutoloadTarget); } } else { loadTrack(null, mAutoloadTarget); } mAdapter.setHasAllItem(true); mAdapter.setIsSessions(TracksFragment.NEXT_TYPE_SESSIONS.equals(mNextType)); mAdapter.changeCursor(mCursor); } /** {@inheritDoc} */ public void onItemClick(AdapterView<?> parent, View view, int position, long id) { final Cursor cursor = (Cursor) mAdapter.getItem(position); loadTrack(cursor, true); if (cursor != null) { UIUtils.setLastUsedTrackID(getActivity(), cursor.getString( TracksAdapter.TracksQuery.TRACK_ID)); } else { UIUtils.setLastUsedTrackID(getActivity(), ScheduleContract.Tracks.ALL_TRACK_ID); } if (mListPopupWindow != null) { mListPopupWindow.dismiss(); } } public void loadTrack(Cursor cursor, boolean loadTargetFragment) { final String trackId; final int trackColor; final Resources res = getResources(); if (cursor != null) { trackColor = cursor.getInt(TracksAdapter.TracksQuery.TRACK_COLOR); trackId = cursor.getString(TracksAdapter.TracksQuery.TRACK_ID); mTitle.setText(cursor.getString(TracksAdapter.TracksQuery.TRACK_NAME)); mAbstract.setText(cursor.getString(TracksAdapter.TracksQuery.TRACK_ABSTRACT)); } else { trackColor = res.getColor(R.color.all_track_color); trackId = ScheduleContract.Tracks.ALL_TRACK_ID; mTitle.setText(TracksFragment.NEXT_TYPE_SESSIONS.equals(mNextType) ? R.string.all_sessions_title : R.string.all_sandbox_title); mAbstract.setText(TracksFragment.NEXT_TYPE_SESSIONS.equals(mNextType) ? R.string.all_sessions_subtitle : R.string.all_sandbox_subtitle); } boolean isDark = UIUtils.isColorDark(trackColor); mRootView.setBackgroundColor(trackColor); if (isDark) { mTitle.setTextColor(res.getColor(R.color.body_text_1_inverse)); mAbstract.setTextColor(res.getColor(R.color.body_text_2_inverse)); mRootView.findViewById(R.id.track_dropdown_arrow).setBackgroundResource( R.drawable.track_dropdown_arrow_light); } else { mTitle.setTextColor(res.getColor(R.color.body_text_1)); mAbstract.setTextColor(res.getColor(R.color.body_text_2)); mRootView.findViewById(R.id.track_dropdown_arrow).setBackgroundResource( R.drawable.track_dropdown_arrow_dark); } if (loadTargetFragment) { final Intent intent = new Intent(Intent.ACTION_VIEW); final Uri trackUri = ScheduleContract.Tracks.buildTrackUri(trackId); intent.putExtra(SessionDetailFragment.EXTRA_TRACK, trackUri); if (NEXT_TYPE_SESSIONS.equals(mNextType)) { if (cursor == null) { intent.setData(ScheduleContract.Sessions.CONTENT_URI); } else { intent.setData(ScheduleContract.Tracks.buildSessionsUri(trackId)); } } else if (NEXT_TYPE_VENDORS.equals(mNextType)) { if (cursor == null) { intent.setData(ScheduleContract.Vendors.CONTENT_URI); } else { intent.setData(ScheduleContract.Tracks.buildVendorsUri(trackId)); } } ((BaseActivity) getActivity()).openActivityOrFragment(intent); } } public void onDismiss() { mListPopupWindow = null; } }
Java
/* * Copyright 2011 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.google.android.apps.iosched.ui.tablet; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.ui.BaseMultiPaneActivity; import com.google.android.apps.iosched.ui.SessionDetailFragment; import com.google.android.apps.iosched.ui.SessionsFragment; import com.google.android.apps.iosched.ui.TracksFragment; import com.google.android.apps.iosched.ui.phone.SessionDetailActivity; import com.google.android.apps.iosched.ui.phone.SessionsActivity; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.FragmentManager; import android.view.ViewGroup; /** * A multi-pane activity, consisting of a {@link TracksDropdownFragment}, a * {@link SessionsFragment}, and {@link SessionDetailFragment}. * * This activity requires API level 11 or greater because {@link TracksDropdownFragment} requires * API level 11. */ public class SessionsMultiPaneActivity extends BaseMultiPaneActivity { private TracksDropdownFragment mTracksDropdownFragment; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_sessions); Intent intent = new Intent(); intent.setData(ScheduleContract.Tracks.CONTENT_URI); intent.putExtra(TracksFragment.EXTRA_NEXT_TYPE, TracksFragment.NEXT_TYPE_SESSIONS); final FragmentManager fm = getSupportFragmentManager(); mTracksDropdownFragment = (TracksDropdownFragment) fm.findFragmentById( R.id.fragment_tracks_dropdown); mTracksDropdownFragment.reloadFromArguments(intentToFragmentArguments(intent)); } @Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); getActivityHelper().setupSubActivity(); ViewGroup detailContainer = (ViewGroup) findViewById(R.id.fragment_container_session_detail); if (detailContainer != null && detailContainer.getChildCount() > 0) { findViewById(R.id.fragment_container_session_detail).setBackgroundColor(0xffffffff); } } @Override public FragmentReplaceInfo onSubstituteFragmentForActivityLaunch(String activityClassName) { if (SessionsActivity.class.getName().equals(activityClassName)) { return new FragmentReplaceInfo( SessionsFragment.class, "sessions", R.id.fragment_container_sessions); } else if (SessionDetailActivity.class.getName().equals(activityClassName)) { findViewById(R.id.fragment_container_session_detail).setBackgroundColor( 0xffffffff); return new FragmentReplaceInfo( SessionDetailFragment.class, "session_detail", R.id.fragment_container_session_detail); } return null; } }
Java
/* * Copyright 2011 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.google.android.apps.iosched.ui.tablet; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.ui.BaseMultiPaneActivity; import com.google.android.apps.iosched.ui.MapFragment; import com.google.android.apps.iosched.ui.SessionDetailFragment; import com.google.android.apps.iosched.ui.SessionsFragment; import com.google.android.apps.iosched.ui.VendorDetailFragment; import com.google.android.apps.iosched.ui.VendorsFragment; import com.google.android.apps.iosched.ui.phone.SessionDetailActivity; import com.google.android.apps.iosched.ui.phone.SessionsActivity; import com.google.android.apps.iosched.ui.phone.VendorDetailActivity; import com.google.android.apps.iosched.ui.phone.VendorsActivity; import android.app.FragmentBreadCrumbs; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.view.View; /** * A multi-pane activity, where the primary navigation pane is a {@link MapFragment}, that shows * {@link SessionsFragment}, {@link SessionDetailFragment}, {@link VendorsFragment}, and * {@link VendorDetailFragment} as popups. * * This activity requires API level 11 or greater because of its use of {@link FragmentBreadCrumbs}. */ public class MapMultiPaneActivity extends BaseMultiPaneActivity implements View.OnClickListener, FragmentManager.OnBackStackChangedListener { private static final int POPUP_TYPE_SESSIONS = 1; private static final int POPUP_TYPE_VENDORS = 2; private int mPopupType = -1; private boolean mPauseBackStackWatcher = false; private FragmentManager mFragmentManager; private FragmentBreadCrumbs mFragmentBreadCrumbs; private MapFragment mMapFragment; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_map); mFragmentManager = getSupportFragmentManager(); mFragmentManager.addOnBackStackChangedListener(this); mFragmentBreadCrumbs = (FragmentBreadCrumbs) findViewById(R.id.breadcrumbs); mFragmentBreadCrumbs.setActivity(this); mMapFragment = (MapFragment) mFragmentManager.findFragmentByTag("map"); if (mMapFragment == null) { mMapFragment = new MapFragment(); mMapFragment.setArguments(intentToFragmentArguments(getIntent())); mFragmentManager.beginTransaction() .add(R.id.fragment_container_map, mMapFragment, "map") .commit(); } findViewById(R.id.close_button).setOnClickListener(new View.OnClickListener() { public void onClick(View view) { clearBackStack(getSupportFragmentManager()); } }); updateBreadCrumb(); } @Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); getActivityHelper().setupSubActivity(); } @Override public FragmentReplaceInfo onSubstituteFragmentForActivityLaunch(String activityClassName) { if (SessionsActivity.class.getName().equals(activityClassName)) { clearBackStack(getSupportFragmentManager()); mPopupType = POPUP_TYPE_SESSIONS; showHideDetailAndPan(true); return new FragmentReplaceInfo( SessionsFragment.class, "sessions", R.id.fragment_container_map_detail); } else if (SessionDetailActivity.class.getName().equals(activityClassName)) { mPopupType = POPUP_TYPE_SESSIONS; showHideDetailAndPan(true); return new FragmentReplaceInfo( SessionDetailFragment.class, "session_detail", R.id.fragment_container_map_detail); } else if (VendorsActivity.class.getName().equals(activityClassName)) { clearBackStack(getSupportFragmentManager()); mPopupType = POPUP_TYPE_VENDORS; showHideDetailAndPan(true); return new FragmentReplaceInfo( VendorsFragment.class, "vendors", R.id.fragment_container_map_detail); } else if (VendorDetailActivity.class.getName().equals(activityClassName)) { mPopupType = POPUP_TYPE_VENDORS; showHideDetailAndPan(true); return new FragmentReplaceInfo( VendorDetailFragment.class, "vendor_detail", R.id.fragment_container_map_detail); } return null; } @Override protected void onBeforeCommitReplaceFragment(FragmentManager fm, FragmentTransaction ft, Fragment fragment) { super.onBeforeCommitReplaceFragment(fm, ft, fragment); if (fragment instanceof SessionsFragment || fragment instanceof VendorsFragment) { mPauseBackStackWatcher = true; clearBackStack(fm); mPauseBackStackWatcher = false; } ft.addToBackStack(null); updateBreadCrumb(); } /** * Handler for the breadcrumb parent. */ public void onClick(View view) { mFragmentManager.popBackStack(); } private void clearBackStack(FragmentManager fm) { while (fm.getBackStackEntryCount() > 0) { fm.popBackStackImmediate(); } } public void onBackStackChanged() { if (mPauseBackStackWatcher) { return; } if (mFragmentManager.getBackStackEntryCount() == 0) { showHideDetailAndPan(false); } updateBreadCrumb(); } private void showHideDetailAndPan(boolean show) { View detailPopup = findViewById(R.id.map_detail_popup); if (show != (detailPopup.getVisibility() == View.VISIBLE)) { detailPopup.setVisibility(show ? View.VISIBLE : View.GONE); mMapFragment.panLeft(show ? 0.25f : -0.25f); } } public void updateBreadCrumb() { final String title = (mPopupType == POPUP_TYPE_SESSIONS) ? getString(R.string.title_sessions) : getString(R.string.title_vendors); final String detailTitle = (mPopupType == POPUP_TYPE_SESSIONS) ? getString(R.string.title_session_detail) : getString(R.string.title_vendor_detail); if (mFragmentManager.getBackStackEntryCount() >= 2) { mFragmentBreadCrumbs.setParentTitle(title, title, this); mFragmentBreadCrumbs.setTitle(detailTitle, detailTitle); } else { mFragmentBreadCrumbs.setParentTitle(null, null, null); mFragmentBreadCrumbs.setTitle(title, title); } } }
Java
/* * Copyright 2011 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.google.android.apps.iosched.ui.tablet; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.provider.ScheduleContract.Sessions; import com.google.android.apps.iosched.ui.BaseMultiPaneActivity; import com.google.android.apps.iosched.ui.SessionDetailFragment; import com.google.android.apps.iosched.ui.SessionsFragment; import com.google.android.apps.iosched.ui.phone.SessionDetailActivity; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.FragmentManager; import android.view.View; import android.view.ViewGroup; /** * An activity that shows currently playing sessions in a two-pane view. */ public class NowPlayingMultiPaneActivity extends BaseMultiPaneActivity { private SessionsFragment mSessionsFragment; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Intent intent = new Intent(); intent.setData(Sessions.buildSessionsAtDirUri(System.currentTimeMillis())); setContentView(R.layout.activity_now_playing); final FragmentManager fm = getSupportFragmentManager(); mSessionsFragment = (SessionsFragment) fm.findFragmentByTag("sessions"); if (mSessionsFragment == null) { mSessionsFragment = new SessionsFragment(); mSessionsFragment.setArguments(intentToFragmentArguments(intent)); fm.beginTransaction() .add(R.id.fragment_container_sessions, mSessionsFragment, "sessions") .commit(); } } @Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); getActivityHelper().setupSubActivity(); ViewGroup detailContainer = (ViewGroup) findViewById( R.id.fragment_container_now_playing_detail); if (detailContainer != null && detailContainer.getChildCount() > 1) { findViewById(android.R.id.empty).setVisibility(View.GONE); } } @Override public FragmentReplaceInfo onSubstituteFragmentForActivityLaunch( String activityClassName) { findViewById(android.R.id.empty).setVisibility(View.GONE); if (SessionDetailActivity.class.getName().equals(activityClassName)) { clearSelectedItems(); return new FragmentReplaceInfo( SessionDetailFragment.class, "session_detail", R.id.fragment_container_now_playing_detail); } return null; } private void clearSelectedItems() { if (mSessionsFragment != null) { mSessionsFragment.clearCheckedPosition(); } } }
Java
/* * Copyright 2011 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.google.android.apps.iosched.ui; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.util.ActivityHelper; import com.google.android.apps.iosched.util.AnalyticsUtils; import com.google.android.apps.iosched.util.BitmapUtils; import com.google.android.apps.iosched.util.FractionalTouchDelegate; import com.google.android.apps.iosched.util.NotifyingAsyncQueryHandler; import com.google.android.apps.iosched.util.ParserUtils; import com.google.android.apps.iosched.util.UIUtils; import android.content.ContentValues; import android.content.Intent; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.RectF; import android.net.Uri; import android.os.Bundle; import android.support.v4.app.Fragment; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.CompoundButton; import android.widget.ImageView; import android.widget.TextView; /** * A fragment that shows detail information for a sandbox company, including company name, * description, product description, logo, etc. */ public class VendorDetailFragment extends Fragment implements NotifyingAsyncQueryHandler.AsyncQueryListener, CompoundButton.OnCheckedChangeListener { private static final String TAG = "VendorDetailFragment"; private Uri mVendorUri; private String mTrackId; private ViewGroup mRootView; private TextView mName; private CompoundButton mStarred; private ImageView mLogo; private TextView mUrl; private TextView mDesc; private TextView mProductDesc; private String mNameString; private NotifyingAsyncQueryHandler mHandler; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); final Intent intent = BaseActivity.fragmentArgumentsToIntent(getArguments()); mVendorUri = intent.getData(); if (mVendorUri== null) { return; } setHasOptionsMenu(true); } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); if (mVendorUri == null) { return; } // Start background query to load vendor details mHandler = new NotifyingAsyncQueryHandler(getActivity().getContentResolver(), this); mHandler.startQuery(mVendorUri, VendorsQuery.PROJECTION); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { mRootView = (ViewGroup) inflater.inflate(R.layout.fragment_vendor_detail, null); mName = (TextView) mRootView.findViewById(R.id.vendor_name); mStarred = (CompoundButton) mRootView.findViewById(R.id.star_button); mStarred.setFocusable(true); mStarred.setClickable(true); // Larger target triggers star toggle final View starParent = mRootView.findViewById(R.id.header_vendor); FractionalTouchDelegate.setupDelegate(starParent, mStarred, new RectF(0.6f, 0f, 1f, 0.8f)); mLogo = (ImageView) mRootView.findViewById(R.id.vendor_logo); mUrl = (TextView) mRootView.findViewById(R.id.vendor_url); mDesc = (TextView) mRootView.findViewById(R.id.vendor_desc); mProductDesc = (TextView) mRootView.findViewById(R.id.vendor_product_desc); return mRootView; } /** * Build a {@link android.view.View} to be used as a tab indicator, setting the requested string resource as * its label. * * @return View */ private View buildIndicator(int textRes) { final TextView indicator = (TextView) getActivity().getLayoutInflater() .inflate(R.layout.tab_indicator, (ViewGroup) mRootView.findViewById(android.R.id.tabs), false); indicator.setText(textRes); return indicator; } /** * {@inheritDoc} */ public void onQueryComplete(int token, Object cookie, Cursor cursor) { if (getActivity() == null) { return; } try { if (!cursor.moveToFirst()) { return; } mNameString = cursor.getString(VendorsQuery.NAME); mName.setText(mNameString); // Unregister around setting checked state to avoid triggering // listener since change isn't user generated. mStarred.setOnCheckedChangeListener(null); mStarred.setChecked(cursor.getInt(VendorsQuery.STARRED) != 0); mStarred.setOnCheckedChangeListener(this); // Start background fetch to load vendor logo final String logoUrl = cursor.getString(VendorsQuery.LOGO_URL); if (!TextUtils.isEmpty(logoUrl)) { BitmapUtils.fetchImage(getActivity(), logoUrl, null, null, new BitmapUtils.OnFetchCompleteListener() { public void onFetchComplete(Object cookie, Bitmap result) { if (result == null) { mLogo.setVisibility(View.GONE); } else { mLogo.setVisibility(View.VISIBLE); mLogo.setImageBitmap(result); } } }); } mUrl.setText(cursor.getString(VendorsQuery.URL)); mDesc.setText(cursor.getString(VendorsQuery.DESC)); mProductDesc.setText(cursor.getString(VendorsQuery.PRODUCT_DESC)); mTrackId = cursor.getString(VendorsQuery.TRACK_ID); // Assign track details when found // TODO: handle vendors not attached to track ActivityHelper activityHelper = ((BaseActivity) getActivity()).getActivityHelper(); activityHelper.setActionBarTitle(cursor.getString(VendorsQuery.TRACK_NAME)); activityHelper.setActionBarColor(cursor.getInt(VendorsQuery.TRACK_COLOR)); AnalyticsUtils.getInstance(getActivity()).trackPageView( "/Sandbox/Vendors/" + mNameString); } finally { cursor.close(); } } /** * Handle toggling of starred checkbox. */ public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { final ContentValues values = new ContentValues(); values.put(ScheduleContract.Vendors.VENDOR_STARRED, isChecked ? 1 : 0); mHandler.startUpdate(mVendorUri, values); AnalyticsUtils.getInstance(getActivity()).trackEvent( "Sandbox", isChecked ? "Starred" : "Unstarred", mNameString, 0); } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { inflater.inflate(R.menu.map_menu_items, menu); super.onCreateOptionsMenu(menu, inflater); } @Override public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == R.id.menu_map) { // The room ID for the sandbox, in the map, is just the track ID final Intent intent = new Intent(getActivity().getApplicationContext(), UIUtils.getMapActivityClass(getActivity())); intent.putExtra(MapFragment.EXTRA_ROOM, ParserUtils.translateTrackIdAliasInverse(mTrackId)); startActivity(intent); return true; } return super.onOptionsItemSelected(item); } /** * {@link com.google.android.apps.iosched.provider.ScheduleContract.Vendors} query parameters. */ private interface VendorsQuery { String[] PROJECTION = { ScheduleContract.Vendors.VENDOR_NAME, ScheduleContract.Vendors.VENDOR_LOCATION, ScheduleContract.Vendors.VENDOR_DESC, ScheduleContract.Vendors.VENDOR_URL, ScheduleContract.Vendors.VENDOR_PRODUCT_DESC, ScheduleContract.Vendors.VENDOR_LOGO_URL, ScheduleContract.Vendors.VENDOR_STARRED, ScheduleContract.Vendors.TRACK_ID, ScheduleContract.Tracks.TRACK_NAME, ScheduleContract.Tracks.TRACK_COLOR, }; int NAME = 0; int LOCATION = 1; int DESC = 2; int URL = 3; int PRODUCT_DESC = 4; int LOGO_URL = 5; int STARRED = 6; int TRACK_ID = 7; int TRACK_NAME = 8; int TRACK_COLOR = 9; } }
Java
/* * Copyright 2011 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.google.android.apps.iosched.ui; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.ui.phone.ScheduleActivity; import com.google.android.apps.iosched.ui.tablet.ScheduleMultiPaneActivity; import com.google.android.apps.iosched.ui.tablet.SessionsMultiPaneActivity; import com.google.android.apps.iosched.ui.tablet.VendorsMultiPaneActivity; import com.google.android.apps.iosched.util.AnalyticsUtils; import com.google.android.apps.iosched.util.UIUtils; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; public class DashboardFragment extends Fragment { public void fireTrackerEvent(String label) { AnalyticsUtils.getInstance(getActivity()).trackEvent( "Home Screen Dashboard", "Click", label, 0); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View root = inflater.inflate(R.layout.fragment_dashboard, container); // Attach event handlers root.findViewById(R.id.home_btn_schedule).setOnClickListener(new View.OnClickListener() { public void onClick(View view) { fireTrackerEvent("Schedule"); if (UIUtils.isHoneycombTablet(getActivity())) { startActivity(new Intent(getActivity(), ScheduleMultiPaneActivity.class)); } else { startActivity(new Intent(getActivity(), ScheduleActivity.class)); } } }); root.findViewById(R.id.home_btn_sessions).setOnClickListener(new View.OnClickListener() { public void onClick(View view) { fireTrackerEvent("Sessions"); // Launch sessions list if (UIUtils.isHoneycombTablet(getActivity())) { startActivity(new Intent(getActivity(), SessionsMultiPaneActivity.class)); } else { final Intent intent = new Intent(Intent.ACTION_VIEW, ScheduleContract.Tracks.CONTENT_URI); intent.putExtra(Intent.EXTRA_TITLE, getString(R.string.title_session_tracks)); intent.putExtra(TracksFragment.EXTRA_NEXT_TYPE, TracksFragment.NEXT_TYPE_SESSIONS); startActivity(intent); } } }); root.findViewById(R.id.home_btn_starred).setOnClickListener(new View.OnClickListener() { public void onClick(View view) { fireTrackerEvent("Starred"); // Launch list of sessions and vendors the user has starred startActivity(new Intent(getActivity(), StarredActivity.class)); } }); root.findViewById(R.id.home_btn_vendors).setOnClickListener(new View.OnClickListener() { public void onClick(View view) { fireTrackerEvent("Sandbox"); // Launch vendors list if (UIUtils.isHoneycombTablet(getActivity())) { startActivity(new Intent(getActivity(), VendorsMultiPaneActivity.class)); } else { final Intent intent = new Intent(Intent.ACTION_VIEW, ScheduleContract.Tracks.CONTENT_URI); intent.putExtra(Intent.EXTRA_TITLE, getString(R.string.title_vendor_tracks)); intent.putExtra(TracksFragment.EXTRA_NEXT_TYPE, TracksFragment.NEXT_TYPE_VENDORS); startActivity(intent); } } }); root.findViewById(R.id.home_btn_map).setOnClickListener(new View.OnClickListener() { public void onClick(View view) { // Launch map of conference venue fireTrackerEvent("Map"); startActivity(new Intent(getActivity(), UIUtils.getMapActivityClass(getActivity()))); } }); root.findViewById(R.id.home_btn_announcements).setOnClickListener( new View.OnClickListener() { public void onClick(View view) { // splicing in tag streamer fireTrackerEvent("Bulletin"); Intent intent = new Intent(getActivity(), BulletinActivity.class); startActivity(intent); } }); return root; } }
Java
/* * Copyright 2011 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.google.android.apps.iosched.ui; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.util.ActivityHelper; import com.google.android.apps.iosched.util.AnalyticsUtils; import com.google.android.apps.iosched.util.NotifyingAsyncQueryHandler; import com.google.android.apps.iosched.util.UIUtils; import android.content.Context; import android.content.Intent; import android.database.ContentObserver; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.os.SystemClock; import android.provider.BaseColumns; import android.support.v4.app.ListFragment; import android.text.Spannable; import android.util.Log; import android.view.View; import android.view.ViewGroup; import android.widget.CursorAdapter; import android.widget.ListView; import android.widget.TextView; import static com.google.android.apps.iosched.util.UIUtils.buildStyledSnippet; import static com.google.android.apps.iosched.util.UIUtils.formatSessionSubtitle; /** * A {@link ListFragment} showing a list of sessions. */ public class SessionsFragment extends ListFragment implements NotifyingAsyncQueryHandler.AsyncQueryListener { public static final String EXTRA_SCHEDULE_TIME_STRING = "com.google.android.iosched.extra.SCHEDULE_TIME_STRING"; private static final String STATE_CHECKED_POSITION = "checkedPosition"; private Uri mTrackUri; private Cursor mCursor; private CursorAdapter mAdapter; private int mCheckedPosition = -1; private boolean mHasSetEmptyText = false; private NotifyingAsyncQueryHandler mHandler; private Handler mMessageQueueHandler = new Handler(); @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mHandler = new NotifyingAsyncQueryHandler(getActivity().getContentResolver(), this); reloadFromArguments(getArguments()); } public void reloadFromArguments(Bundle arguments) { // Teardown from previous arguments if (mCursor != null) { getActivity().stopManagingCursor(mCursor); mCursor = null; } mCheckedPosition = -1; setListAdapter(null); mHandler.cancelOperation(SearchQuery._TOKEN); mHandler.cancelOperation(SessionsQuery._TOKEN); mHandler.cancelOperation(TracksQuery._TOKEN); // Load new arguments final Intent intent = BaseActivity.fragmentArgumentsToIntent(arguments); final Uri sessionsUri = intent.getData(); final int sessionQueryToken; if (sessionsUri == null) { return; } String[] projection; if (!ScheduleContract.Sessions.isSearchUri(sessionsUri)) { mAdapter = new SessionsAdapter(getActivity()); projection = SessionsQuery.PROJECTION; sessionQueryToken = SessionsQuery._TOKEN; } else { mAdapter = new SearchAdapter(getActivity()); projection = SearchQuery.PROJECTION; sessionQueryToken = SearchQuery._TOKEN; } setListAdapter(mAdapter); // Start background query to load sessions mHandler.startQuery(sessionQueryToken, null, sessionsUri, projection, null, null, ScheduleContract.Sessions.DEFAULT_SORT); // If caller launched us with specific track hint, pass it along when // launching session details. Also start a query to load the track info. mTrackUri = intent.getParcelableExtra(SessionDetailFragment.EXTRA_TRACK); if (mTrackUri != null) { mHandler.startQuery(TracksQuery._TOKEN, mTrackUri, TracksQuery.PROJECTION); } } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE); if (savedInstanceState != null) { mCheckedPosition = savedInstanceState.getInt(STATE_CHECKED_POSITION, -1); } if (!mHasSetEmptyText) { // Could be a bug, but calling this twice makes it become visible when it shouldn't // be visible. setEmptyText(getString(R.string.empty_sessions)); mHasSetEmptyText = true; } } /** {@inheritDoc} */ public void onQueryComplete(int token, Object cookie, Cursor cursor) { if (getActivity() == null) { return; } if (token == SessionsQuery._TOKEN || token == SearchQuery._TOKEN) { onSessionOrSearchQueryComplete(cursor); } else if (token == TracksQuery._TOKEN) { onTrackQueryComplete(cursor); } else { Log.d("SessionsFragment/onQueryComplete", "Query complete, Not Actionable: " + token); cursor.close(); } } /** * Handle {@link SessionsQuery} {@link Cursor}. */ private void onSessionOrSearchQueryComplete(Cursor cursor) { if (mCursor != null) { // In case cancelOperation() doesn't work and we end up with consecutive calls to this // callback. getActivity().stopManagingCursor(mCursor); mCursor = null; } mCursor = cursor; getActivity().startManagingCursor(mCursor); mAdapter.changeCursor(mCursor); if (mCheckedPosition >= 0 && getView() != null) { getListView().setItemChecked(mCheckedPosition, true); } } /** * Handle {@link TracksQuery} {@link Cursor}. */ private void onTrackQueryComplete(Cursor cursor) { try { if (!cursor.moveToFirst()) { return; } // Use found track to build title-bar ActivityHelper activityHelper = ((BaseActivity) getActivity()).getActivityHelper(); String trackName = cursor.getString(TracksQuery.TRACK_NAME); activityHelper.setActionBarTitle(trackName); activityHelper.setActionBarColor(cursor.getInt(TracksQuery.TRACK_COLOR)); AnalyticsUtils.getInstance(getActivity()).trackPageView("/Tracks/" + trackName); } finally { cursor.close(); } } @Override public void onResume() { super.onResume(); mMessageQueueHandler.post(mRefreshSessionsRunnable); getActivity().getContentResolver().registerContentObserver( ScheduleContract.Sessions.CONTENT_URI, true, mSessionChangesObserver); if (mCursor != null) { mCursor.requery(); } } @Override public void onPause() { super.onPause(); mMessageQueueHandler.removeCallbacks(mRefreshSessionsRunnable); getActivity().getContentResolver().unregisterContentObserver(mSessionChangesObserver); } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putInt(STATE_CHECKED_POSITION, mCheckedPosition); } /** {@inheritDoc} */ @Override public void onListItemClick(ListView l, View v, int position, long id) { // Launch viewer for specific session, passing along any track knowledge // that should influence the title-bar. final Cursor cursor = (Cursor)mAdapter.getItem(position); final String sessionId = cursor.getString(cursor.getColumnIndex( ScheduleContract.Sessions.SESSION_ID)); final Uri sessionUri = ScheduleContract.Sessions.buildSessionUri(sessionId); final Intent intent = new Intent(Intent.ACTION_VIEW, sessionUri); intent.putExtra(SessionDetailFragment.EXTRA_TRACK, mTrackUri); ((BaseActivity) getActivity()).openActivityOrFragment(intent); getListView().setItemChecked(position, true); mCheckedPosition = position; } public void clearCheckedPosition() { if (mCheckedPosition >= 0) { getListView().setItemChecked(mCheckedPosition, false); mCheckedPosition = -1; } } /** * {@link CursorAdapter} that renders a {@link SessionsQuery}. */ private class SessionsAdapter extends CursorAdapter { public SessionsAdapter(Context context) { super(context, null); } /** {@inheritDoc} */ @Override public View newView(Context context, Cursor cursor, ViewGroup parent) { return getActivity().getLayoutInflater().inflate(R.layout.list_item_session, parent, false); } /** {@inheritDoc} */ @Override public void bindView(View view, Context context, Cursor cursor) { final TextView titleView = (TextView) view.findViewById(R.id.session_title); final TextView subtitleView = (TextView) view.findViewById(R.id.session_subtitle); titleView.setText(cursor.getString(SessionsQuery.TITLE)); // Format time block this session occupies final long blockStart = cursor.getLong(SessionsQuery.BLOCK_START); final long blockEnd = cursor.getLong(SessionsQuery.BLOCK_END); final String roomName = cursor.getString(SessionsQuery.ROOM_NAME); final String subtitle = formatSessionSubtitle(blockStart, blockEnd, roomName, context); subtitleView.setText(subtitle); final boolean starred = cursor.getInt(SessionsQuery.STARRED) != 0; view.findViewById(R.id.star_button).setVisibility( starred ? View.VISIBLE : View.INVISIBLE); // Possibly indicate that the session has occurred in the past. UIUtils.setSessionTitleColor(blockStart, blockEnd, titleView, subtitleView); } } /** * {@link CursorAdapter} that renders a {@link SearchQuery}. */ private class SearchAdapter extends CursorAdapter { public SearchAdapter(Context context) { super(context, null); } /** {@inheritDoc} */ @Override public View newView(Context context, Cursor cursor, ViewGroup parent) { return getActivity().getLayoutInflater().inflate(R.layout.list_item_session, parent, false); } /** {@inheritDoc} */ @Override public void bindView(View view, Context context, Cursor cursor) { ((TextView) view.findViewById(R.id.session_title)).setText(cursor .getString(SearchQuery.TITLE)); final String snippet = cursor.getString(SearchQuery.SEARCH_SNIPPET); final Spannable styledSnippet = buildStyledSnippet(snippet); ((TextView) view.findViewById(R.id.session_subtitle)).setText(styledSnippet); final boolean starred = cursor.getInt(SearchQuery.STARRED) != 0; view.findViewById(R.id.star_button).setVisibility( starred ? View.VISIBLE : View.INVISIBLE); } } private ContentObserver mSessionChangesObserver = new ContentObserver(new Handler()) { @Override public void onChange(boolean selfChange) { if (mCursor != null) { mCursor.requery(); } } }; private Runnable mRefreshSessionsRunnable = new Runnable() { public void run() { if (mAdapter != null) { // This is used to refresh session title colors. mAdapter.notifyDataSetChanged(); } // Check again on the next quarter hour, with some padding to account for network // time differences. long nextQuarterHour = (SystemClock.uptimeMillis() / 900000 + 1) * 900000 + 5000; mMessageQueueHandler.postAtTime(mRefreshSessionsRunnable, nextQuarterHour); } }; /** * {@link com.google.android.apps.iosched.provider.ScheduleContract.Sessions} query parameters. */ private interface SessionsQuery { int _TOKEN = 0x1; String[] PROJECTION = { BaseColumns._ID, ScheduleContract.Sessions.SESSION_ID, ScheduleContract.Sessions.SESSION_TITLE, ScheduleContract.Sessions.SESSION_STARRED, ScheduleContract.Blocks.BLOCK_START, ScheduleContract.Blocks.BLOCK_END, ScheduleContract.Rooms.ROOM_NAME, }; int _ID = 0; int SESSION_ID = 1; int TITLE = 2; int STARRED = 3; int BLOCK_START = 4; int BLOCK_END = 5; int ROOM_NAME = 6; } /** * {@link com.google.android.apps.iosched.provider.ScheduleContract.Tracks} query parameters. */ private interface TracksQuery { int _TOKEN = 0x2; String[] PROJECTION = { ScheduleContract.Tracks.TRACK_NAME, ScheduleContract.Tracks.TRACK_COLOR, }; int TRACK_NAME = 0; int TRACK_COLOR = 1; } /** {@link com.google.android.apps.iosched.provider.ScheduleContract.Sessions} search query * parameters. */ private interface SearchQuery { int _TOKEN = 0x3; String[] PROJECTION = { BaseColumns._ID, ScheduleContract.Sessions.SESSION_ID, ScheduleContract.Sessions.SESSION_TITLE, ScheduleContract.Sessions.SEARCH_SNIPPET, ScheduleContract.Sessions.SESSION_STARRED, }; int _ID = 0; int SESSION_ID = 1; int TITLE = 2; int SEARCH_SNIPPET = 3; int STARRED = 4; } }
Java
/* * Copyright 2011 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.google.android.apps.iosched.ui; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.util.ActivityHelper; import com.google.android.apps.iosched.util.AnalyticsUtils; import com.google.android.apps.iosched.util.BitmapUtils; import com.google.android.apps.iosched.util.CatchNotesHelper; import com.google.android.apps.iosched.util.FractionalTouchDelegate; import com.google.android.apps.iosched.util.NotifyingAsyncQueryHandler; import com.google.android.apps.iosched.util.UIUtils; import android.content.BroadcastReceiver; import android.content.ContentValues; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.RectF; import android.graphics.Typeface; import android.net.Uri; import android.os.Bundle; import android.support.v4.app.Fragment; import android.text.Spannable; import android.text.SpannableStringBuilder; import android.text.TextUtils; import android.text.method.LinkMovementMethod; import android.text.style.StyleSpan; import android.util.Log; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.CompoundButton; import android.widget.ImageView; import android.widget.TabHost; import android.widget.TextView; /** * A fragment that shows detail information for a session, including session title, abstract, * time information, speaker photos and bios, etc. */ public class SessionDetailFragment extends Fragment implements NotifyingAsyncQueryHandler.AsyncQueryListener, CompoundButton.OnCheckedChangeListener { private static final String TAG = "SessionDetailFragment"; /** * Since sessions can belong tracks, the parent activity can send this extra specifying a * track URI that should be used for coloring the title-bar. */ public static final String EXTRA_TRACK = "com.google.android.iosched.extra.TRACK"; private static final String TAG_SUMMARY = "summary"; private static final String TAG_NOTES = "notes"; private static final String TAG_LINKS = "links"; private static StyleSpan sBoldSpan = new StyleSpan(Typeface.BOLD); private String mSessionId; private Uri mSessionUri; private Uri mTrackUri; private String mTitleString; private String mHashtag; private String mUrl; private TextView mTagDisplay; private String mRoomId; private ViewGroup mRootView; private TabHost mTabHost; private TextView mTitle; private TextView mSubtitle; private CompoundButton mStarred; private TextView mAbstract; private TextView mRequirements; private NotifyingAsyncQueryHandler mHandler; private boolean mSessionCursor = false; private boolean mSpeakersCursor = false; private boolean mHasSummaryContent = false; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); final Intent intent = BaseActivity.fragmentArgumentsToIntent(getArguments()); mSessionUri = intent.getData(); mTrackUri = resolveTrackUri(intent); if (mSessionUri == null) { return; } mSessionId = ScheduleContract.Sessions.getSessionId(mSessionUri); setHasOptionsMenu(true); } @Override public void onResume() { super.onResume(); updateNotesTab(); // Start listening for time updates to adjust "now" bar. TIME_TICK is // triggered once per minute, which is how we move the bar over time. final IntentFilter filter = new IntentFilter(); filter.addAction(Intent.ACTION_PACKAGE_ADDED); filter.addAction(Intent.ACTION_PACKAGE_REMOVED); filter.addAction(Intent.ACTION_PACKAGE_REPLACED); filter.addDataScheme("package"); getActivity().registerReceiver(mPackageChangesReceiver, filter); } @Override public void onPause() { super.onPause(); getActivity().unregisterReceiver(mPackageChangesReceiver); } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); if (mSessionUri == null) { return; } // Start background queries to load session and track details final Uri speakersUri = ScheduleContract.Sessions.buildSpeakersDirUri(mSessionId); mHandler = new NotifyingAsyncQueryHandler(getActivity().getContentResolver(), this); mHandler.startQuery(SessionsQuery._TOKEN, mSessionUri, SessionsQuery.PROJECTION); mHandler.startQuery(TracksQuery._TOKEN, mTrackUri, TracksQuery.PROJECTION); mHandler.startQuery(SpeakersQuery._TOKEN, speakersUri, SpeakersQuery.PROJECTION); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { mRootView = (ViewGroup) inflater.inflate(R.layout.fragment_session_detail, null); mTabHost = (TabHost) mRootView.findViewById(android.R.id.tabhost); mTabHost.setup(); mTitle = (TextView) mRootView.findViewById(R.id.session_title); mSubtitle = (TextView) mRootView.findViewById(R.id.session_subtitle); mStarred = (CompoundButton) mRootView.findViewById(R.id.star_button); mStarred.setFocusable(true); mStarred.setClickable(true); // Larger target triggers star toggle final View starParent = mRootView.findViewById(R.id.header_session); FractionalTouchDelegate.setupDelegate(starParent, mStarred, new RectF(0.6f, 0f, 1f, 0.8f)); mAbstract = (TextView) mRootView.findViewById(R.id.session_abstract); mRequirements = (TextView) mRootView.findViewById(R.id.session_requirements); setupSummaryTab(); setupNotesTab(); setupLinksTab(); return mRootView; } /** * Build and add "summary" tab. */ private void setupSummaryTab() { // Summary content comes from existing layout mTabHost.addTab(mTabHost.newTabSpec(TAG_SUMMARY) .setIndicator(buildIndicator(R.string.session_summary)) .setContent(R.id.tab_session_summary)); } /** * Build a {@link View} to be used as a tab indicator, setting the requested string resource as * its label. * * @param textRes * @return View */ private View buildIndicator(int textRes) { final TextView indicator = (TextView) getActivity().getLayoutInflater() .inflate(R.layout.tab_indicator, (ViewGroup) mRootView.findViewById(android.R.id.tabs), false); indicator.setText(textRes); return indicator; } /** * Derive {@link com.google.android.apps.iosched.provider.ScheduleContract.Tracks#CONTENT_ITEM_TYPE} * {@link Uri} based on incoming {@link Intent}, using * {@link #EXTRA_TRACK} when set. * @param intent * @return Uri */ private Uri resolveTrackUri(Intent intent) { final Uri trackUri = intent.getParcelableExtra(EXTRA_TRACK); if (trackUri != null) { return trackUri; } else { return ScheduleContract.Sessions.buildTracksDirUri(mSessionId); } } /** * {@inheritDoc} */ public void onQueryComplete(int token, Object cookie, Cursor cursor) { if (getActivity() == null) { return; } if (token == SessionsQuery._TOKEN) { onSessionQueryComplete(cursor); } else if (token == TracksQuery._TOKEN) { onTrackQueryComplete(cursor); } else if (token == SpeakersQuery._TOKEN) { onSpeakersQueryComplete(cursor); } else { cursor.close(); } } /** * Handle {@link SessionsQuery} {@link Cursor}. */ private void onSessionQueryComplete(Cursor cursor) { try { mSessionCursor = true; if (!cursor.moveToFirst()) { return; } // Format time block this session occupies final long blockStart = cursor.getLong(SessionsQuery.BLOCK_START); final long blockEnd = cursor.getLong(SessionsQuery.BLOCK_END); final String roomName = cursor.getString(SessionsQuery.ROOM_NAME); final String subtitle = UIUtils.formatSessionSubtitle(blockStart, blockEnd, roomName, getActivity()); mTitleString = cursor.getString(SessionsQuery.TITLE); mTitle.setText(mTitleString); mSubtitle.setText(subtitle); mUrl = cursor.getString(SessionsQuery.URL); if (TextUtils.isEmpty(mUrl)) { mUrl = ""; } mHashtag = cursor.getString(SessionsQuery.HASHTAG); mTagDisplay = (TextView) mRootView.findViewById(R.id.session_tags_button); if (!TextUtils.isEmpty(mHashtag)) { // Create the button text SpannableStringBuilder sb = new SpannableStringBuilder(); sb.append(getString(R.string.tag_stream) + " "); int boldStart = sb.length(); sb.append(getHashtagsString()); sb.setSpan(sBoldSpan, boldStart, sb.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); mTagDisplay.setText(sb); mTagDisplay.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { Intent intent = new Intent(getActivity(), TagStreamActivity.class); intent.putExtra(TagStreamFragment.EXTRA_QUERY, getHashtagsString()); startActivity(intent); } }); } else { mTagDisplay.setVisibility(View.GONE); } mRoomId = cursor.getString(SessionsQuery.ROOM_ID); // Unregister around setting checked state to avoid triggering // listener since change isn't user generated. mStarred.setOnCheckedChangeListener(null); mStarred.setChecked(cursor.getInt(SessionsQuery.STARRED) != 0); mStarred.setOnCheckedChangeListener(this); final String sessionAbstract = cursor.getString(SessionsQuery.ABSTRACT); if (!TextUtils.isEmpty(sessionAbstract)) { UIUtils.setTextMaybeHtml(mAbstract, sessionAbstract); mAbstract.setVisibility(View.VISIBLE); mHasSummaryContent = true; } else { mAbstract.setVisibility(View.GONE); } final View requirementsBlock = mRootView.findViewById(R.id.session_requirements_block); final String sessionRequirements = cursor.getString(SessionsQuery.REQUIREMENTS); if (!TextUtils.isEmpty(sessionRequirements)) { UIUtils.setTextMaybeHtml(mRequirements, sessionRequirements); requirementsBlock.setVisibility(View.VISIBLE); mHasSummaryContent = true; } else { requirementsBlock.setVisibility(View.GONE); } // Show empty message when all data is loaded, and nothing to show if (mSpeakersCursor && !mHasSummaryContent) { mRootView.findViewById(android.R.id.empty).setVisibility(View.VISIBLE); } AnalyticsUtils.getInstance(getActivity()).trackPageView("/Sessions/" + mTitleString); updateLinksTab(cursor); updateNotesTab(); } finally { cursor.close(); } } /** * Handle {@link TracksQuery} {@link Cursor}. */ private void onTrackQueryComplete(Cursor cursor) { try { if (!cursor.moveToFirst()) { return; } // Use found track to build title-bar ActivityHelper activityHelper = ((BaseActivity) getActivity()).getActivityHelper(); activityHelper.setActionBarTitle(cursor.getString(TracksQuery.TRACK_NAME)); activityHelper.setActionBarColor(cursor.getInt(TracksQuery.TRACK_COLOR)); } finally { cursor.close(); } } private void onSpeakersQueryComplete(Cursor cursor) { try { mSpeakersCursor = true; // TODO: remove any existing speakers from layout, since this cursor // might be from a data change notification. final ViewGroup speakersGroup = (ViewGroup) mRootView.findViewById(R.id.session_speakers_block); final LayoutInflater inflater = getActivity().getLayoutInflater(); boolean hasSpeakers = false; while (cursor.moveToNext()) { final String speakerName = cursor.getString(SpeakersQuery.SPEAKER_NAME); if (TextUtils.isEmpty(speakerName)) { continue; } final String speakerImageUrl = cursor.getString(SpeakersQuery.SPEAKER_IMAGE_URL); final String speakerCompany = cursor.getString(SpeakersQuery.SPEAKER_COMPANY); final String speakerUrl = cursor.getString(SpeakersQuery.SPEAKER_URL); final String speakerAbstract = cursor.getString(SpeakersQuery.SPEAKER_ABSTRACT); String speakerHeader = speakerName; if (!TextUtils.isEmpty(speakerCompany)) { speakerHeader += ", " + speakerCompany; } final View speakerView = inflater .inflate(R.layout.speaker_detail, speakersGroup, false); final TextView speakerHeaderView = (TextView) speakerView .findViewById(R.id.speaker_header); final ImageView speakerImgView = (ImageView) speakerView .findViewById(R.id.speaker_image); final TextView speakerUrlView = (TextView) speakerView .findViewById(R.id.speaker_url); final TextView speakerAbstractView = (TextView) speakerView .findViewById(R.id.speaker_abstract); if (!TextUtils.isEmpty(speakerImageUrl)) { BitmapUtils.fetchImage(getActivity(), speakerImageUrl, null, null, new BitmapUtils.OnFetchCompleteListener() { public void onFetchComplete(Object cookie, Bitmap result) { if (result != null) { speakerImgView.setImageBitmap(result); } } }); } speakerHeaderView.setText(speakerHeader); UIUtils.setTextMaybeHtml(speakerAbstractView, speakerAbstract); if (!TextUtils.isEmpty(speakerUrl)) { UIUtils.setTextMaybeHtml(speakerUrlView, speakerUrl); speakerUrlView.setVisibility(View.VISIBLE); } else { speakerUrlView.setVisibility(View.GONE); } speakersGroup.addView(speakerView); hasSpeakers = true; mHasSummaryContent = true; } speakersGroup.setVisibility(hasSpeakers ? View.VISIBLE : View.GONE); // Show empty message when all data is loaded, and nothing to show if (mSessionCursor && !mHasSummaryContent) { mRootView.findViewById(android.R.id.empty).setVisibility(View.VISIBLE); } } finally { if (null != cursor) { cursor.close(); } } } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { inflater.inflate(R.menu.session_detail_menu_items, menu); super.onCreateOptionsMenu(menu, inflater); } @Override public boolean onOptionsItemSelected(MenuItem item) { final String shareString; final Intent intent; switch (item.getItemId()) { case R.id.menu_map: intent = new Intent(getActivity().getApplicationContext(), UIUtils.getMapActivityClass(getActivity())); intent.putExtra(MapFragment.EXTRA_ROOM, mRoomId); startActivity(intent); return true; case R.id.menu_share: // TODO: consider bringing in shortlink to session shareString = getString(R.string.share_template, mTitleString, getHashtagsString(), mUrl); intent = new Intent(Intent.ACTION_SEND); intent.setType("text/plain"); intent.putExtra(Intent.EXTRA_TEXT, shareString); startActivity(Intent.createChooser(intent, getText(R.string.title_share))); return true; } return super.onOptionsItemSelected(item); } /** * Handle toggling of starred checkbox. */ public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { final ContentValues values = new ContentValues(); values.put(ScheduleContract.Sessions.SESSION_STARRED, isChecked ? 1 : 0); mHandler.startUpdate(mSessionUri, values); // Because change listener is set to null during initialization, these won't fire on // pageview. AnalyticsUtils.getInstance(getActivity()).trackEvent( "Sandbox", isChecked ? "Starred" : "Unstarred", mTitleString, 0); } /** * Build and add "notes" tab. */ private void setupNotesTab() { // Make powered-by clickable ((TextView) mRootView.findViewById(R.id.notes_powered_by)).setMovementMethod( LinkMovementMethod.getInstance()); // Setup tab mTabHost.addTab(mTabHost.newTabSpec(TAG_NOTES) .setIndicator(buildIndicator(R.string.session_notes)) .setContent(R.id.tab_session_notes)); } /* * Event structure: * Category -> "Session Details" * Action -> "Create Note", "View Note", etc * Label -> Session's Title * Value -> 0. */ public void fireNotesEvent(int actionId) { AnalyticsUtils.getInstance(getActivity()).trackEvent( "Session Details", getActivity().getString(actionId), mTitleString, 0); } /* * Event structure: * Category -> "Session Details" * Action -> Link Text * Label -> Session's Title * Value -> 0. */ public void fireLinkEvent(int actionId) { AnalyticsUtils.getInstance(getActivity()).trackEvent( "Link Details", getActivity().getString(actionId), mTitleString, 0); } private void updateNotesTab() { final CatchNotesHelper helper = new CatchNotesHelper(getActivity()); final boolean notesInstalled = helper.isNotesInstalledAndMinimumVersion(); final Intent marketIntent = helper.notesMarketIntent(); final Intent newIntent = helper.createNoteIntent( getString(R.string.note_template, mTitleString, getHashtagsString())); final Intent viewIntent = helper.viewNotesIntent(getHashtagsString()); // Set icons and click listeners ((ImageView) mRootView.findViewById(R.id.notes_catch_market_icon)).setImageDrawable( UIUtils.getIconForIntent(getActivity(), marketIntent)); ((ImageView) mRootView.findViewById(R.id.notes_catch_new_icon)).setImageDrawable( UIUtils.getIconForIntent(getActivity(), newIntent)); ((ImageView) mRootView.findViewById(R.id.notes_catch_view_icon)).setImageDrawable( UIUtils.getIconForIntent(getActivity(), viewIntent)); // Set click listeners mRootView.findViewById(R.id.notes_catch_market_link).setOnClickListener( new View.OnClickListener() { public void onClick(View view) { startActivity(marketIntent); fireNotesEvent(R.string.notes_catch_market_title); } }); mRootView.findViewById(R.id.notes_catch_new_link).setOnClickListener( new View.OnClickListener() { public void onClick(View view) { startActivity(newIntent); fireNotesEvent(R.string.notes_catch_new_title); } }); mRootView.findViewById(R.id.notes_catch_view_link).setOnClickListener( new View.OnClickListener() { public void onClick(View view) { startActivity(viewIntent); fireNotesEvent(R.string.notes_catch_view_title); } }); // Show/hide elements mRootView.findViewById(R.id.notes_catch_market_link).setVisibility( notesInstalled ? View.GONE : View.VISIBLE); mRootView.findViewById(R.id.notes_catch_market_separator).setVisibility( notesInstalled ? View.GONE : View.VISIBLE); mRootView.findViewById(R.id.notes_catch_new_link).setVisibility( !notesInstalled ? View.GONE : View.VISIBLE); mRootView.findViewById(R.id.notes_catch_new_separator).setVisibility( !notesInstalled ? View.GONE : View.VISIBLE); mRootView.findViewById(R.id.notes_catch_view_link).setVisibility( !notesInstalled ? View.GONE : View.VISIBLE); mRootView.findViewById(R.id.notes_catch_view_separator).setVisibility( !notesInstalled ? View.GONE : View.VISIBLE); } /** * Build and add "summary" tab. */ private void setupLinksTab() { // Summary content comes from existing layout mTabHost.addTab(mTabHost.newTabSpec(TAG_LINKS) .setIndicator(buildIndicator(R.string.session_links)) .setContent(R.id.tab_session_links)); } private void updateLinksTab(Cursor cursor) { ViewGroup container = (ViewGroup) mRootView.findViewById(R.id.links_container); // Remove all views but the 'empty' view int childCount = container.getChildCount(); if (childCount > 1) { container.removeViews(1, childCount - 1); } LayoutInflater inflater = getLayoutInflater(null); boolean hasLinks = false; for (int i = 0; i < SessionsQuery.LINKS_INDICES.length; i++) { final String url = cursor.getString(SessionsQuery.LINKS_INDICES[i]); if (!TextUtils.isEmpty(url)) { hasLinks = true; ViewGroup linkContainer = (ViewGroup) inflater.inflate(R.layout.list_item_session_link, container, false); ((TextView) linkContainer.findViewById(R.id.link_text)).setText( SessionsQuery.LINKS_TITLES[i]); final int linkTitleIndex = i; linkContainer.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { fireLinkEvent(SessionsQuery.LINKS_TITLES[linkTitleIndex]); Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url)); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET); startActivity(intent); } }); container.addView(linkContainer); // Create separator View separatorView = new ImageView(getActivity()); separatorView.setLayoutParams( new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)); separatorView.setBackgroundResource(android.R.drawable.divider_horizontal_bright); container.addView(separatorView); } } container.findViewById(R.id.empty_links).setVisibility(hasLinks ? View.GONE : View.VISIBLE); } private String getHashtagsString() { if (!TextUtils.isEmpty(mHashtag)) { return TagStreamFragment.CONFERENCE_HASHTAG + " #" + mHashtag; } else { return TagStreamFragment.CONFERENCE_HASHTAG; } } private BroadcastReceiver mPackageChangesReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { updateNotesTab(); } }; /** * {@link com.google.android.apps.iosched.provider.ScheduleContract.Sessions} query parameters. */ private interface SessionsQuery { int _TOKEN = 0x1; String[] PROJECTION = { ScheduleContract.Blocks.BLOCK_START, ScheduleContract.Blocks.BLOCK_END, ScheduleContract.Sessions.SESSION_LEVEL, ScheduleContract.Sessions.SESSION_TITLE, ScheduleContract.Sessions.SESSION_ABSTRACT, ScheduleContract.Sessions.SESSION_REQUIREMENTS, ScheduleContract.Sessions.SESSION_STARRED, ScheduleContract.Sessions.SESSION_HASHTAG, ScheduleContract.Sessions.SESSION_SLUG, ScheduleContract.Sessions.SESSION_URL, ScheduleContract.Sessions.SESSION_MODERATOR_URL, ScheduleContract.Sessions.SESSION_YOUTUBE_URL, ScheduleContract.Sessions.SESSION_PDF_URL, ScheduleContract.Sessions.SESSION_FEEDBACK_URL, ScheduleContract.Sessions.SESSION_NOTES_URL, ScheduleContract.Sessions.ROOM_ID, ScheduleContract.Rooms.ROOM_NAME, }; int BLOCK_START = 0; int BLOCK_END = 1; int LEVEL = 2; int TITLE = 3; int ABSTRACT = 4; int REQUIREMENTS = 5; int STARRED = 6; int HASHTAG = 7; int SLUG = 8; int URL = 9; int MODERATOR_URL = 10; int YOUTUBE_URL = 11; int PDF_URL = 12; int FEEDBACK_URL = 13; int NOTES_URL = 14; int ROOM_ID = 15; int ROOM_NAME = 16; int[] LINKS_INDICES = { URL, MODERATOR_URL, YOUTUBE_URL, PDF_URL, FEEDBACK_URL, NOTES_URL, }; int[] LINKS_TITLES = { R.string.session_link_main, R.string.session_link_moderator, R.string.session_link_youtube, R.string.session_link_pdf, R.string.session_link_feedback, R.string.session_link_notes, }; } /** * {@link com.google.android.apps.iosched.provider.ScheduleContract.Tracks} query parameters. */ private interface TracksQuery { int _TOKEN = 0x2; String[] PROJECTION = { ScheduleContract.Tracks.TRACK_NAME, ScheduleContract.Tracks.TRACK_COLOR, }; int TRACK_NAME = 0; int TRACK_COLOR = 1; } private interface SpeakersQuery { int _TOKEN = 0x3; String[] PROJECTION = { ScheduleContract.Speakers.SPEAKER_NAME, ScheduleContract.Speakers.SPEAKER_IMAGE_URL, ScheduleContract.Speakers.SPEAKER_COMPANY, ScheduleContract.Speakers.SPEAKER_ABSTRACT, ScheduleContract.Speakers.SPEAKER_URL, }; int SPEAKER_NAME = 0; int SPEAKER_IMAGE_URL = 1; int SPEAKER_COMPANY = 2; int SPEAKER_ABSTRACT = 3; int SPEAKER_URL = 4; } }
Java
/* * Copyright 2011 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.google.android.apps.iosched.ui; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.util.AnalyticsUtils; import android.content.Intent; import android.graphics.Bitmap; import android.net.Uri; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.webkit.WebView; import android.webkit.WebViewClient; import java.util.regex.Pattern; /** * A fragment containing a {@link WebView} pointing to the I/O announcements URL. */ public class BulletinFragment extends Fragment { private static final Pattern sSiteUrlPattern = Pattern.compile("google\\.com\\/events\\/io"); private static final String BULLETIN_URL = "http://www.google.com/events/io/2011/mobile_announcements.html"; private WebView mWebView; private View mLoadingSpinner; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setHasOptionsMenu(true); AnalyticsUtils.getInstance(getActivity()).trackPageView("/Bulletin"); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { ViewGroup root = (ViewGroup) inflater.inflate(R.layout.fragment_webview_with_spinner, null); // For some reason, if we omit this, NoSaveStateFrameLayout thinks we are // FILL_PARENT / WRAP_CONTENT, making the progress bar stick to the top of the activity. root.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT)); mLoadingSpinner = root.findViewById(R.id.loading_spinner); mWebView = (WebView) root.findViewById(R.id.webview); mWebView.setWebViewClient(mWebViewClient); mWebView.post(new Runnable() { public void run() { mWebView.getSettings().setJavaScriptEnabled(true); mWebView.getSettings().setJavaScriptCanOpenWindowsAutomatically(false); mWebView.loadUrl(BULLETIN_URL); } }); return root; } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { super.onCreateOptionsMenu(menu, inflater); inflater.inflate(R.menu.refresh_menu_items, menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == R.id.menu_refresh) { mWebView.reload(); return true; } return super.onOptionsItemSelected(item); } private WebViewClient mWebViewClient = new WebViewClient() { @Override public void onPageStarted(WebView view, String url, Bitmap favicon) { super.onPageStarted(view, url, favicon); mLoadingSpinner.setVisibility(View.VISIBLE); mWebView.setVisibility(View.INVISIBLE); } @Override public void onPageFinished(WebView view, String url) { super.onPageFinished(view, url); mLoadingSpinner.setVisibility(View.GONE); mWebView.setVisibility(View.VISIBLE); } @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { if (sSiteUrlPattern.matcher(url).find()) { return false; } Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url)); startActivity(intent); return true; } }; }
Java
/* * Copyright 2011 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.google.android.apps.iosched.ui; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.util.ActivityHelper; import com.google.android.apps.iosched.util.AnalyticsUtils; import com.google.android.apps.iosched.util.NotifyingAsyncQueryHandler; import android.content.Context; import android.content.Intent; import android.database.ContentObserver; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.provider.BaseColumns; import android.support.v4.app.ListFragment; import android.text.Spannable; import android.util.Log; import android.view.View; import android.view.ViewGroup; import android.widget.CursorAdapter; import android.widget.ListView; import android.widget.TextView; import static com.google.android.apps.iosched.util.UIUtils.buildStyledSnippet; /** * A {@link ListFragment} showing a list of sandbox comapnies. */ public class VendorsFragment extends ListFragment implements NotifyingAsyncQueryHandler.AsyncQueryListener { private static final String STATE_CHECKED_POSITION = "checkedPosition"; private Uri mTrackUri; private Cursor mCursor; private CursorAdapter mAdapter; private int mCheckedPosition = -1; private boolean mHasSetEmptyText = false; private NotifyingAsyncQueryHandler mHandler; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mHandler = new NotifyingAsyncQueryHandler(getActivity().getContentResolver(), this); reloadFromArguments(getArguments()); } public void reloadFromArguments(Bundle arguments) { // Teardown from previous arguments if (mCursor != null) { getActivity().stopManagingCursor(mCursor); mCursor = null; } mCheckedPosition = -1; setListAdapter(null); mHandler.cancelOperation(SearchQuery._TOKEN); mHandler.cancelOperation(VendorsQuery._TOKEN); // Load new arguments final Intent intent = BaseActivity.fragmentArgumentsToIntent(arguments); final Uri vendorsUri = intent.getData(); final int vendorQueryToken; if (vendorsUri == null) { return; } String[] projection; if (!ScheduleContract.Vendors.isSearchUri(vendorsUri)) { mAdapter = new VendorsAdapter(getActivity()); projection = VendorsQuery.PROJECTION; vendorQueryToken = VendorsQuery._TOKEN; } else { Log.d("VendorsFragment/reloadFromArguments", "A search URL definitely gets passed in."); mAdapter = new SearchAdapter(getActivity()); projection = SearchQuery.PROJECTION; vendorQueryToken = SearchQuery._TOKEN; } setListAdapter(mAdapter); // Start background query to load vendors mHandler.startQuery(vendorQueryToken, null, vendorsUri, projection, null, null, ScheduleContract.Vendors.DEFAULT_SORT); // If caller launched us with specific track hint, pass it along when // launching vendor details. Also start a query to load the track info. mTrackUri = intent.getParcelableExtra(SessionDetailFragment.EXTRA_TRACK); if (mTrackUri != null) { mHandler.startQuery(TracksQuery._TOKEN, mTrackUri, TracksQuery.PROJECTION); } } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE); if (savedInstanceState != null) { mCheckedPosition = savedInstanceState.getInt(STATE_CHECKED_POSITION, -1); } if (!mHasSetEmptyText) { // Could be a bug, but calling this twice makes it become visible when it shouldn't // be visible. setEmptyText(getString(R.string.empty_vendors)); mHasSetEmptyText = true; } } /** {@inheritDoc} */ public void onQueryComplete(int token, Object cookie, Cursor cursor) { if (getActivity() == null) { return; } if (token == VendorsQuery._TOKEN || token == SearchQuery._TOKEN) { onVendorsOrSearchQueryComplete(cursor); } else if (token == TracksQuery._TOKEN) { onTrackQueryComplete(cursor); } else { cursor.close(); } } /** * Handle {@link VendorsQuery} {@link Cursor}. */ private void onVendorsOrSearchQueryComplete(Cursor cursor) { if (mCursor != null) { // In case cancelOperation() doesn't work and we end up with consecutive calls to this // callback. getActivity().stopManagingCursor(mCursor); mCursor = null; } // TODO(romannurik): stopManagingCursor on detach (throughout app) mCursor = cursor; getActivity().startManagingCursor(mCursor); mAdapter.changeCursor(mCursor); if (mCheckedPosition >= 0 && getView() != null) { getListView().setItemChecked(mCheckedPosition, true); } } /** * Handle {@link TracksQuery} {@link Cursor}. */ private void onTrackQueryComplete(Cursor cursor) { try { if (!cursor.moveToFirst()) { return; } // Use found track to build title-bar ActivityHelper activityHelper = ((BaseActivity) getActivity()).getActivityHelper(); String trackName = cursor.getString(TracksQuery.TRACK_NAME); activityHelper.setActionBarTitle(trackName); activityHelper.setActionBarColor(cursor.getInt(TracksQuery.TRACK_COLOR)); AnalyticsUtils.getInstance(getActivity()).trackPageView("/Sandbox/Track/" + trackName); } finally { cursor.close(); } } @Override public void onResume() { super.onResume(); getActivity().getContentResolver().registerContentObserver( ScheduleContract.Vendors.CONTENT_URI, true, mVendorChangesObserver); if (mCursor != null) { mCursor.requery(); } } @Override public void onPause() { super.onPause(); getActivity().getContentResolver().unregisterContentObserver(mVendorChangesObserver); } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putInt(STATE_CHECKED_POSITION, mCheckedPosition); } /** {@inheritDoc} */ @Override public void onListItemClick(ListView l, View v, int position, long id) { // Launch viewer for specific vendor. final Cursor cursor = (Cursor)mAdapter.getItem(position); final String vendorId = cursor.getString(VendorsQuery.VENDOR_ID); final Uri vendorUri = ScheduleContract.Vendors.buildVendorUri(vendorId); ((BaseActivity) getActivity()).openActivityOrFragment(new Intent(Intent.ACTION_VIEW, vendorUri)); getListView().setItemChecked(position, true); mCheckedPosition = position; } public void clearCheckedPosition() { if (mCheckedPosition >= 0) { getListView().setItemChecked(mCheckedPosition, false); mCheckedPosition = -1; } } /** * {@link CursorAdapter} that renders a {@link VendorsQuery}. */ private class VendorsAdapter extends CursorAdapter { public VendorsAdapter(Context context) { super(context, null); } /** {@inheritDoc} */ @Override public View newView(Context context, Cursor cursor, ViewGroup parent) { return getActivity().getLayoutInflater().inflate(R.layout.list_item_vendor_oneline, parent, false); } /** {@inheritDoc} */ @Override public void bindView(View view, Context context, Cursor cursor) { ((TextView) view.findViewById(R.id.vendor_name)).setText( cursor.getString(VendorsQuery.NAME)); final boolean starred = cursor.getInt(VendorsQuery.STARRED) != 0; view.findViewById(R.id.star_button).setVisibility( starred ? View.VISIBLE : View.INVISIBLE); } } /** * {@link CursorAdapter} that renders a {@link SearchQuery}. */ private class SearchAdapter extends CursorAdapter { public SearchAdapter(Context context) { super(context, null); } /** {@inheritDoc} */ @Override public View newView(Context context, Cursor cursor, ViewGroup parent) { return getActivity().getLayoutInflater().inflate(R.layout.list_item_vendor, parent, false); } /** {@inheritDoc} */ @Override public void bindView(View view, Context context, Cursor cursor) { ((TextView) view.findViewById(R.id.vendor_name)).setText(cursor .getString(SearchQuery.NAME)); final String snippet = cursor.getString(SearchQuery.SEARCH_SNIPPET); final Spannable styledSnippet = buildStyledSnippet(snippet); ((TextView) view.findViewById(R.id.vendor_location)).setText(styledSnippet); final boolean starred = cursor.getInt(VendorsQuery.STARRED) != 0; view.findViewById(R.id.star_button).setVisibility( starred ? View.VISIBLE : View.INVISIBLE); } } private ContentObserver mVendorChangesObserver = new ContentObserver(new Handler()) { @Override public void onChange(boolean selfChange) { if (mCursor != null) { mCursor.requery(); } } }; /** * {@link com.google.android.apps.iosched.provider.ScheduleContract.Vendors} query parameters. */ private interface VendorsQuery { int _TOKEN = 0x1; String[] PROJECTION = { BaseColumns._ID, ScheduleContract.Vendors.VENDOR_ID, ScheduleContract.Vendors.VENDOR_NAME, ScheduleContract.Vendors.VENDOR_LOCATION, ScheduleContract.Vendors.VENDOR_STARRED, }; int _ID = 0; int VENDOR_ID = 1; int NAME = 2; int LOCATION = 3; int STARRED = 4; } /** * {@link com.google.android.apps.iosched.provider.ScheduleContract.Tracks} query parameters. */ private interface TracksQuery { int _TOKEN = 0x2; String[] PROJECTION = { ScheduleContract.Tracks.TRACK_NAME, ScheduleContract.Tracks.TRACK_COLOR, }; int TRACK_NAME = 0; int TRACK_COLOR = 1; } /** {@link com.google.android.apps.iosched.provider.ScheduleContract.Vendors} search query * parameters. */ private interface SearchQuery { int _TOKEN = 0x3; String[] PROJECTION = { BaseColumns._ID, ScheduleContract.Vendors.VENDOR_ID, ScheduleContract.Vendors.VENDOR_NAME, ScheduleContract.Vendors.SEARCH_SNIPPET, ScheduleContract.Vendors.VENDOR_STARRED, }; int _ID = 0; int VENDOR_ID = 1; int NAME = 2; int SEARCH_SNIPPET = 3; int STARRED = 4; } }
Java
/* * Copyright 2011 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.google.android.apps.iosched.ui; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.provider.ScheduleContract.Sessions; import com.google.android.apps.iosched.provider.ScheduleContract.Vendors; import com.google.android.apps.iosched.ui.phone.SessionDetailActivity; import com.google.android.apps.iosched.ui.phone.VendorDetailActivity; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.FragmentManager; import android.view.View; import android.view.ViewGroup; import android.widget.FrameLayout; import android.widget.TabHost; import android.widget.TabWidget; import android.widget.TextView; /** * An activity that shows the user's starred sessions and sandbox companies. This activity can be * either single or multi-pane, depending on the device configuration. We want the multi-pane * support that {@link BaseMultiPaneActivity} offers, so we inherit from it instead of * {@link BaseSinglePaneActivity}. */ public class StarredActivity extends BaseMultiPaneActivity { public static final String TAG_SESSIONS = "sessions"; public static final String TAG_VENDORS = "vendors"; private TabHost mTabHost; private TabWidget mTabWidget; private SessionsFragment mSessionsFragment; private VendorsFragment mVendorsFragment; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_starred); getActivityHelper().setupActionBar(getTitle(), 0); mTabHost = (TabHost) findViewById(android.R.id.tabhost); mTabWidget = (TabWidget) findViewById(android.R.id.tabs); mTabHost.setup(); setupSessionsTab(); setupVendorsTab(); } @Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); getActivityHelper().setupSubActivity(); ViewGroup detailContainer = (ViewGroup) findViewById(R.id.fragment_container_starred_detail); if (detailContainer != null && detailContainer.getChildCount() > 1) { findViewById(android.R.id.empty).setVisibility(View.GONE); } } /** * Build and add "sessions" tab. */ private void setupSessionsTab() { // TODO: this is very inefficient and messy, clean it up FrameLayout fragmentContainer = new FrameLayout(this); fragmentContainer.setId(R.id.fragment_sessions); fragmentContainer.setLayoutParams( new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT)); ((ViewGroup) findViewById(android.R.id.tabcontent)).addView(fragmentContainer); final Intent intent = new Intent(Intent.ACTION_VIEW, Sessions.CONTENT_STARRED_URI); final FragmentManager fm = getSupportFragmentManager(); mSessionsFragment = (SessionsFragment) fm.findFragmentByTag("sessions"); if (mSessionsFragment == null) { mSessionsFragment = new SessionsFragment(); mSessionsFragment.setArguments(intentToFragmentArguments(intent)); fm.beginTransaction() .add(R.id.fragment_sessions, mSessionsFragment, "sessions") .commit(); } // Sessions content comes from reused activity mTabHost.addTab(mTabHost.newTabSpec(TAG_SESSIONS) .setIndicator(buildIndicator(R.string.starred_sessions)) .setContent(R.id.fragment_sessions)); } /** * Build and add "vendors" tab. */ private void setupVendorsTab() { // TODO: this is very inefficient and messy, clean it up FrameLayout fragmentContainer = new FrameLayout(this); fragmentContainer.setId(R.id.fragment_vendors); fragmentContainer.setLayoutParams( new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT)); ((ViewGroup) findViewById(android.R.id.tabcontent)).addView(fragmentContainer); final Intent intent = new Intent(Intent.ACTION_VIEW, Vendors.CONTENT_STARRED_URI); final FragmentManager fm = getSupportFragmentManager(); mVendorsFragment = (VendorsFragment) fm.findFragmentByTag("vendors"); if (mVendorsFragment == null) { mVendorsFragment = new VendorsFragment(); mVendorsFragment.setArguments(intentToFragmentArguments(intent)); fm.beginTransaction() .add(R.id.fragment_vendors, mVendorsFragment, "vendors") .commit(); } // Vendors content comes from reused activity mTabHost.addTab(mTabHost.newTabSpec(TAG_VENDORS) .setIndicator(buildIndicator(R.string.starred_vendors)) .setContent(R.id.fragment_vendors)); } /** * Build a {@link View} to be used as a tab indicator, setting the requested string resource as * its label. */ private View buildIndicator(int textRes) { final TextView indicator = (TextView) getLayoutInflater().inflate(R.layout.tab_indicator, mTabWidget, false); indicator.setText(textRes); return indicator; } @Override public FragmentReplaceInfo onSubstituteFragmentForActivityLaunch(String activityClassName) { if (findViewById(R.id.fragment_container_starred_detail) != null) { // The layout we currently have has a detail container, we can add fragments there. findViewById(android.R.id.empty).setVisibility(View.GONE); if (SessionDetailActivity.class.getName().equals(activityClassName)) { clearSelectedItems(); return new FragmentReplaceInfo( SessionDetailFragment.class, "session_detail", R.id.fragment_container_starred_detail); } else if (VendorDetailActivity.class.getName().equals(activityClassName)) { clearSelectedItems(); return new FragmentReplaceInfo( VendorDetailFragment.class, "vendor_detail", R.id.fragment_container_starred_detail); } } return null; } private void clearSelectedItems() { if (mSessionsFragment != null) { mSessionsFragment.clearCheckedPosition(); } if (mVendorsFragment != null) { mVendorsFragment.clearCheckedPosition(); } } }
Java
/* * Copyright 2011 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.google.android.apps.iosched.ui; import com.google.android.apps.iosched.R; import android.content.Intent; import android.graphics.Bitmap; import android.net.Uri; import android.os.Bundle; import android.support.v4.app.Fragment; import android.text.TextUtils; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.webkit.WebView; import android.webkit.WebViewClient; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; /** * A {@link WebView}-based fragment that shows Google Realtime Search results for a given query, * provided as the {@link TagStreamFragment#EXTRA_QUERY} extra in the fragment arguments. If no * search query is provided, the conference hashtag is used as the default query. */ public class TagStreamFragment extends Fragment { private static final String TAG = "TagStreamFragment"; public static final String EXTRA_QUERY = "com.google.android.iosched.extra.QUERY"; public static final String CONFERENCE_HASHTAG = "#io2011"; private String mSearchString; private WebView mWebView; private View mLoadingSpinner; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); final Intent intent = BaseActivity.fragmentArgumentsToIntent(getArguments()); mSearchString = intent.getStringExtra(EXTRA_QUERY); if (TextUtils.isEmpty(mSearchString)) { mSearchString = CONFERENCE_HASHTAG; } if (!mSearchString.startsWith("#")) { mSearchString = "#" + mSearchString; } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { ViewGroup root = (ViewGroup) inflater.inflate(R.layout.fragment_webview_with_spinner, null); // For some reason, if we omit this, NoSaveStateFrameLayout thinks we are // FILL_PARENT / WRAP_CONTENT, making the progress bar stick to the top of the activity. root.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT)); mLoadingSpinner = root.findViewById(R.id.loading_spinner); mWebView = (WebView) root.findViewById(R.id.webview); mWebView.setWebViewClient(mWebViewClient); mWebView.post(new Runnable() { public void run() { mWebView.getSettings().setJavaScriptEnabled(true); mWebView.getSettings().setJavaScriptCanOpenWindowsAutomatically(false); try { mWebView.loadUrl( "http://www.google.com/search?tbs=" + "mbl%3A1&hl=en&source=hp&biw=1170&bih=668&q=" + URLEncoder.encode(mSearchString, "UTF-8") + "&btnG=Search"); } catch (UnsupportedEncodingException e) { Log.e(TAG, "Could not construct the realtime search URL", e); } } }); return root; } public void refresh() { mWebView.reload(); } private WebViewClient mWebViewClient = new WebViewClient() { @Override public void onPageStarted(WebView view, String url, Bitmap favicon) { super.onPageStarted(view, url, favicon); mLoadingSpinner.setVisibility(View.VISIBLE); mWebView.setVisibility(View.INVISIBLE); } @Override public void onPageFinished(WebView view, String url) { super.onPageFinished(view, url); mLoadingSpinner.setVisibility(View.GONE); mWebView.setVisibility(View.VISIBLE); } @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { if (url.startsWith("javascript")) { return false; } Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url)); startActivity(intent); return true; } }; }
Java
/* * Copyright 2011 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.google.android.apps.iosched.ui; import android.content.Intent; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import java.util.List; /** * A {@link BaseActivity} that can contain multiple panes, and has the ability to substitute * fragments for activities when intents are fired using * {@link BaseActivity#openActivityOrFragment(android.content.Intent)}. */ public abstract class BaseMultiPaneActivity extends BaseActivity { /** {@inheritDoc} */ @Override public void openActivityOrFragment(final Intent intent) { final PackageManager pm = getPackageManager(); List<ResolveInfo> resolveInfoList = pm .queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY); for (ResolveInfo resolveInfo : resolveInfoList) { final FragmentReplaceInfo fri = onSubstituteFragmentForActivityLaunch( resolveInfo.activityInfo.name); if (fri != null) { final Bundle arguments = intentToFragmentArguments(intent); final FragmentManager fm = getSupportFragmentManager(); try { Fragment fragment = (Fragment) fri.getFragmentClass().newInstance(); fragment.setArguments(arguments); FragmentTransaction ft = fm.beginTransaction(); ft.replace(fri.getContainerId(), fragment, fri.getFragmentTag()); onBeforeCommitReplaceFragment(fm, ft, fragment); ft.commit(); } catch (InstantiationException e) { throw new IllegalStateException( "Error creating new fragment.", e); } catch (IllegalAccessException e) { throw new IllegalStateException( "Error creating new fragment.", e); } return; } } super.openActivityOrFragment(intent); } /** * Callback that's triggered to find out if a fragment can substitute the given activity class. * Base activites should return a {@link FragmentReplaceInfo} if a fragment can act in place * of the given activity class name. */ protected FragmentReplaceInfo onSubstituteFragmentForActivityLaunch(String activityClassName) { return null; } /** * Called just before a fragment replacement transaction is committed in response to an intent * being fired and substituted for a fragment. */ protected void onBeforeCommitReplaceFragment(FragmentManager fm, FragmentTransaction ft, Fragment fragment) { } /** * A class describing information for a fragment-substitution, used when a fragment can act * in place of an activity. */ protected class FragmentReplaceInfo { private Class mFragmentClass; private String mFragmentTag; private int mContainerId; public FragmentReplaceInfo(Class fragmentClass, String fragmentTag, int containerId) { mFragmentClass = fragmentClass; mFragmentTag = fragmentTag; mContainerId = containerId; } public Class getFragmentClass() { return mFragmentClass; } public String getFragmentTag() { return mFragmentTag; } public int getContainerId() { return mContainerId; } } }
Java
/* * Copyright 2011 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.google.android.apps.iosched.ui; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.service.SyncService; import com.google.android.apps.iosched.util.AnalyticsUtils; import com.google.android.apps.iosched.util.DetachableResultReceiver; import com.google.android.apps.iosched.util.EulaHelper; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.view.Menu; import android.view.MenuItem; import android.widget.Toast; /** * Front-door {@link Activity} that displays high-level features the schedule application offers to * users. Depending on whether the device is a phone or an Android 3.0+ tablet, different layouts * will be used. For example, on a phone, the primary content is a {@link DashboardFragment}, * whereas on a tablet, both a {@link DashboardFragment} and a {@link TagStreamFragment} are * displayed. */ public class HomeActivity extends BaseActivity { private static final String TAG = "HomeActivity"; private TagStreamFragment mTagStreamFragment; private SyncStatusUpdaterFragment mSyncStatusUpdaterFragment; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (!EulaHelper.hasAcceptedEula(this)) { EulaHelper.showEula(false, this); } AnalyticsUtils.getInstance(this).trackPageView("/Home"); setContentView(R.layout.activity_home); getActivityHelper().setupActionBar(null, 0); FragmentManager fm = getSupportFragmentManager(); mTagStreamFragment = (TagStreamFragment) fm.findFragmentById(R.id.fragment_tag_stream); mSyncStatusUpdaterFragment = (SyncStatusUpdaterFragment) fm .findFragmentByTag(SyncStatusUpdaterFragment.TAG); if (mSyncStatusUpdaterFragment == null) { mSyncStatusUpdaterFragment = new SyncStatusUpdaterFragment(); fm.beginTransaction().add(mSyncStatusUpdaterFragment, SyncStatusUpdaterFragment.TAG).commit(); triggerRefresh(); } } @Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); getActivityHelper().setupHomeActivity(); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.refresh_menu_items, menu); super.onCreateOptionsMenu(menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == R.id.menu_refresh) { triggerRefresh(); return true; } return super.onOptionsItemSelected(item); } private void triggerRefresh() { final Intent intent = new Intent(Intent.ACTION_SYNC, null, this, SyncService.class); intent.putExtra(SyncService.EXTRA_STATUS_RECEIVER, mSyncStatusUpdaterFragment.mReceiver); startService(intent); if (mTagStreamFragment != null) { mTagStreamFragment.refresh(); } } private void updateRefreshStatus(boolean refreshing) { getActivityHelper().setRefreshActionButtonCompatState(refreshing); } /** * A non-UI fragment, retained across configuration changes, that updates its activity's UI * when sync status changes. */ public static class SyncStatusUpdaterFragment extends Fragment implements DetachableResultReceiver.Receiver { public static final String TAG = SyncStatusUpdaterFragment.class.getName(); private boolean mSyncing = false; private DetachableResultReceiver mReceiver; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setRetainInstance(true); mReceiver = new DetachableResultReceiver(new Handler()); mReceiver.setReceiver(this); } /** {@inheritDoc} */ public void onReceiveResult(int resultCode, Bundle resultData) { HomeActivity activity = (HomeActivity) getActivity(); if (activity == null) { return; } switch (resultCode) { case SyncService.STATUS_RUNNING: { mSyncing = true; break; } case SyncService.STATUS_FINISHED: { mSyncing = false; break; } case SyncService.STATUS_ERROR: { // Error happened down in SyncService, show as toast. mSyncing = false; final String errorText = getString(R.string.toast_sync_error, resultData .getString(Intent.EXTRA_TEXT)); Toast.makeText(activity, errorText, Toast.LENGTH_LONG).show(); break; } } activity.updateRefreshStatus(mSyncing); } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); ((HomeActivity) getActivity()).updateRefreshStatus(mSyncing); } } }
Java
/* * Copyright 2011 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.google.android.apps.iosched.ui; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.provider.ScheduleContract; import android.app.Activity; import android.content.Context; import android.database.Cursor; import android.graphics.drawable.ColorDrawable; import android.provider.BaseColumns; import android.view.View; import android.view.ViewGroup; import android.widget.CursorAdapter; import android.widget.ImageView; import android.widget.TextView; /** * A {@link android.widget.CursorAdapter} that renders a {@link TracksQuery}. */ public class TracksAdapter extends CursorAdapter { private static final int ALL_ITEM_ID = Integer.MAX_VALUE; private Activity mActivity; private boolean mHasAllItem; private int mPositionDisplacement; private boolean mIsSessions = true; public TracksAdapter(Activity activity) { super(activity, null); mActivity = activity; } public void setHasAllItem(boolean hasAllItem) { mHasAllItem = hasAllItem; mPositionDisplacement = mHasAllItem ? 1 : 0; } public void setIsSessions(boolean isSessions) { mIsSessions = isSessions; } @Override public int getCount() { return super.getCount() + mPositionDisplacement; } @Override public View getView(int position, View convertView, ViewGroup parent) { if (mHasAllItem && position == 0) { if (convertView == null) { convertView = mActivity.getLayoutInflater().inflate( R.layout.list_item_track, parent, false); } // Custom binding for the first item ((TextView) convertView.findViewById(android.R.id.text1)).setText( "(" + mActivity.getResources().getString(mIsSessions ? R.string.all_sessions_title : R.string.all_sandbox_title) + ")"); convertView.findViewById(android.R.id.icon1).setVisibility(View.INVISIBLE); return convertView; } return super.getView(position - mPositionDisplacement, convertView, parent); } @Override public Object getItem(int position) { if (mHasAllItem && position == 0) { return null; } return super.getItem(position - mPositionDisplacement); } @Override public long getItemId(int position) { if (mHasAllItem && position == 0) { return ALL_ITEM_ID; } return super.getItemId(position - mPositionDisplacement); } @Override public boolean isEnabled(int position) { if (mHasAllItem && position == 0) { return true; } return super.isEnabled(position - mPositionDisplacement); } @Override public int getViewTypeCount() { // Add an item type for the "All" view. return super.getViewTypeCount() + 1; } @Override public int getItemViewType(int position) { if (mHasAllItem && position == 0) { return getViewTypeCount() - 1; } return super.getItemViewType(position - mPositionDisplacement); } /** {@inheritDoc} */ @Override public View newView(Context context, Cursor cursor, ViewGroup parent) { return mActivity.getLayoutInflater().inflate(R.layout.list_item_track, parent, false); } /** {@inheritDoc} */ @Override public void bindView(View view, Context context, Cursor cursor) { final TextView textView = (TextView) view.findViewById(android.R.id.text1); textView.setText(cursor.getString(TracksQuery.TRACK_NAME)); // Assign track color to visible block final ImageView iconView = (ImageView) view.findViewById(android.R.id.icon1); iconView.setImageDrawable(new ColorDrawable(cursor.getInt(TracksQuery.TRACK_COLOR))); } /** {@link com.google.android.apps.iosched.provider.ScheduleContract.Tracks} query parameters. */ public interface TracksQuery { int _TOKEN = 0x1; String[] PROJECTION = { BaseColumns._ID, ScheduleContract.Tracks.TRACK_ID, ScheduleContract.Tracks.TRACK_NAME, ScheduleContract.Tracks.TRACK_ABSTRACT, ScheduleContract.Tracks.TRACK_COLOR, }; String[] PROJECTION_WITH_SESSIONS_COUNT = { BaseColumns._ID, ScheduleContract.Tracks.TRACK_ID, ScheduleContract.Tracks.TRACK_NAME, ScheduleContract.Tracks.TRACK_ABSTRACT, ScheduleContract.Tracks.TRACK_COLOR, ScheduleContract.Tracks.SESSIONS_COUNT, }; String[] PROJECTION_WITH_VENDORS_COUNT = { BaseColumns._ID, ScheduleContract.Tracks.TRACK_ID, ScheduleContract.Tracks.TRACK_NAME, ScheduleContract.Tracks.TRACK_ABSTRACT, ScheduleContract.Tracks.TRACK_COLOR, ScheduleContract.Tracks.VENDORS_COUNT, }; int _ID = 0; int TRACK_ID = 1; int TRACK_NAME = 2; int TRACK_ABSTRACT = 3; int TRACK_COLOR = 4; } }
Java
/* * Copyright 2011 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.google.android.apps.iosched.ui; import android.os.Bundle; import android.support.v4.app.Fragment; public class TagStreamActivity extends BaseSinglePaneActivity { @Override protected Fragment onCreatePane() { return new TagStreamFragment(); } @Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); getActivityHelper().setupSubActivity(); } }
Java
/* * Copyright 2011 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. */ /** * ATTENTION: Consider using the 'ViewPager' widget, available in the * Android Compatibility Package, r3: * * http://developer.android.com/sdk/compatibility-library.html */ package com.google.android.apps.iosched.ui.widget; import com.google.android.apps.iosched.util.MotionEventUtils; import com.google.android.apps.iosched.util.ReflectionUtils; import android.content.Context; import android.graphics.Canvas; import android.graphics.Rect; import android.graphics.drawable.Drawable; import android.os.Parcel; import android.os.Parcelable; import android.util.AttributeSet; import android.util.Log; import android.view.MotionEvent; import android.view.VelocityTracker; import android.view.View; import android.view.ViewConfiguration; import android.view.ViewGroup; import android.view.ViewParent; import android.widget.Scroller; import java.util.ArrayList; /** * A {@link android.view.ViewGroup} that shows one child at a time, allowing the user to swipe * horizontally to page between other child views. Based on <code>Workspace.java</code> in the * <code>Launcher.git</code> AOSP project. * * An improved version of this UI widget named 'ViewPager' is now available in the * <a href="http://developer.android.com/sdk/compatibility-library.html">Android Compatibility * Package, r3</a>. */ public class Workspace extends ViewGroup { private static final String TAG = "Workspace"; private static final int INVALID_SCREEN = -1; /** * The velocity at which a fling gesture will cause us to snap to the next screen */ private static final int SNAP_VELOCITY = 500; /** * The user needs to drag at least this much for it to be considered a fling gesture. This * reduces the chance of a random twitch sending the user to the next screen. */ // TODO: refactor private static final int MIN_LENGTH_FOR_FLING = 100; private int mDefaultScreen; private boolean mFirstLayout = true; private boolean mHasLaidOut = false; private int mCurrentScreen; private int mNextScreen = INVALID_SCREEN; private Scroller mScroller; private VelocityTracker mVelocityTracker; /** * X position of the active pointer when it was first pressed down. */ private float mDownMotionX; /** * Y position of the active pointer when it was first pressed down. */ private float mDownMotionY; /** * This view's X scroll offset when the active pointer was first pressed down. */ private int mDownScrollX; private final static int TOUCH_STATE_REST = 0; private final static int TOUCH_STATE_SCROLLING = 1; private int mTouchState = TOUCH_STATE_REST; private OnLongClickListener mLongClickListener; private boolean mAllowLongPress = true; private int mTouchSlop; private int mPagingTouchSlop; private int mMaximumVelocity; private static final int INVALID_POINTER = -1; private int mActivePointerId = INVALID_POINTER; private Drawable mSeparatorDrawable; private OnScreenChangeListener mOnScreenChangeListener; private OnScrollListener mOnScrollListener; private boolean mLocked; private int mDeferredScreenChange = -1; private boolean mDeferredScreenChangeFast = false; private boolean mDeferredNotify = false; private boolean mIgnoreChildFocusRequests; private boolean mIsVerbose = false; public interface OnScreenChangeListener { void onScreenChanged(View newScreen, int newScreenIndex); void onScreenChanging(View newScreen, int newScreenIndex); } public interface OnScrollListener { void onScroll(float screenFraction); } /** * Used to inflate the com.google.android.ext.workspace.Workspace from XML. * * @param context The application's context. * @param attrs The attributes set containing the com.google.android.ext.workspace.Workspace's * customization values. */ public Workspace(Context context, AttributeSet attrs) { super(context, attrs); mDefaultScreen = 0; mLocked = false; setHapticFeedbackEnabled(false); initWorkspace(); mIsVerbose = Log.isLoggable(TAG, Log.VERBOSE); } /** * Initializes various states for this workspace. */ private void initWorkspace() { mScroller = new Scroller(getContext()); mCurrentScreen = mDefaultScreen; final ViewConfiguration configuration = ViewConfiguration.get(getContext()); mTouchSlop = configuration.getScaledTouchSlop(); mMaximumVelocity = configuration.getScaledMaximumFlingVelocity(); mPagingTouchSlop = ReflectionUtils.callWithDefault(configuration, "getScaledPagingTouchSlop", mTouchSlop * 2); } /** * Returns the index of the currently displayed screen. */ int getCurrentScreen() { return mCurrentScreen; } /** * Returns the number of screens currently contained in this Workspace. */ int getScreenCount() { int childCount = getChildCount(); if (mSeparatorDrawable != null) { return (childCount + 1) / 2; } return childCount; } View getScreenAt(int index) { if (mSeparatorDrawable == null) { return getChildAt(index); } return getChildAt(index * 2); } int getScrollWidth() { int w = getWidth(); if (mSeparatorDrawable != null) { w += mSeparatorDrawable.getIntrinsicWidth(); } return w; } void handleScreenChangeCompletion(int currentScreen) { mCurrentScreen = currentScreen; View screen = getScreenAt(mCurrentScreen); //screen.requestFocus(); try { ReflectionUtils.tryInvoke(screen, "dispatchDisplayHint", new Class[]{int.class}, View.VISIBLE); invalidate(); } catch (NullPointerException e) { Log.e(TAG, "Caught NullPointerException", e); } notifyScreenChangeListener(mCurrentScreen, true); } void notifyScreenChangeListener(int whichScreen, boolean changeComplete) { if (mOnScreenChangeListener != null) { if (changeComplete) mOnScreenChangeListener.onScreenChanged(getScreenAt(whichScreen), whichScreen); else mOnScreenChangeListener.onScreenChanging(getScreenAt(whichScreen), whichScreen); } if (mOnScrollListener != null) { mOnScrollListener.onScroll(getCurrentScreenFraction()); } } /** * Registers the specified listener on each screen contained in this workspace. * * @param listener The listener used to respond to long clicks. */ @Override public void setOnLongClickListener(OnLongClickListener listener) { mLongClickListener = listener; final int count = getScreenCount(); for (int i = 0; i < count; i++) { getScreenAt(i).setOnLongClickListener(listener); } } @Override public void computeScroll() { if (mScroller.computeScrollOffset()) { scrollTo(mScroller.getCurrX(), mScroller.getCurrY()); if (mOnScrollListener != null) { mOnScrollListener.onScroll(getCurrentScreenFraction()); } postInvalidate(); } else if (mNextScreen != INVALID_SCREEN) { // The scroller has finished. handleScreenChangeCompletion(Math.max(0, Math.min(mNextScreen, getScreenCount() - 1))); mNextScreen = INVALID_SCREEN; } } @Override protected void dispatchDraw(Canvas canvas) { boolean restore = false; int restoreCount = 0; // ViewGroup.dispatchDraw() supports many features we don't need: // clip to padding, layout animation, animation listener, disappearing // children, etc. The following implementation attempts to fast-track // the drawing dispatch by drawing only what we know needs to be drawn. boolean fastDraw = mTouchState != TOUCH_STATE_SCROLLING && mNextScreen == INVALID_SCREEN; // If we are not scrolling or flinging, draw only the current screen if (fastDraw) { if (getScreenAt(mCurrentScreen) != null) { drawChild(canvas, getScreenAt(mCurrentScreen), getDrawingTime()); } } else { final long drawingTime = getDrawingTime(); // If we are flinging, draw only the current screen and the target screen if (mNextScreen >= 0 && mNextScreen < getScreenCount() && Math.abs(mCurrentScreen - mNextScreen) == 1) { drawChild(canvas, getScreenAt(mCurrentScreen), drawingTime); drawChild(canvas, getScreenAt(mNextScreen), drawingTime); } else { // If we are scrolling, draw all of our children final int count = getChildCount(); for (int i = 0; i < count; i++) { drawChild(canvas, getChildAt(i), drawingTime); } } } if (restore) { canvas.restoreToCount(restoreCount); } } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); // The children are given the same width and height as the workspace final int count = getChildCount(); for (int i = 0; i < count; i++) { if (mSeparatorDrawable != null && (i & 1) == 1) { // separator getChildAt(i).measure(mSeparatorDrawable.getIntrinsicWidth(), heightMeasureSpec); } else { getChildAt(i).measure(widthMeasureSpec, heightMeasureSpec); } } if (mFirstLayout) { setHorizontalScrollBarEnabled(false); int width = MeasureSpec.getSize(widthMeasureSpec); if (mSeparatorDrawable != null) { width += mSeparatorDrawable.getIntrinsicWidth(); } scrollTo(mCurrentScreen * width, 0); setHorizontalScrollBarEnabled(true); mFirstLayout = false; } } @Override protected void onLayout(boolean changed, int left, int top, int right, int bottom) { int childLeft = 0; final int count = getChildCount(); for (int i = 0; i < count; i++) { final View child = getChildAt(i); if (child.getVisibility() != View.GONE) { final int childWidth = child.getMeasuredWidth(); child.layout(childLeft, 0, childLeft + childWidth, child.getMeasuredHeight()); childLeft += childWidth; } } mHasLaidOut = true; if (mDeferredScreenChange >= 0) { snapToScreen(mDeferredScreenChange, mDeferredScreenChangeFast, mDeferredNotify); mDeferredScreenChange = -1; mDeferredScreenChangeFast = false; } } @Override public boolean requestChildRectangleOnScreen(View child, Rect rectangle, boolean immediate) { int screen = indexOfChild(child); if (mIgnoreChildFocusRequests && !mScroller.isFinished()) { Log.w(TAG, "Ignoring child focus request: request " + mCurrentScreen + " -> " + screen); return false; } if (screen != mCurrentScreen || !mScroller.isFinished()) { snapToScreen(screen); return true; } return false; } @Override protected boolean onRequestFocusInDescendants(int direction, Rect previouslyFocusedRect) { int focusableScreen; if (mNextScreen != INVALID_SCREEN) { focusableScreen = mNextScreen; } else { focusableScreen = mCurrentScreen; } View v = getScreenAt(focusableScreen); if (v != null) { return v.requestFocus(direction, previouslyFocusedRect); } return false; } @Override public boolean dispatchUnhandledMove(View focused, int direction) { if (direction == View.FOCUS_LEFT) { if (getCurrentScreen() > 0) { snapToScreen(getCurrentScreen() - 1); return true; } } else if (direction == View.FOCUS_RIGHT) { if (getCurrentScreen() < getScreenCount() - 1) { snapToScreen(getCurrentScreen() + 1); return true; } } return super.dispatchUnhandledMove(focused, direction); } @Override public void addFocusables(ArrayList<View> views, int direction, int focusableMode) { View focusableSourceScreen = null; if (mCurrentScreen >= 0 && mCurrentScreen < getScreenCount()) { focusableSourceScreen = getScreenAt(mCurrentScreen); } if (direction == View.FOCUS_LEFT) { if (mCurrentScreen > 0) { focusableSourceScreen = getScreenAt(mCurrentScreen - 1); } } else if (direction == View.FOCUS_RIGHT) { if (mCurrentScreen < getScreenCount() - 1) { focusableSourceScreen = getScreenAt(mCurrentScreen + 1); } } if (focusableSourceScreen != null) { focusableSourceScreen.addFocusables(views, direction, focusableMode); } } /** * If one of our descendant views decides that it could be focused now, only pass that along if * it's on the current screen. * * This happens when live folders requery, and if they're off screen, they end up calling * requestFocus, which pulls it on screen. */ @Override public void focusableViewAvailable(View focused) { View current = getScreenAt(mCurrentScreen); View v = focused; ViewParent parent; while (true) { if (v == current) { super.focusableViewAvailable(focused); return; } if (v == this) { return; } parent = v.getParent(); if (parent instanceof View) { v = (View) v.getParent(); } else { return; } } } @Override public boolean onInterceptTouchEvent(MotionEvent ev) { /* * This method JUST determines whether we want to intercept the motion. * If we return true, onTouchEvent will be called and we do the actual * scrolling there. */ // Begin tracking velocity even before we have intercepted touch events. if (mVelocityTracker == null) { mVelocityTracker = VelocityTracker.obtain(); } mVelocityTracker.addMovement(ev); /* * Shortcut the most recurring case: the user is in the dragging * state and he is moving his finger. We want to intercept this * motion. */ final int action = ev.getAction(); if (mIsVerbose) { Log.v(TAG, "onInterceptTouchEvent: " + (ev.getAction() & MotionEventUtils.ACTION_MASK)); } if (((action & MotionEventUtils.ACTION_MASK) == MotionEvent.ACTION_MOVE) && (mTouchState == TOUCH_STATE_SCROLLING)) { if (mIsVerbose) { Log.v(TAG, "Intercepting touch events"); } return true; } switch (action & MotionEventUtils.ACTION_MASK) { case MotionEvent.ACTION_MOVE: { if (mLocked) { // we're locked on the current screen, don't allow moving break; } /* * Locally do absolute value. mDownMotionX is set to the y value * of the down event. */ final int pointerIndex = MotionEventUtils.findPointerIndex(ev, mActivePointerId); final float x = MotionEventUtils.getX(ev, pointerIndex); final float y = MotionEventUtils.getY(ev, pointerIndex); final int xDiff = (int) Math.abs(x - mDownMotionX); final int yDiff = (int) Math.abs(y - mDownMotionY); boolean xPaged = xDiff > mPagingTouchSlop; boolean xMoved = xDiff > mTouchSlop; boolean yMoved = yDiff > mTouchSlop; if (xMoved || yMoved) { if (xPaged) { // Scroll if the user moved far enough along the X axis mTouchState = TOUCH_STATE_SCROLLING; } // Either way, cancel any pending longpress if (mAllowLongPress) { mAllowLongPress = false; // Try canceling the long press. It could also have been scheduled // by a distant descendant, so use the mAllowLongPress flag to block // everything final View currentScreen = getScreenAt(mCurrentScreen); if (currentScreen != null) { currentScreen.cancelLongPress(); } } } break; } case MotionEvent.ACTION_DOWN: { final float x = ev.getX(); final float y = ev.getY(); // Remember location of down touch mDownMotionX = x; mDownMotionY = y; mDownScrollX = getScrollX(); mActivePointerId = MotionEventUtils.getPointerId(ev, 0); mAllowLongPress = true; /* * If being flinged and user touches the screen, initiate drag; * otherwise don't. mScroller.isFinished should be false when * being flinged. */ mTouchState = mScroller.isFinished() ? TOUCH_STATE_REST : TOUCH_STATE_SCROLLING; break; } case MotionEvent.ACTION_CANCEL: case MotionEvent.ACTION_UP: // Release the drag mTouchState = TOUCH_STATE_REST; mAllowLongPress = false; mActivePointerId = INVALID_POINTER; if (mVelocityTracker != null) { mVelocityTracker.recycle(); mVelocityTracker = null; } break; case MotionEventUtils.ACTION_POINTER_UP: onSecondaryPointerUp(ev); break; } /* * The only time we want to intercept motion events is if we are in the * drag mode. */ boolean intercept = mTouchState != TOUCH_STATE_REST; if (mIsVerbose) { Log.v(TAG, "Intercepting touch events: " + Boolean.toString(intercept)); } return intercept; } void onSecondaryPointerUp(MotionEvent ev) { final int pointerIndex = (ev.getAction() & MotionEventUtils.ACTION_POINTER_INDEX_MASK) >> MotionEventUtils.ACTION_POINTER_INDEX_SHIFT; final int pointerId = MotionEventUtils.getPointerId(ev, pointerIndex); if (pointerId == mActivePointerId) { // This was our active pointer going up. Choose a new // active pointer and adjust accordingly. // TODO: Make this decision more intelligent. final int newPointerIndex = pointerIndex == 0 ? 1 : 0; mDownMotionX = MotionEventUtils.getX(ev, newPointerIndex); mDownMotionX = MotionEventUtils.getY(ev, newPointerIndex); mDownScrollX = getScrollX(); mActivePointerId = MotionEventUtils.getPointerId(ev, newPointerIndex); if (mVelocityTracker != null) { mVelocityTracker.clear(); } } } @Override public void requestChildFocus(View child, View focused) { super.requestChildFocus(child, focused); int screen = indexOfChild(child); if (mSeparatorDrawable != null) { screen /= 2; } if (screen >= 0 && !isInTouchMode()) { snapToScreen(screen); } } @Override public boolean onTouchEvent(MotionEvent ev) { if (mIsVerbose) { Log.v(TAG, "onTouchEvent: " + (ev.getAction() & MotionEventUtils.ACTION_MASK)); } if (mVelocityTracker == null) { mVelocityTracker = VelocityTracker.obtain(); } mVelocityTracker.addMovement(ev); final int action = ev.getAction(); switch (action & MotionEventUtils.ACTION_MASK) { case MotionEvent.ACTION_DOWN: // If being flinged and user touches, stop the fling. isFinished // will be false if being flinged. if (!mScroller.isFinished()) { mScroller.abortAnimation(); } // Remember where the motion event started mDownMotionX = ev.getX(); mDownMotionY = ev.getY(); mDownScrollX = getScrollX(); mActivePointerId = MotionEventUtils.getPointerId(ev, 0); break; case MotionEvent.ACTION_MOVE: if (mIsVerbose) { Log.v(TAG, "mTouchState=" + mTouchState); } if (mTouchState == TOUCH_STATE_SCROLLING) { // Scroll to follow the motion event final int pointerIndex = MotionEventUtils .findPointerIndex(ev, mActivePointerId); final float x = MotionEventUtils.getX(ev, pointerIndex); final View lastChild = getChildAt(getChildCount() - 1); final int maxScrollX = lastChild.getRight() - getWidth(); scrollTo(Math.max(0, Math.min(maxScrollX, (int)(mDownScrollX + mDownMotionX - x ))), 0); if (mOnScrollListener != null) { mOnScrollListener.onScroll(getCurrentScreenFraction()); } } else if (mTouchState == TOUCH_STATE_REST) { if (mLocked) { // we're locked on the current screen, don't allow moving break; } /* * Locally do absolute value. mLastMotionX is set to the y value * of the down event. */ final int pointerIndex = MotionEventUtils.findPointerIndex(ev, mActivePointerId); final float x = MotionEventUtils.getX(ev, pointerIndex); final float y = MotionEventUtils.getY(ev, pointerIndex); final int xDiff = (int) Math.abs(x - mDownMotionX); final int yDiff = (int) Math.abs(y - mDownMotionY); boolean xPaged = xDiff > mPagingTouchSlop; boolean xMoved = xDiff > mTouchSlop; boolean yMoved = yDiff > mTouchSlop; if (xMoved || yMoved) { if (xPaged) { // Scroll if the user moved far enough along the X axis mTouchState = TOUCH_STATE_SCROLLING; } // Either way, cancel any pending longpress if (mAllowLongPress) { mAllowLongPress = false; // Try canceling the long press. It could also have been scheduled // by a distant descendant, so use the mAllowLongPress flag to block // everything final View currentScreen = getScreenAt(mCurrentScreen); if (currentScreen != null) { currentScreen.cancelLongPress(); } } } } break; case MotionEvent.ACTION_UP: if (mTouchState == TOUCH_STATE_SCROLLING) { final int activePointerId = mActivePointerId; final int pointerIndex = MotionEventUtils.findPointerIndex(ev, activePointerId); final float x = MotionEventUtils.getX(ev, pointerIndex); final VelocityTracker velocityTracker = mVelocityTracker; velocityTracker.computeCurrentVelocity(1000, mMaximumVelocity); //TODO(minsdk8): int velocityX = (int) MotionEventUtils.getXVelocity(velocityTracker, activePointerId); int velocityX = (int) velocityTracker.getXVelocity(); boolean isFling = Math.abs(mDownMotionX - x) > MIN_LENGTH_FOR_FLING; final float scrolledPos = getCurrentScreenFraction(); final int whichScreen = Math.round(scrolledPos); if (isFling && mIsVerbose) { Log.v(TAG, "isFling, whichScreen=" + whichScreen + " scrolledPos=" + scrolledPos + " mCurrentScreen=" + mCurrentScreen + " velocityX=" + velocityX); } if (isFling && velocityX > SNAP_VELOCITY && mCurrentScreen > 0) { // Fling hard enough to move left // Don't fling across more than one screen at a time. final int bound = scrolledPos <= whichScreen ? mCurrentScreen - 1 : mCurrentScreen; snapToScreen(Math.min(whichScreen, bound)); } else if (isFling && velocityX < -SNAP_VELOCITY && mCurrentScreen < getChildCount() - 1) { // Fling hard enough to move right // Don't fling across more than one screen at a time. final int bound = scrolledPos >= whichScreen ? mCurrentScreen + 1 : mCurrentScreen; snapToScreen(Math.max(whichScreen, bound)); } else { snapToDestination(); } } else { performClick(); } mTouchState = TOUCH_STATE_REST; mActivePointerId = INVALID_POINTER; // Intentially fall through to cancel case MotionEvent.ACTION_CANCEL: mTouchState = TOUCH_STATE_REST; mActivePointerId = INVALID_POINTER; if (mVelocityTracker != null) { mVelocityTracker.recycle(); mVelocityTracker = null; } break; case MotionEventUtils.ACTION_POINTER_UP: onSecondaryPointerUp(ev); break; } return true; } /** * Returns the current scroll position as a float value from 0 to the number of screens. * Fractional values indicate that the user is mid-scroll or mid-fling, and whole values * indicate that the Workspace is currently snapped to a screen. */ float getCurrentScreenFraction() { if (!mHasLaidOut) { return mCurrentScreen; } final int scrollX = getScrollX(); final int screenWidth = getWidth(); return (float) scrollX / screenWidth; } void snapToDestination() { final int screenWidth = getScrollWidth(); final int whichScreen = (getScrollX() + (screenWidth / 2)) / screenWidth; snapToScreen(whichScreen); } void snapToScreen(int whichScreen) { snapToScreen(whichScreen, false, true); } void snapToScreen(int whichScreen, boolean fast, boolean notify) { if (!mHasLaidOut) { // Can't handle scrolling until we are laid out. mDeferredScreenChange = whichScreen; mDeferredScreenChangeFast = fast; mDeferredNotify = notify; return; } if (mIsVerbose) { Log.v(TAG, "Snapping to screen: " + whichScreen); } whichScreen = Math.max(0, Math.min(whichScreen, getScreenCount() - 1)); final int screenDelta = Math.abs(whichScreen - mCurrentScreen); final boolean screenChanging = (mNextScreen != INVALID_SCREEN && mNextScreen != whichScreen) || (mCurrentScreen != whichScreen); mNextScreen = whichScreen; View focusedChild = getFocusedChild(); boolean setTabFocus = false; if (focusedChild != null && screenDelta != 0 && focusedChild == getScreenAt( mCurrentScreen)) { // clearing the focus of the child will cause focus to jump to the tabs, // which will in turn cause snapToScreen to be called again with a different // value. To prevent this, we temporarily disable the OnTabClickListener //if (mTabRow != null) { // mTabRow.setOnTabClickListener(null); //} //focusedChild.clearFocus(); //setTabRow(mTabRow); // restore the listener //setTabFocus = true; } final int newX = whichScreen * getScrollWidth(); final int sX = getScrollX(); final int delta = newX - sX; int duration = screenDelta * 300; awakenScrollBars(duration); if (duration == 0) { duration = Math.abs(delta); } if (fast) { duration = 0; } if (mNextScreen != mCurrentScreen) { // make the current listview hide its filter popup final View screenAt = getScreenAt(mCurrentScreen); if (screenAt != null) { ReflectionUtils.tryInvoke(screenAt, "dispatchDisplayHint", new Class[]{int.class}, View.INVISIBLE); } else { Log.e(TAG, "Screen at index was null. mCurrentScreen = " + mCurrentScreen); return; } // showing the filter popup for the next listview needs to be delayed // until we've fully moved to that listview, since otherwise the // popup will appear at the wrong place on the screen //removeCallbacks(mFilterWindowEnabler); //postDelayed(mFilterWindowEnabler, duration + 10); // NOTE: moved to computeScroll and handleScreenChangeCompletion() } if (!mScroller.isFinished()) { mScroller.abortAnimation(); } mScroller.startScroll(sX, 0, delta, 0, duration); if (screenChanging && notify) { notifyScreenChangeListener(mNextScreen, false); } invalidate(); } @Override protected Parcelable onSaveInstanceState() { final SavedState state = new SavedState(super.onSaveInstanceState()); state.currentScreen = mCurrentScreen; return state; } @Override protected void onRestoreInstanceState(Parcelable state) { SavedState savedState = (SavedState) state; super.onRestoreInstanceState(savedState.getSuperState()); if (savedState.currentScreen != -1) { snapToScreen(savedState.currentScreen, true, true); } } /** * @return True is long presses are still allowed for the current touch */ boolean allowLongPress() { return mAllowLongPress; } /** * Register a callback to be invoked when the screen is changed, either programmatically or via * user interaction. Will automatically trigger a callback. * * @param screenChangeListener The callback. */ public void setOnScreenChangeListener(OnScreenChangeListener screenChangeListener) { setOnScreenChangeListener(screenChangeListener, true); } /** * Register a callback to be invoked when the screen is changed, either programmatically or via * user interaction. * * @param screenChangeListener The callback. * @param notifyImmediately Whether to trigger a notification immediately */ public void setOnScreenChangeListener(OnScreenChangeListener screenChangeListener, boolean notifyImmediately) { mOnScreenChangeListener = screenChangeListener; if (mOnScreenChangeListener != null && notifyImmediately) { mOnScreenChangeListener.onScreenChanged(getScreenAt(mCurrentScreen), mCurrentScreen); } } /** * Register a callback to be invoked when this Workspace is mid-scroll or mid-fling, either * due to user interaction or programmatic changes in the current screen index. * * @param scrollListener The callback. * @param notifyImmediately Whether to trigger a notification immediately */ public void setOnScrollListener(OnScrollListener scrollListener, boolean notifyImmediately) { mOnScrollListener = scrollListener; if (mOnScrollListener != null && notifyImmediately) { mOnScrollListener.onScroll(getCurrentScreenFraction()); } } /** * Scrolls to the given screen. */ public void setCurrentScreen(int screenIndex) { snapToScreen(Math.max(0, Math.min(getScreenCount() - 1, screenIndex))); } /** * Scrolls to the given screen fast (no matter how large the scroll distance is) * * @param screenIndex */ public void setCurrentScreenNow(int screenIndex) { setCurrentScreenNow(screenIndex, true); } public void setCurrentScreenNow(int screenIndex, boolean notify) { snapToScreen(Math.max(0, Math.min(getScreenCount() - 1, screenIndex)), true, notify); } /** * Scrolls to the screen adjacent to the current screen on the left, if it exists. This method * is a no-op if the Workspace is currently locked. */ public void scrollLeft() { if (mLocked) { return; } if (mScroller.isFinished()) { if (mCurrentScreen > 0) { snapToScreen(mCurrentScreen - 1); } } else { if (mNextScreen > 0) { snapToScreen(mNextScreen - 1); } } } /** * Scrolls to the screen adjacent to the current screen on the right, if it exists. This method * is a no-op if the Workspace is currently locked. */ public void scrollRight() { if (mLocked) { return; } if (mScroller.isFinished()) { if (mCurrentScreen < getChildCount() - 1) { snapToScreen(mCurrentScreen + 1); } } else { if (mNextScreen < getChildCount() - 1) { snapToScreen(mNextScreen + 1); } } } /** * If set, invocations of requestChildRectangleOnScreen() will be ignored. */ public void setIgnoreChildFocusRequests(boolean mIgnoreChildFocusRequests) { this.mIgnoreChildFocusRequests = mIgnoreChildFocusRequests; } public void markViewSelected(View v) { mCurrentScreen = indexOfChild(v); } /** * Locks the current screen, preventing users from changing screens by swiping. */ public void lockCurrentScreen() { mLocked = true; } /** * Unlocks the current screen, if it was previously locked. See also {@link * Workspace#lockCurrentScreen()}. */ public void unlockCurrentScreen() { mLocked = false; } /** * Sets the resource ID of the separator drawable to use between adjacent screens. */ public void setSeparator(int resId) { if (mSeparatorDrawable != null && resId == 0) { // remove existing separators mSeparatorDrawable = null; int num = getChildCount(); for (int i = num - 2; i > 0; i -= 2) { removeViewAt(i); } requestLayout(); } else if (resId != 0) { // add or update separators if (mSeparatorDrawable == null) { // add int numsep = getChildCount(); int insertIndex = 1; mSeparatorDrawable = getResources().getDrawable(resId); for (int i = 1; i < numsep; i++) { View v = new View(getContext()); v.setBackgroundDrawable(mSeparatorDrawable); LayoutParams lp = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.FILL_PARENT); v.setLayoutParams(lp); addView(v, insertIndex); insertIndex += 2; } requestLayout(); } else { // update mSeparatorDrawable = getResources().getDrawable(resId); int num = getChildCount(); for (int i = num - 2; i > 0; i -= 2) { getChildAt(i).setBackgroundDrawable(mSeparatorDrawable); } requestLayout(); } } } private static class SavedState extends BaseSavedState { int currentScreen = -1; SavedState(Parcelable superState) { super(superState); } private SavedState(Parcel in) { super(in); currentScreen = in.readInt(); } @Override public void writeToParcel(Parcel out, int flags) { super.writeToParcel(out, flags); out.writeInt(currentScreen); } 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 void addViewToFront(View v) { mCurrentScreen++; addView(v, 0); } public void removeViewFromFront() { mCurrentScreen--; removeViewAt(0); } public void addViewToBack(View v) { addView(v); } public void removeViewFromBack() { removeViewAt(getChildCount() - 1); } }
Java
/* * Copyright 2011 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.google.android.apps.iosched.ui.widget; import android.content.Context; import android.util.AttributeSet; import android.widget.ScrollView; /** * A custom ScrollView that can notify a scroll listener when scrolled. */ public class ObservableScrollView extends ScrollView { private OnScrollListener mScrollListener; public ObservableScrollView(Context context, AttributeSet attrs) { super(context, attrs); } @Override protected void onScrollChanged(int l, int t, int oldl, int oldt) { super.onScrollChanged(l, t, oldl, oldt); if (mScrollListener != null) { mScrollListener.onScrollChanged(this); } } public boolean isScrollPossible() { return computeVerticalScrollRange() > getHeight(); } public void setOnScrollListener(OnScrollListener listener) { mScrollListener = listener; } public static interface OnScrollListener { public void onScrollChanged(ObservableScrollView view); } }
Java
/* * Copyright 2011 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.google.android.apps.iosched.ui.widget; import com.google.android.apps.iosched.R; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.PorterDuff; import android.graphics.PorterDuffXfermode; import android.graphics.Rect; import android.graphics.RectF; import android.graphics.drawable.Drawable; import android.util.AttributeSet; import android.widget.ImageView; /** * An {@link ImageView} that draws its contents inside a mask and draws a border drawable on top. * This is useful for applying a beveled look to image contents, but is also flexible enough for use * with other desired aesthetics. */ public class BezelImageView extends ImageView { private static final String TAG = "BezelImageView"; private Paint mMaskedPaint; private Paint mCopyPaint; private Rect mBounds; private RectF mBoundsF; private Drawable mBorderDrawable; private Drawable mMaskDrawable; public BezelImageView(Context context) { this(context, null); } public BezelImageView(Context context, AttributeSet attrs) { this(context, attrs, 0); } public BezelImageView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); // Attribute initialization final TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.BezelImageView, defStyle, 0); mMaskDrawable = a.getDrawable(R.styleable.BezelImageView_maskDrawable); if (mMaskDrawable == null) { mMaskDrawable = getResources().getDrawable(R.drawable.bezel_mask); } mMaskDrawable.setCallback(this); mBorderDrawable = a.getDrawable(R.styleable.BezelImageView_borderDrawable); if (mBorderDrawable == null) { mBorderDrawable = getResources().getDrawable(R.drawable.bezel_border); } mBorderDrawable.setCallback(this); a.recycle(); // Other initialization mMaskedPaint = new Paint(); mMaskedPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_ATOP)); mCopyPaint = new Paint(); } @Override protected boolean setFrame(int l, int t, int r, int b) { final boolean changed = super.setFrame(l, t, r, b); mBounds = new Rect(0, 0, r - l, b - t); mBoundsF = new RectF(mBounds); mBorderDrawable.setBounds(mBounds); mMaskDrawable.setBounds(mBounds); return changed; } @Override protected void onDraw(Canvas canvas) { int sc = canvas.saveLayer(mBoundsF, mCopyPaint, Canvas.HAS_ALPHA_LAYER_SAVE_FLAG | Canvas.FULL_COLOR_LAYER_SAVE_FLAG); mMaskDrawable.draw(canvas); canvas.saveLayer(mBoundsF, mMaskedPaint, 0); super.onDraw(canvas); canvas.restoreToCount(sc); mBorderDrawable.draw(canvas); } @Override protected void drawableStateChanged() { super.drawableStateChanged(); if (mBorderDrawable.isStateful()) { mBorderDrawable.setState(getDrawableState()); } if (mMaskDrawable.isStateful()) { mMaskDrawable.setState(getDrawableState()); } // TODO: is this the right place to invalidate? invalidate(); } }
Java