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 com.actionbarsherlock.R; import android.content.Context; import android.content.res.TypedArray; import android.graphics.drawable.Drawable; import android.util.AttributeSet; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RadioButton; import android.widget.TextView; /** * The item view for each item in the ListView-based MenuViews. */ public class ListMenuItemView extends LinearLayout implements MenuView.ItemView { private MenuItemImpl mItemData; private ImageView mIconView; private RadioButton mRadioButton; private TextView mTitleView; private CheckBox mCheckBox; private TextView mShortcutView; private Drawable mBackground; private int mTextAppearance; private Context mTextAppearanceContext; private boolean mPreserveIconSpacing; //UNUSED private int mMenuType; private LayoutInflater mInflater; private boolean mForceShowIcon; final Context mContext; public ListMenuItemView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs); mContext = context; TypedArray a = context.obtainStyledAttributes( attrs, R.styleable.SherlockMenuView, defStyle, 0); mBackground = a.getDrawable(R.styleable.SherlockMenuView_itemBackground); mTextAppearance = a.getResourceId(R.styleable. SherlockMenuView_itemTextAppearance, -1); mPreserveIconSpacing = a.getBoolean( R.styleable.SherlockMenuView_preserveIconSpacing, false); mTextAppearanceContext = context; a.recycle(); } public ListMenuItemView(Context context, AttributeSet attrs) { this(context, attrs, 0); } @Override protected void onFinishInflate() { super.onFinishInflate(); setBackgroundDrawable(mBackground); mTitleView = (TextView) findViewById(R.id.abs__title); if (mTextAppearance != -1) { mTitleView.setTextAppearance(mTextAppearanceContext, mTextAppearance); } mShortcutView = (TextView) findViewById(R.id.abs__shortcut); } public void initialize(MenuItemImpl itemData, int menuType) { mItemData = itemData; //UNUSED mMenuType = menuType; setVisibility(itemData.isVisible() ? View.VISIBLE : View.GONE); setTitle(itemData.getTitleForItemView(this)); setCheckable(itemData.isCheckable()); setShortcut(itemData.shouldShowShortcut(), itemData.getShortcut()); setIcon(itemData.getIcon()); setEnabled(itemData.isEnabled()); } public void setForceShowIcon(boolean forceShow) { mPreserveIconSpacing = mForceShowIcon = forceShow; } public void setTitle(CharSequence title) { if (title != null) { mTitleView.setText(title); if (mTitleView.getVisibility() != VISIBLE) mTitleView.setVisibility(VISIBLE); } else { if (mTitleView.getVisibility() != GONE) mTitleView.setVisibility(GONE); } } public MenuItemImpl getItemData() { return mItemData; } public void setCheckable(boolean checkable) { if (!checkable && mRadioButton == null && mCheckBox == null) { return; } if (mRadioButton == null) { insertRadioButton(); } if (mCheckBox == null) { insertCheckBox(); } // Depending on whether its exclusive check or not, the checkbox or // radio button will be the one in use (and the other will be otherCompoundButton) final CompoundButton compoundButton; final CompoundButton otherCompoundButton; if (mItemData.isExclusiveCheckable()) { compoundButton = mRadioButton; otherCompoundButton = mCheckBox; } else { compoundButton = mCheckBox; otherCompoundButton = mRadioButton; } if (checkable) { compoundButton.setChecked(mItemData.isChecked()); final int newVisibility = checkable ? VISIBLE : GONE; if (compoundButton.getVisibility() != newVisibility) { compoundButton.setVisibility(newVisibility); } // Make sure the other compound button isn't visible if (otherCompoundButton.getVisibility() != GONE) { otherCompoundButton.setVisibility(GONE); } } else { mCheckBox.setVisibility(GONE); mRadioButton.setVisibility(GONE); } } public void setChecked(boolean checked) { CompoundButton compoundButton; if (mItemData.isExclusiveCheckable()) { if (mRadioButton == null) { insertRadioButton(); } compoundButton = mRadioButton; } else { if (mCheckBox == null) { insertCheckBox(); } compoundButton = mCheckBox; } compoundButton.setChecked(checked); } public void setShortcut(boolean showShortcut, char shortcutKey) { final int newVisibility = (showShortcut && mItemData.shouldShowShortcut()) ? VISIBLE : GONE; if (newVisibility == VISIBLE) { mShortcutView.setText(mItemData.getShortcutLabel()); } if (mShortcutView.getVisibility() != newVisibility) { mShortcutView.setVisibility(newVisibility); } } public void setIcon(Drawable icon) { final boolean showIcon = mItemData.shouldShowIcon() || mForceShowIcon; if (!showIcon && !mPreserveIconSpacing) { return; } if (mIconView == null && icon == null && !mPreserveIconSpacing) { return; } if (mIconView == null) { insertIconView(); } if (icon != null || mPreserveIconSpacing) { mIconView.setImageDrawable(showIcon ? icon : null); if (mIconView.getVisibility() != VISIBLE) { mIconView.setVisibility(VISIBLE); } } else { mIconView.setVisibility(GONE); } } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { if (mIconView != null && mPreserveIconSpacing) { // Enforce minimum icon spacing ViewGroup.LayoutParams lp = getLayoutParams(); LayoutParams iconLp = (LayoutParams) mIconView.getLayoutParams(); if (lp.height > 0 && iconLp.width <= 0) { iconLp.width = lp.height; } } super.onMeasure(widthMeasureSpec, heightMeasureSpec); } private void insertIconView() { LayoutInflater inflater = getInflater(); mIconView = (ImageView) inflater.inflate(R.layout.abs__list_menu_item_icon, this, false); addView(mIconView, 0); } private void insertRadioButton() { LayoutInflater inflater = getInflater(); mRadioButton = (RadioButton) inflater.inflate(R.layout.abs__list_menu_item_radio, this, false); addView(mRadioButton); } private void insertCheckBox() { LayoutInflater inflater = getInflater(); mCheckBox = (CheckBox) inflater.inflate(R.layout.abs__list_menu_item_checkbox, this, false); addView(mCheckBox); } public boolean prefersCondensedTitle() { return false; } public boolean showsIcon() { return mForceShowIcon; } private LayoutInflater getInflater() { if (mInflater == null) { mInflater = LayoutInflater.from(mContext); } return mInflater; } }
Java
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
/* * Copyright (C) 2010 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.actionbarsherlock.internal.view.menu; import android.content.Context; import android.content.Intent; import android.graphics.drawable.Drawable; import android.view.ContextMenu.ContextMenuInfo; import android.view.View; import com.actionbarsherlock.view.ActionProvider; import com.actionbarsherlock.view.MenuItem; import com.actionbarsherlock.view.SubMenu; /** * @hide */ public class ActionMenuItem implements MenuItem { private final int mId; private final int mGroup; //UNUSED private final int mCategoryOrder; private final int mOrdering; private CharSequence mTitle; private CharSequence mTitleCondensed; private Intent mIntent; private char mShortcutNumericChar; private char mShortcutAlphabeticChar; private Drawable mIconDrawable; //UNUSED private int mIconResId = NO_ICON; private Context mContext; private MenuItem.OnMenuItemClickListener mClickListener; //UNUSED private static final int NO_ICON = 0; private int mFlags = ENABLED; private static final int CHECKABLE = 0x00000001; private static final int CHECKED = 0x00000002; private static final int EXCLUSIVE = 0x00000004; private static final int HIDDEN = 0x00000008; private static final int ENABLED = 0x00000010; public ActionMenuItem(Context context, int group, int id, int categoryOrder, int ordering, CharSequence title) { mContext = context; mId = id; mGroup = group; //UNUSED mCategoryOrder = categoryOrder; mOrdering = ordering; mTitle = title; } public char getAlphabeticShortcut() { return mShortcutAlphabeticChar; } public int getGroupId() { return mGroup; } public Drawable getIcon() { return mIconDrawable; } public Intent getIntent() { return mIntent; } public int getItemId() { return mId; } public ContextMenuInfo getMenuInfo() { return null; } public char getNumericShortcut() { return mShortcutNumericChar; } public int getOrder() { return mOrdering; } public SubMenu getSubMenu() { return null; } public CharSequence getTitle() { return mTitle; } public CharSequence getTitleCondensed() { return mTitleCondensed; } public boolean hasSubMenu() { return false; } public boolean isCheckable() { return (mFlags & CHECKABLE) != 0; } public boolean isChecked() { return (mFlags & CHECKED) != 0; } public boolean isEnabled() { return (mFlags & ENABLED) != 0; } public boolean isVisible() { return (mFlags & HIDDEN) == 0; } public MenuItem setAlphabeticShortcut(char alphaChar) { mShortcutAlphabeticChar = alphaChar; return this; } public MenuItem setCheckable(boolean checkable) { mFlags = (mFlags & ~CHECKABLE) | (checkable ? CHECKABLE : 0); return this; } public ActionMenuItem setExclusiveCheckable(boolean exclusive) { mFlags = (mFlags & ~EXCLUSIVE) | (exclusive ? EXCLUSIVE : 0); return this; } public MenuItem setChecked(boolean checked) { mFlags = (mFlags & ~CHECKED) | (checked ? CHECKED : 0); return this; } public MenuItem setEnabled(boolean enabled) { mFlags = (mFlags & ~ENABLED) | (enabled ? ENABLED : 0); return this; } public MenuItem setIcon(Drawable icon) { mIconDrawable = icon; //UNUSED mIconResId = NO_ICON; return this; } public MenuItem setIcon(int iconRes) { //UNUSED mIconResId = iconRes; mIconDrawable = mContext.getResources().getDrawable(iconRes); return this; } public MenuItem setIntent(Intent intent) { mIntent = intent; return this; } public MenuItem setNumericShortcut(char numericChar) { mShortcutNumericChar = numericChar; return this; } public MenuItem setOnMenuItemClickListener(OnMenuItemClickListener menuItemClickListener) { mClickListener = menuItemClickListener; return this; } public MenuItem setShortcut(char numericChar, char alphaChar) { mShortcutNumericChar = numericChar; mShortcutAlphabeticChar = alphaChar; return this; } public MenuItem setTitle(CharSequence title) { mTitle = title; return this; } public MenuItem setTitle(int title) { mTitle = mContext.getResources().getString(title); return this; } public MenuItem setTitleCondensed(CharSequence title) { mTitleCondensed = title; return this; } public MenuItem setVisible(boolean visible) { mFlags = (mFlags & HIDDEN) | (visible ? 0 : HIDDEN); return this; } public boolean invoke() { if (mClickListener != null && mClickListener.onMenuItemClick(this)) { return true; } if (mIntent != null) { mContext.startActivity(mIntent); return true; } return false; } public void setShowAsAction(int show) { // Do nothing. ActionMenuItems always show as action buttons. } public MenuItem setActionView(View actionView) { throw new UnsupportedOperationException(); } public View getActionView() { return null; } @Override public MenuItem setActionView(int resId) { throw new UnsupportedOperationException(); } @Override public ActionProvider getActionProvider() { return null; } @Override public MenuItem setActionProvider(ActionProvider actionProvider) { throw new UnsupportedOperationException(); } @Override public MenuItem setShowAsActionFlags(int actionEnum) { setShowAsAction(actionEnum); return this; } @Override public boolean expandActionView() { return false; } @Override public boolean collapseActionView() { return false; } @Override public boolean isActionViewExpanded() { return false; } @Override public MenuItem setOnActionExpandListener(OnActionExpandListener listener) { // No need to save the listener; ActionMenuItem does not support collapsing items. return this; } }
Java
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) 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
/* * 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.app; import java.lang.ref.WeakReference; import java.util.ArrayList; import android.app.Activity; import android.app.Dialog; import android.content.Context; import android.content.res.Configuration; import android.content.res.Resources; import android.graphics.drawable.Drawable; import android.os.Build; import android.os.Handler; import android.support.v4.app.FragmentTransaction; import android.util.TypedValue; import android.view.ContextThemeWrapper; import android.view.LayoutInflater; import android.view.View; import android.view.Window; import android.view.accessibility.AccessibilityEvent; import android.widget.SpinnerAdapter; import com.actionbarsherlock.R; import com.actionbarsherlock.app.ActionBar; import com.actionbarsherlock.app.SherlockFragmentActivity; import com.actionbarsherlock.internal.nineoldandroids.animation.Animator; import com.actionbarsherlock.internal.nineoldandroids.animation.AnimatorListenerAdapter; import com.actionbarsherlock.internal.nineoldandroids.animation.AnimatorSet; import com.actionbarsherlock.internal.nineoldandroids.animation.ObjectAnimator; import com.actionbarsherlock.internal.nineoldandroids.animation.Animator.AnimatorListener; import com.actionbarsherlock.internal.nineoldandroids.widget.NineFrameLayout; 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.ActionBarContainer; import com.actionbarsherlock.internal.widget.ActionBarContextView; import com.actionbarsherlock.internal.widget.ActionBarView; import com.actionbarsherlock.internal.widget.ScrollingTabContainerView; import com.actionbarsherlock.view.ActionMode; import com.actionbarsherlock.view.Menu; import com.actionbarsherlock.view.MenuInflater; import com.actionbarsherlock.view.MenuItem; import static com.actionbarsherlock.internal.ResourcesCompat.getResources_getBoolean; /** * ActionBarImpl is the ActionBar implementation used * by devices of all screen sizes. If it detects a compatible decor, * it will split contextual modes across both the ActionBarView at * the top of the screen and a horizontal LinearLayout at the bottom * which is normally hidden. */ public class ActionBarImpl extends ActionBar { //UNUSED private static final String TAG = "ActionBarImpl"; private Context mContext; private Context mThemedContext; private Activity mActivity; //UNUSED private Dialog mDialog; private ActionBarContainer mContainerView; private ActionBarView mActionView; private ActionBarContextView mContextView; private ActionBarContainer mSplitView; private NineFrameLayout mContentView; private ScrollingTabContainerView mTabScrollView; private ArrayList<TabImpl> mTabs = new ArrayList<TabImpl>(); private TabImpl mSelectedTab; private int mSavedTabPosition = INVALID_POSITION; ActionModeImpl mActionMode; ActionMode mDeferredDestroyActionMode; ActionMode.Callback mDeferredModeDestroyCallback; private boolean mLastMenuVisibility; private ArrayList<OnMenuVisibilityListener> mMenuVisibilityListeners = new ArrayList<OnMenuVisibilityListener>(); private static final int CONTEXT_DISPLAY_NORMAL = 0; private static final int CONTEXT_DISPLAY_SPLIT = 1; private static final int INVALID_POSITION = -1; private int mContextDisplayMode; private boolean mHasEmbeddedTabs; final Handler mHandler = new Handler(); Runnable mTabSelector; private Animator mCurrentShowAnim; private Animator mCurrentModeAnim; private boolean mShowHideAnimationEnabled; boolean mWasHiddenBeforeMode; final AnimatorListener mHideListener = new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { if (mContentView != null) { mContentView.setTranslationY(0); mContainerView.setTranslationY(0); } if (mSplitView != null && mContextDisplayMode == CONTEXT_DISPLAY_SPLIT) { mSplitView.setVisibility(View.GONE); } mContainerView.setVisibility(View.GONE); mContainerView.setTransitioning(false); mCurrentShowAnim = null; completeDeferredDestroyActionMode(); } }; final AnimatorListener mShowListener = new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { mCurrentShowAnim = null; mContainerView.requestLayout(); } }; public ActionBarImpl(Activity activity, int features) { mActivity = activity; Window window = activity.getWindow(); View decor = window.getDecorView(); init(decor); //window.hasFeature() workaround for pre-3.0 if ((features & (1 << Window.FEATURE_ACTION_BAR_OVERLAY)) == 0) { mContentView = (NineFrameLayout)decor.findViewById(android.R.id.content); } } public ActionBarImpl(Dialog dialog) { //UNUSED mDialog = dialog; init(dialog.getWindow().getDecorView()); } private void init(View decor) { mContext = decor.getContext(); mActionView = (ActionBarView) decor.findViewById(R.id.abs__action_bar); mContextView = (ActionBarContextView) decor.findViewById( R.id.abs__action_context_bar); mContainerView = (ActionBarContainer) decor.findViewById( R.id.abs__action_bar_container); mSplitView = (ActionBarContainer) decor.findViewById( R.id.abs__split_action_bar); if (mActionView == null || mContextView == null || mContainerView == null) { throw new IllegalStateException(getClass().getSimpleName() + " can only be used " + "with a compatible window decor layout"); } mActionView.setContextView(mContextView); mContextDisplayMode = mActionView.isSplitActionBar() ? CONTEXT_DISPLAY_SPLIT : CONTEXT_DISPLAY_NORMAL; // Older apps get the home button interaction enabled by default. // Newer apps need to enable it explicitly. setHomeButtonEnabled(mContext.getApplicationInfo().targetSdkVersion < 14); setHasEmbeddedTabs(getResources_getBoolean(mContext, R.bool.abs__action_bar_embed_tabs)); } public void onConfigurationChanged(Configuration newConfig) { setHasEmbeddedTabs(getResources_getBoolean(mContext, R.bool.abs__action_bar_embed_tabs)); //Manually dispatch a configuration change to the action bar view on pre-2.2 if (Build.VERSION.SDK_INT < Build.VERSION_CODES.FROYO) { mActionView.onConfigurationChanged(newConfig); if (mContextView != null) { mContextView.onConfigurationChanged(newConfig); } } } private void setHasEmbeddedTabs(boolean hasEmbeddedTabs) { mHasEmbeddedTabs = hasEmbeddedTabs; // Switch tab layout configuration if needed if (!mHasEmbeddedTabs) { mActionView.setEmbeddedTabView(null); mContainerView.setTabContainer(mTabScrollView); } else { mContainerView.setTabContainer(null); mActionView.setEmbeddedTabView(mTabScrollView); } final boolean isInTabMode = getNavigationMode() == NAVIGATION_MODE_TABS; if (mTabScrollView != null) { mTabScrollView.setVisibility(isInTabMode ? View.VISIBLE : View.GONE); } mActionView.setCollapsable(!mHasEmbeddedTabs && isInTabMode); } private void ensureTabsExist() { if (mTabScrollView != null) { return; } ScrollingTabContainerView tabScroller = new ScrollingTabContainerView(mContext); if (mHasEmbeddedTabs) { tabScroller.setVisibility(View.VISIBLE); mActionView.setEmbeddedTabView(tabScroller); } else { tabScroller.setVisibility(getNavigationMode() == NAVIGATION_MODE_TABS ? View.VISIBLE : View.GONE); mContainerView.setTabContainer(tabScroller); } mTabScrollView = tabScroller; } void completeDeferredDestroyActionMode() { if (mDeferredModeDestroyCallback != null) { mDeferredModeDestroyCallback.onDestroyActionMode(mDeferredDestroyActionMode); mDeferredDestroyActionMode = null; mDeferredModeDestroyCallback = null; } } /** * Enables or disables animation between show/hide states. * If animation is disabled using this method, animations in progress * will be finished. * * @param enabled true to animate, false to not animate. */ public void setShowHideAnimationEnabled(boolean enabled) { mShowHideAnimationEnabled = enabled; if (!enabled && mCurrentShowAnim != null) { mCurrentShowAnim.end(); } } public void addOnMenuVisibilityListener(OnMenuVisibilityListener listener) { mMenuVisibilityListeners.add(listener); } public void removeOnMenuVisibilityListener(OnMenuVisibilityListener listener) { mMenuVisibilityListeners.remove(listener); } public void dispatchMenuVisibilityChanged(boolean isVisible) { if (isVisible == mLastMenuVisibility) { return; } mLastMenuVisibility = isVisible; final int count = mMenuVisibilityListeners.size(); for (int i = 0; i < count; i++) { mMenuVisibilityListeners.get(i).onMenuVisibilityChanged(isVisible); } } @Override public void setCustomView(int resId) { setCustomView(LayoutInflater.from(getThemedContext()).inflate(resId, mActionView, false)); } @Override public void setDisplayUseLogoEnabled(boolean useLogo) { setDisplayOptions(useLogo ? DISPLAY_USE_LOGO : 0, DISPLAY_USE_LOGO); } @Override public void setDisplayShowHomeEnabled(boolean showHome) { setDisplayOptions(showHome ? DISPLAY_SHOW_HOME : 0, DISPLAY_SHOW_HOME); } @Override public void setDisplayHomeAsUpEnabled(boolean showHomeAsUp) { setDisplayOptions(showHomeAsUp ? DISPLAY_HOME_AS_UP : 0, DISPLAY_HOME_AS_UP); } @Override public void setDisplayShowTitleEnabled(boolean showTitle) { setDisplayOptions(showTitle ? DISPLAY_SHOW_TITLE : 0, DISPLAY_SHOW_TITLE); } @Override public void setDisplayShowCustomEnabled(boolean showCustom) { setDisplayOptions(showCustom ? DISPLAY_SHOW_CUSTOM : 0, DISPLAY_SHOW_CUSTOM); } @Override public void setHomeButtonEnabled(boolean enable) { mActionView.setHomeButtonEnabled(enable); } @Override public void setTitle(int resId) { setTitle(mContext.getString(resId)); } @Override public void setSubtitle(int resId) { setSubtitle(mContext.getString(resId)); } public void setSelectedNavigationItem(int position) { switch (mActionView.getNavigationMode()) { case NAVIGATION_MODE_TABS: selectTab(mTabs.get(position)); break; case NAVIGATION_MODE_LIST: mActionView.setDropdownSelectedPosition(position); break; default: throw new IllegalStateException( "setSelectedNavigationIndex not valid for current navigation mode"); } } public void removeAllTabs() { cleanupTabs(); } private void cleanupTabs() { if (mSelectedTab != null) { selectTab(null); } mTabs.clear(); if (mTabScrollView != null) { mTabScrollView.removeAllTabs(); } mSavedTabPosition = INVALID_POSITION; } public void setTitle(CharSequence title) { mActionView.setTitle(title); } public void setSubtitle(CharSequence subtitle) { mActionView.setSubtitle(subtitle); } public void setDisplayOptions(int options) { mActionView.setDisplayOptions(options); } public void setDisplayOptions(int options, int mask) { final int current = mActionView.getDisplayOptions(); mActionView.setDisplayOptions((options & mask) | (current & ~mask)); } public void setBackgroundDrawable(Drawable d) { mContainerView.setPrimaryBackground(d); } public void setStackedBackgroundDrawable(Drawable d) { mContainerView.setStackedBackground(d); } public void setSplitBackgroundDrawable(Drawable d) { if (mSplitView != null) { mSplitView.setSplitBackground(d); } } public View getCustomView() { return mActionView.getCustomNavigationView(); } public CharSequence getTitle() { return mActionView.getTitle(); } public CharSequence getSubtitle() { return mActionView.getSubtitle(); } public int getNavigationMode() { return mActionView.getNavigationMode(); } public int getDisplayOptions() { return mActionView.getDisplayOptions(); } public ActionMode startActionMode(ActionMode.Callback callback) { boolean wasHidden = false; if (mActionMode != null) { wasHidden = mWasHiddenBeforeMode; mActionMode.finish(); } mContextView.killMode(); ActionModeImpl mode = new ActionModeImpl(callback); if (mode.dispatchOnCreate()) { mWasHiddenBeforeMode = !isShowing() || wasHidden; mode.invalidate(); mContextView.initForMode(mode); animateToMode(true); if (mSplitView != null && mContextDisplayMode == CONTEXT_DISPLAY_SPLIT) { // TODO animate this mSplitView.setVisibility(View.VISIBLE); } mContextView.sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED); mActionMode = mode; return mode; } return null; } private void configureTab(Tab tab, int position) { final TabImpl tabi = (TabImpl) tab; final ActionBar.TabListener callback = tabi.getCallback(); if (callback == null) { throw new IllegalStateException("Action Bar Tab must have a Callback"); } tabi.setPosition(position); mTabs.add(position, tabi); final int count = mTabs.size(); for (int i = position + 1; i < count; i++) { mTabs.get(i).setPosition(i); } } @Override public void addTab(Tab tab) { addTab(tab, mTabs.isEmpty()); } @Override public void addTab(Tab tab, int position) { addTab(tab, position, mTabs.isEmpty()); } @Override public void addTab(Tab tab, boolean setSelected) { ensureTabsExist(); mTabScrollView.addTab(tab, setSelected); configureTab(tab, mTabs.size()); if (setSelected) { selectTab(tab); } } @Override public void addTab(Tab tab, int position, boolean setSelected) { ensureTabsExist(); mTabScrollView.addTab(tab, position, setSelected); configureTab(tab, position); if (setSelected) { selectTab(tab); } } @Override public Tab newTab() { return new TabImpl(); } @Override public void removeTab(Tab tab) { removeTabAt(tab.getPosition()); } @Override public void removeTabAt(int position) { if (mTabScrollView == null) { // No tabs around to remove return; } int selectedTabPosition = mSelectedTab != null ? mSelectedTab.getPosition() : mSavedTabPosition; mTabScrollView.removeTabAt(position); TabImpl removedTab = mTabs.remove(position); if (removedTab != null) { removedTab.setPosition(-1); } final int newTabCount = mTabs.size(); for (int i = position; i < newTabCount; i++) { mTabs.get(i).setPosition(i); } if (selectedTabPosition == position) { selectTab(mTabs.isEmpty() ? null : mTabs.get(Math.max(0, position - 1))); } } @Override public void selectTab(Tab tab) { if (getNavigationMode() != NAVIGATION_MODE_TABS) { mSavedTabPosition = tab != null ? tab.getPosition() : INVALID_POSITION; return; } FragmentTransaction trans = null; if (mActivity instanceof SherlockFragmentActivity) { trans = ((SherlockFragmentActivity)mActivity).getSupportFragmentManager().beginTransaction() .disallowAddToBackStack(); } if (mSelectedTab == tab) { if (mSelectedTab != null) { mSelectedTab.getCallback().onTabReselected(mSelectedTab, trans); mTabScrollView.animateToTab(tab.getPosition()); } } else { mTabScrollView.setTabSelected(tab != null ? tab.getPosition() : Tab.INVALID_POSITION); if (mSelectedTab != null) { mSelectedTab.getCallback().onTabUnselected(mSelectedTab, trans); } mSelectedTab = (TabImpl) tab; if (mSelectedTab != null) { mSelectedTab.getCallback().onTabSelected(mSelectedTab, trans); } } if (trans != null && !trans.isEmpty()) { trans.commit(); } } @Override public Tab getSelectedTab() { return mSelectedTab; } @Override public int getHeight() { return mContainerView.getHeight(); } @Override public void show() { show(true); } void show(boolean markHiddenBeforeMode) { if (mCurrentShowAnim != null) { mCurrentShowAnim.end(); } if (mContainerView.getVisibility() == View.VISIBLE) { if (markHiddenBeforeMode) mWasHiddenBeforeMode = false; return; } mContainerView.setVisibility(View.VISIBLE); if (mShowHideAnimationEnabled) { mContainerView.setAlpha(0); AnimatorSet anim = new AnimatorSet(); AnimatorSet.Builder b = anim.play(ObjectAnimator.ofFloat(mContainerView, "alpha", 1)); if (mContentView != null) { b.with(ObjectAnimator.ofFloat(mContentView, "translationY", -mContainerView.getHeight(), 0)); mContainerView.setTranslationY(-mContainerView.getHeight()); b.with(ObjectAnimator.ofFloat(mContainerView, "translationY", 0)); } if (mSplitView != null && mContextDisplayMode == CONTEXT_DISPLAY_SPLIT) { mSplitView.setAlpha(0); mSplitView.setVisibility(View.VISIBLE); b.with(ObjectAnimator.ofFloat(mSplitView, "alpha", 1)); } anim.addListener(mShowListener); mCurrentShowAnim = anim; anim.start(); } else { mContainerView.setAlpha(1); mContainerView.setTranslationY(0); mShowListener.onAnimationEnd(null); } } @Override public void hide() { if (mCurrentShowAnim != null) { mCurrentShowAnim.end(); } if (mContainerView.getVisibility() == View.GONE) { return; } if (mShowHideAnimationEnabled) { mContainerView.setAlpha(1); mContainerView.setTransitioning(true); AnimatorSet anim = new AnimatorSet(); AnimatorSet.Builder b = anim.play(ObjectAnimator.ofFloat(mContainerView, "alpha", 0)); if (mContentView != null) { b.with(ObjectAnimator.ofFloat(mContentView, "translationY", 0, -mContainerView.getHeight())); b.with(ObjectAnimator.ofFloat(mContainerView, "translationY", -mContainerView.getHeight())); } if (mSplitView != null && mSplitView.getVisibility() == View.VISIBLE) { mSplitView.setAlpha(1); b.with(ObjectAnimator.ofFloat(mSplitView, "alpha", 0)); } anim.addListener(mHideListener); mCurrentShowAnim = anim; anim.start(); } else { mHideListener.onAnimationEnd(null); } } public boolean isShowing() { return mContainerView.getVisibility() == View.VISIBLE; } void animateToMode(boolean toActionMode) { if (toActionMode) { show(false); } if (mCurrentModeAnim != null) { mCurrentModeAnim.end(); } mActionView.animateToVisibility(toActionMode ? View.GONE : View.VISIBLE); mContextView.animateToVisibility(toActionMode ? View.VISIBLE : View.GONE); if (mTabScrollView != null && !mActionView.hasEmbeddedTabs() && mActionView.isCollapsed()) { mTabScrollView.animateToVisibility(toActionMode ? View.GONE : View.VISIBLE); } } public Context getThemedContext() { if (mThemedContext == null) { TypedValue outValue = new TypedValue(); Resources.Theme currentTheme = mContext.getTheme(); currentTheme.resolveAttribute(R.attr.actionBarWidgetTheme, outValue, true); final int targetThemeRes = outValue.resourceId; if (targetThemeRes != 0) { //XXX && mContext.getThemeResId() != targetThemeRes) { mThemedContext = new ContextThemeWrapper(mContext, targetThemeRes); } else { mThemedContext = mContext; } } return mThemedContext; } /** * @hide */ public class ActionModeImpl extends ActionMode implements MenuBuilder.Callback { private ActionMode.Callback mCallback; private MenuBuilder mMenu; private WeakReference<View> mCustomView; public ActionModeImpl(ActionMode.Callback callback) { mCallback = callback; mMenu = new MenuBuilder(getThemedContext()) .setDefaultShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM); mMenu.setCallback(this); } @Override public MenuInflater getMenuInflater() { return new MenuInflater(getThemedContext()); } @Override public Menu getMenu() { return mMenu; } @Override public void finish() { if (mActionMode != this) { // Not the active action mode - no-op return; } // If we were hidden before the mode was shown, defer the onDestroy // callback until the animation is finished and associated relayout // is about to happen. This lets apps better anticipate visibility // and layout behavior. if (mWasHiddenBeforeMode) { mDeferredDestroyActionMode = this; mDeferredModeDestroyCallback = mCallback; } else { mCallback.onDestroyActionMode(this); } mCallback = null; animateToMode(false); // Clear out the context mode views after the animation finishes mContextView.closeMode(); mActionView.sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED); mActionMode = null; if (mWasHiddenBeforeMode) { hide(); } } @Override public void invalidate() { mMenu.stopDispatchingItemsChanged(); try { mCallback.onPrepareActionMode(this, mMenu); } finally { mMenu.startDispatchingItemsChanged(); } } public boolean dispatchOnCreate() { mMenu.stopDispatchingItemsChanged(); try { return mCallback.onCreateActionMode(this, mMenu); } finally { mMenu.startDispatchingItemsChanged(); } } @Override public void setCustomView(View view) { mContextView.setCustomView(view); mCustomView = new WeakReference<View>(view); } @Override public void setSubtitle(CharSequence subtitle) { mContextView.setSubtitle(subtitle); } @Override public void setTitle(CharSequence title) { mContextView.setTitle(title); } @Override public void setTitle(int resId) { setTitle(mContext.getResources().getString(resId)); } @Override public void setSubtitle(int resId) { setSubtitle(mContext.getResources().getString(resId)); } @Override public CharSequence getTitle() { return mContextView.getTitle(); } @Override public CharSequence getSubtitle() { return mContextView.getSubtitle(); } @Override public View getCustomView() { return mCustomView != null ? mCustomView.get() : null; } public boolean onMenuItemSelected(MenuBuilder menu, MenuItem item) { if (mCallback != null) { return mCallback.onActionItemClicked(this, item); } else { return false; } } public void onCloseMenu(MenuBuilder menu, boolean allMenusAreClosing) { } public boolean onSubMenuSelected(SubMenuBuilder subMenu) { if (mCallback == null) { return false; } if (!subMenu.hasVisibleItems()) { return true; } new MenuPopupHelper(getThemedContext(), subMenu).show(); return true; } public void onCloseSubMenu(SubMenuBuilder menu) { } public void onMenuModeChange(MenuBuilder menu) { if (mCallback == null) { return; } invalidate(); mContextView.showOverflowMenu(); } } /** * @hide */ public class TabImpl extends ActionBar.Tab { private ActionBar.TabListener mCallback; private Object mTag; private Drawable mIcon; private CharSequence mText; private CharSequence mContentDesc; private int mPosition = -1; private View mCustomView; @Override public Object getTag() { return mTag; } @Override public Tab setTag(Object tag) { mTag = tag; return this; } public ActionBar.TabListener getCallback() { return mCallback; } @Override public Tab setTabListener(ActionBar.TabListener callback) { mCallback = callback; return this; } @Override public View getCustomView() { return mCustomView; } @Override public Tab setCustomView(View view) { mCustomView = view; if (mPosition >= 0) { mTabScrollView.updateTab(mPosition); } return this; } @Override public Tab setCustomView(int layoutResId) { return setCustomView(LayoutInflater.from(getThemedContext()) .inflate(layoutResId, null)); } @Override public Drawable getIcon() { return mIcon; } @Override public int getPosition() { return mPosition; } public void setPosition(int position) { mPosition = position; } @Override public CharSequence getText() { return mText; } @Override public Tab setIcon(Drawable icon) { mIcon = icon; if (mPosition >= 0) { mTabScrollView.updateTab(mPosition); } return this; } @Override public Tab setIcon(int resId) { return setIcon(mContext.getResources().getDrawable(resId)); } @Override public Tab setText(CharSequence text) { mText = text; if (mPosition >= 0) { mTabScrollView.updateTab(mPosition); } return this; } @Override public Tab setText(int resId) { return setText(mContext.getResources().getText(resId)); } @Override public void select() { selectTab(this); } @Override public Tab setContentDescription(int resId) { return setContentDescription(mContext.getResources().getText(resId)); } @Override public Tab setContentDescription(CharSequence contentDesc) { mContentDesc = contentDesc; if (mPosition >= 0) { mTabScrollView.updateTab(mPosition); } return this; } @Override public CharSequence getContentDescription() { return mContentDesc; } } @Override public void setCustomView(View view) { mActionView.setCustomNavigationView(view); } @Override public void setCustomView(View view, LayoutParams layoutParams) { view.setLayoutParams(layoutParams); mActionView.setCustomNavigationView(view); } @Override public void setListNavigationCallbacks(SpinnerAdapter adapter, OnNavigationListener callback) { mActionView.setDropdownAdapter(adapter); mActionView.setCallback(callback); } @Override public int getSelectedNavigationIndex() { switch (mActionView.getNavigationMode()) { case NAVIGATION_MODE_TABS: return mSelectedTab != null ? mSelectedTab.getPosition() : -1; case NAVIGATION_MODE_LIST: return mActionView.getDropdownSelectedPosition(); default: return -1; } } @Override public int getNavigationItemCount() { switch (mActionView.getNavigationMode()) { case NAVIGATION_MODE_TABS: return mTabs.size(); case NAVIGATION_MODE_LIST: SpinnerAdapter adapter = mActionView.getDropdownAdapter(); return adapter != null ? adapter.getCount() : 0; default: return 0; } } @Override public int getTabCount() { return mTabs.size(); } @Override public void setNavigationMode(int mode) { final int oldMode = mActionView.getNavigationMode(); switch (oldMode) { case NAVIGATION_MODE_TABS: mSavedTabPosition = getSelectedNavigationIndex(); selectTab(null); mTabScrollView.setVisibility(View.GONE); break; } mActionView.setNavigationMode(mode); switch (mode) { case NAVIGATION_MODE_TABS: ensureTabsExist(); mTabScrollView.setVisibility(View.VISIBLE); if (mSavedTabPosition != INVALID_POSITION) { setSelectedNavigationItem(mSavedTabPosition); mSavedTabPosition = INVALID_POSITION; } break; } mActionView.setCollapsable(mode == NAVIGATION_MODE_TABS && !mHasEmbeddedTabs); } @Override public Tab getTabAt(int index) { return mTabs.get(index); } @Override public void setIcon(int resId) { mActionView.setIcon(resId); } @Override public void setIcon(Drawable icon) { mActionView.setIcon(icon); } @Override public void setLogo(int resId) { mActionView.setLogo(resId); } @Override public void setLogo(Drawable logo) { mActionView.setLogo(logo); } }
Java
package com.actionbarsherlock.internal.app; import java.util.HashSet; import java.util.Set; import android.app.Activity; import android.content.Context; import android.graphics.drawable.Drawable; import android.support.v4.app.FragmentTransaction; import android.view.View; import android.widget.SpinnerAdapter; import com.actionbarsherlock.app.ActionBar; import com.actionbarsherlock.app.SherlockFragmentActivity; public class ActionBarWrapper extends ActionBar implements android.app.ActionBar.OnNavigationListener, android.app.ActionBar.OnMenuVisibilityListener { private final Activity mActivity; private final android.app.ActionBar mActionBar; private ActionBar.OnNavigationListener mNavigationListener; private Set<OnMenuVisibilityListener> mMenuVisibilityListeners = new HashSet<OnMenuVisibilityListener>(1); private FragmentTransaction mFragmentTransaction; public ActionBarWrapper(Activity activity) { mActivity = activity; mActionBar = activity.getActionBar(); if (mActionBar != null) { mActionBar.addOnMenuVisibilityListener(this); } } @Override public void setHomeButtonEnabled(boolean enabled) { mActionBar.setHomeButtonEnabled(enabled); } @Override public Context getThemedContext() { return mActionBar.getThemedContext(); } @Override public void setCustomView(View view) { mActionBar.setCustomView(view); } @Override public void setCustomView(View view, LayoutParams layoutParams) { android.app.ActionBar.LayoutParams lp = new android.app.ActionBar.LayoutParams(layoutParams); lp.gravity = layoutParams.gravity; lp.bottomMargin = layoutParams.bottomMargin; lp.topMargin = layoutParams.topMargin; lp.leftMargin = layoutParams.leftMargin; lp.rightMargin = layoutParams.rightMargin; mActionBar.setCustomView(view, lp); } @Override public void setCustomView(int resId) { mActionBar.setCustomView(resId); } @Override public void setIcon(int resId) { mActionBar.setIcon(resId); } @Override public void setIcon(Drawable icon) { mActionBar.setIcon(icon); } @Override public void setLogo(int resId) { mActionBar.setLogo(resId); } @Override public void setLogo(Drawable logo) { mActionBar.setLogo(logo); } @Override public void setListNavigationCallbacks(SpinnerAdapter adapter, OnNavigationListener callback) { mNavigationListener = callback; mActionBar.setListNavigationCallbacks(adapter, (callback != null) ? this : null); } @Override public boolean onNavigationItemSelected(int itemPosition, long itemId) { //This should never be a NullPointerException since we only set //ourselves as the listener when the callback is not null. return mNavigationListener.onNavigationItemSelected(itemPosition, itemId); } @Override public void setSelectedNavigationItem(int position) { mActionBar.setSelectedNavigationItem(position); } @Override public int getSelectedNavigationIndex() { return mActionBar.getSelectedNavigationIndex(); } @Override public int getNavigationItemCount() { return mActionBar.getNavigationItemCount(); } @Override public void setTitle(CharSequence title) { mActionBar.setTitle(title); } @Override public void setTitle(int resId) { mActionBar.setTitle(resId); } @Override public void setSubtitle(CharSequence subtitle) { mActionBar.setSubtitle(subtitle); } @Override public void setSubtitle(int resId) { mActionBar.setSubtitle(resId); } @Override public void setDisplayOptions(int options) { mActionBar.setDisplayOptions(options); } @Override public void setDisplayOptions(int options, int mask) { mActionBar.setDisplayOptions(options, mask); } @Override public void setDisplayUseLogoEnabled(boolean useLogo) { mActionBar.setDisplayUseLogoEnabled(useLogo); } @Override public void setDisplayShowHomeEnabled(boolean showHome) { mActionBar.setDisplayShowHomeEnabled(showHome); } @Override public void setDisplayHomeAsUpEnabled(boolean showHomeAsUp) { mActionBar.setDisplayHomeAsUpEnabled(showHomeAsUp); } @Override public void setDisplayShowTitleEnabled(boolean showTitle) { mActionBar.setDisplayShowTitleEnabled(showTitle); } @Override public void setDisplayShowCustomEnabled(boolean showCustom) { mActionBar.setDisplayShowCustomEnabled(showCustom); } @Override public void setBackgroundDrawable(Drawable d) { mActionBar.setBackgroundDrawable(d); } @Override public void setStackedBackgroundDrawable(Drawable d) { mActionBar.setStackedBackgroundDrawable(d); } @Override public void setSplitBackgroundDrawable(Drawable d) { mActionBar.setSplitBackgroundDrawable(d); } @Override public View getCustomView() { return mActionBar.getCustomView(); } @Override public CharSequence getTitle() { return mActionBar.getTitle(); } @Override public CharSequence getSubtitle() { return mActionBar.getSubtitle(); } @Override public int getNavigationMode() { return mActionBar.getNavigationMode(); } @Override public void setNavigationMode(int mode) { mActionBar.setNavigationMode(mode); } @Override public int getDisplayOptions() { return mActionBar.getDisplayOptions(); } public class TabWrapper extends ActionBar.Tab implements android.app.ActionBar.TabListener { final android.app.ActionBar.Tab mNativeTab; private Object mTag; private TabListener mListener; public TabWrapper(android.app.ActionBar.Tab nativeTab) { mNativeTab = nativeTab; mNativeTab.setTag(this); } @Override public int getPosition() { return mNativeTab.getPosition(); } @Override public Drawable getIcon() { return mNativeTab.getIcon(); } @Override public CharSequence getText() { return mNativeTab.getText(); } @Override public Tab setIcon(Drawable icon) { mNativeTab.setIcon(icon); return this; } @Override public Tab setIcon(int resId) { mNativeTab.setIcon(resId); return this; } @Override public Tab setText(CharSequence text) { mNativeTab.setText(text); return this; } @Override public Tab setText(int resId) { mNativeTab.setText(resId); return this; } @Override public Tab setCustomView(View view) { mNativeTab.setCustomView(view); return this; } @Override public Tab setCustomView(int layoutResId) { mNativeTab.setCustomView(layoutResId); return this; } @Override public View getCustomView() { return mNativeTab.getCustomView(); } @Override public Tab setTag(Object obj) { mTag = obj; return this; } @Override public Object getTag() { return mTag; } @Override public Tab setTabListener(TabListener listener) { mNativeTab.setTabListener(listener != null ? this : null); mListener = listener; return this; } @Override public void select() { mNativeTab.select(); } @Override public Tab setContentDescription(int resId) { mNativeTab.setContentDescription(resId); return this; } @Override public Tab setContentDescription(CharSequence contentDesc) { mNativeTab.setContentDescription(contentDesc); return this; } @Override public CharSequence getContentDescription() { return mNativeTab.getContentDescription(); } @Override public void onTabReselected(android.app.ActionBar.Tab tab, android.app.FragmentTransaction ft) { if (mListener != null) { FragmentTransaction trans = null; if (mActivity instanceof SherlockFragmentActivity) { trans = ((SherlockFragmentActivity)mActivity).getSupportFragmentManager().beginTransaction() .disallowAddToBackStack(); } mListener.onTabReselected(this, trans); if (trans != null && !trans.isEmpty()) { trans.commit(); } } } @Override public void onTabSelected(android.app.ActionBar.Tab tab, android.app.FragmentTransaction ft) { if (mListener != null) { if (mFragmentTransaction == null && mActivity instanceof SherlockFragmentActivity) { mFragmentTransaction = ((SherlockFragmentActivity)mActivity).getSupportFragmentManager().beginTransaction() .disallowAddToBackStack(); } mListener.onTabSelected(this, mFragmentTransaction); if (mFragmentTransaction != null) { if (!mFragmentTransaction.isEmpty()) { mFragmentTransaction.commit(); } mFragmentTransaction = null; } } } @Override public void onTabUnselected(android.app.ActionBar.Tab tab, android.app.FragmentTransaction ft) { if (mListener != null) { FragmentTransaction trans = null; if (mActivity instanceof SherlockFragmentActivity) { trans = ((SherlockFragmentActivity)mActivity).getSupportFragmentManager().beginTransaction() .disallowAddToBackStack(); mFragmentTransaction = trans; } mListener.onTabUnselected(this, trans); } } } @Override public Tab newTab() { return new TabWrapper(mActionBar.newTab()); } @Override public void addTab(Tab tab) { mActionBar.addTab(((TabWrapper)tab).mNativeTab); } @Override public void addTab(Tab tab, boolean setSelected) { mActionBar.addTab(((TabWrapper)tab).mNativeTab, setSelected); } @Override public void addTab(Tab tab, int position) { mActionBar.addTab(((TabWrapper)tab).mNativeTab, position); } @Override public void addTab(Tab tab, int position, boolean setSelected) { mActionBar.addTab(((TabWrapper)tab).mNativeTab, position, setSelected); } @Override public void removeTab(Tab tab) { mActionBar.removeTab(((TabWrapper)tab).mNativeTab); } @Override public void removeTabAt(int position) { mActionBar.removeTabAt(position); } @Override public void removeAllTabs() { mActionBar.removeAllTabs(); } @Override public void selectTab(Tab tab) { mActionBar.selectTab(((TabWrapper)tab).mNativeTab); } @Override public Tab getSelectedTab() { android.app.ActionBar.Tab selected = mActionBar.getSelectedTab(); return (selected != null) ? (Tab)selected.getTag() : null; } @Override public Tab getTabAt(int index) { android.app.ActionBar.Tab selected = mActionBar.getTabAt(index); return (selected != null) ? (Tab)selected.getTag() : null; } @Override public int getTabCount() { return mActionBar.getTabCount(); } @Override public int getHeight() { return mActionBar.getHeight(); } @Override public void show() { mActionBar.show(); } @Override public void hide() { mActionBar.hide(); } @Override public boolean isShowing() { return mActionBar.isShowing(); } @Override public void addOnMenuVisibilityListener(OnMenuVisibilityListener listener) { mMenuVisibilityListeners.add(listener); } @Override public void removeOnMenuVisibilityListener(OnMenuVisibilityListener listener) { mMenuVisibilityListeners.remove(listener); } @Override public void onMenuVisibilityChanged(boolean isVisible) { for (OnMenuVisibilityListener listener : mMenuVisibilityListeners) { listener.onMenuVisibilityChanged(isVisible); } } }
Java
package com.actionbarsherlock.internal.widget; import android.view.View; final class IcsView { //No instances private IcsView() {} /** * Return only the state bits of {@link #getMeasuredWidthAndState()} * and {@link #getMeasuredHeightAndState()}, combined into one integer. * The width component is in the regular bits {@link #MEASURED_STATE_MASK} * and the height component is at the shifted bits * {@link #MEASURED_HEIGHT_STATE_SHIFT}>>{@link #MEASURED_STATE_MASK}. */ public static int getMeasuredStateInt(View child) { return (child.getMeasuredWidth()&View.MEASURED_STATE_MASK) | ((child.getMeasuredHeight()>>View.MEASURED_HEIGHT_STATE_SHIFT) & (View.MEASURED_STATE_MASK>>View.MEASURED_HEIGHT_STATE_SHIFT)); } }
Java
package com.actionbarsherlock.internal.widget; import java.util.Locale; import android.content.Context; import android.content.res.TypedArray; import android.os.Build; import android.util.AttributeSet; import android.widget.TextView; public class CapitalizingTextView extends TextView { private static final boolean SANS_ICE_CREAM = Build.VERSION.SDK_INT < Build.VERSION_CODES.ICE_CREAM_SANDWICH; private static final boolean IS_GINGERBREAD = Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD; private static final int[] R_styleable_TextView = new int[] { android.R.attr.textAllCaps }; private static final int R_styleable_TextView_textAllCaps = 0; private boolean mAllCaps; public CapitalizingTextView(Context context, AttributeSet attrs) { this(context, attrs, 0); } public CapitalizingTextView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); TypedArray a = context.obtainStyledAttributes(attrs, R_styleable_TextView, defStyle, 0); mAllCaps = a.getBoolean(R_styleable_TextView_textAllCaps, true); a.recycle(); } public void setTextCompat(CharSequence text) { if (SANS_ICE_CREAM && mAllCaps && text != null) { if (IS_GINGERBREAD) { setText(text.toString().toUpperCase(Locale.ROOT)); } else { setText(text.toString().toUpperCase()); } } else { setText(text); } } }
Java
/* * Copyright (C) 2006 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.actionbarsherlock.internal.widget; import android.content.Context; import android.database.DataSetObserver; import android.graphics.Rect; import android.os.Build; import android.os.Parcel; import android.os.Parcelable; import android.util.AttributeSet; import android.util.SparseArray; import android.view.View; import android.view.ViewGroup; import android.widget.SpinnerAdapter; /** * An abstract base class for spinner widgets. SDK users will probably not * need to use this class. * * @attr ref android.R.styleable#AbsSpinner_entries */ public abstract class IcsAbsSpinner extends IcsAdapterView<SpinnerAdapter> { private static final boolean IS_HONEYCOMB = Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB; SpinnerAdapter mAdapter; int mHeightMeasureSpec; int mWidthMeasureSpec; boolean mBlockLayoutRequests; int mSelectionLeftPadding = 0; int mSelectionTopPadding = 0; int mSelectionRightPadding = 0; int mSelectionBottomPadding = 0; final Rect mSpinnerPadding = new Rect(); final RecycleBin mRecycler = new RecycleBin(); private DataSetObserver mDataSetObserver; /** Temporary frame to hold a child View's frame rectangle */ private Rect mTouchFrame; public IcsAbsSpinner(Context context) { super(context); initAbsSpinner(); } public IcsAbsSpinner(Context context, AttributeSet attrs) { this(context, attrs, 0); } public IcsAbsSpinner(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); initAbsSpinner(); /* TypedArray a = context.obtainStyledAttributes(attrs, com.android.internal.R.styleable.AbsSpinner, defStyle, 0); CharSequence[] entries = a.getTextArray(R.styleable.AbsSpinner_entries); if (entries != null) { ArrayAdapter<CharSequence> adapter = new ArrayAdapter<CharSequence>(context, R.layout.simple_spinner_item, entries); adapter.setDropDownViewResource(R.layout.simple_spinner_dropdown_item); setAdapter(adapter); } a.recycle(); */ } /** * Common code for different constructor flavors */ private void initAbsSpinner() { setFocusable(true); setWillNotDraw(false); } /** * The Adapter is used to provide the data which backs this Spinner. * It also provides methods to transform spinner items based on their position * relative to the selected item. * @param adapter The SpinnerAdapter to use for this Spinner */ @Override public void setAdapter(SpinnerAdapter adapter) { if (null != mAdapter) { mAdapter.unregisterDataSetObserver(mDataSetObserver); resetList(); } mAdapter = adapter; mOldSelectedPosition = INVALID_POSITION; mOldSelectedRowId = INVALID_ROW_ID; if (mAdapter != null) { mOldItemCount = mItemCount; mItemCount = mAdapter.getCount(); checkFocus(); mDataSetObserver = new AdapterDataSetObserver(); mAdapter.registerDataSetObserver(mDataSetObserver); int position = mItemCount > 0 ? 0 : INVALID_POSITION; setSelectedPositionInt(position); setNextSelectedPositionInt(position); if (mItemCount == 0) { // Nothing selected checkSelectionChanged(); } } else { checkFocus(); resetList(); // Nothing selected checkSelectionChanged(); } requestLayout(); } /** * Clear out all children from the list */ void resetList() { mDataChanged = false; mNeedSync = false; removeAllViewsInLayout(); mOldSelectedPosition = INVALID_POSITION; mOldSelectedRowId = INVALID_ROW_ID; setSelectedPositionInt(INVALID_POSITION); setNextSelectedPositionInt(INVALID_POSITION); invalidate(); } /** * @see android.view.View#measure(int, int) * * Figure out the dimensions of this Spinner. The width comes from * the widthMeasureSpec as Spinnners can't have their width set to * UNSPECIFIED. The height is based on the height of the selected item * plus padding. */ @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int widthMode = MeasureSpec.getMode(widthMeasureSpec); int widthSize; int heightSize; final int mPaddingLeft = getPaddingLeft(); final int mPaddingTop = getPaddingTop(); final int mPaddingRight = getPaddingRight(); final int mPaddingBottom = getPaddingBottom(); mSpinnerPadding.left = mPaddingLeft > mSelectionLeftPadding ? mPaddingLeft : mSelectionLeftPadding; mSpinnerPadding.top = mPaddingTop > mSelectionTopPadding ? mPaddingTop : mSelectionTopPadding; mSpinnerPadding.right = mPaddingRight > mSelectionRightPadding ? mPaddingRight : mSelectionRightPadding; mSpinnerPadding.bottom = mPaddingBottom > mSelectionBottomPadding ? mPaddingBottom : mSelectionBottomPadding; if (mDataChanged) { handleDataChanged(); } int preferredHeight = 0; int preferredWidth = 0; boolean needsMeasuring = true; int selectedPosition = getSelectedItemPosition(); if (selectedPosition >= 0 && mAdapter != null && selectedPosition < mAdapter.getCount()) { // Try looking in the recycler. (Maybe we were measured once already) View view = mRecycler.get(selectedPosition); if (view == null) { // Make a new one view = mAdapter.getView(selectedPosition, null, this); } if (view != null) { // Put in recycler for re-measuring and/or layout mRecycler.put(selectedPosition, view); } if (view != null) { if (view.getLayoutParams() == null) { mBlockLayoutRequests = true; view.setLayoutParams(generateDefaultLayoutParams()); mBlockLayoutRequests = false; } measureChild(view, widthMeasureSpec, heightMeasureSpec); preferredHeight = getChildHeight(view) + mSpinnerPadding.top + mSpinnerPadding.bottom; preferredWidth = getChildWidth(view) + mSpinnerPadding.left + mSpinnerPadding.right; needsMeasuring = false; } } if (needsMeasuring) { // No views -- just use padding preferredHeight = mSpinnerPadding.top + mSpinnerPadding.bottom; if (widthMode == MeasureSpec.UNSPECIFIED) { preferredWidth = mSpinnerPadding.left + mSpinnerPadding.right; } } preferredHeight = Math.max(preferredHeight, getSuggestedMinimumHeight()); preferredWidth = Math.max(preferredWidth, getSuggestedMinimumWidth()); if (IS_HONEYCOMB) { heightSize = resolveSizeAndState(preferredHeight, heightMeasureSpec, 0); widthSize = resolveSizeAndState(preferredWidth, widthMeasureSpec, 0); } else { heightSize = resolveSize(preferredHeight, heightMeasureSpec); widthSize = resolveSize(preferredWidth, widthMeasureSpec); } setMeasuredDimension(widthSize, heightSize); mHeightMeasureSpec = heightMeasureSpec; mWidthMeasureSpec = widthMeasureSpec; } int getChildHeight(View child) { return child.getMeasuredHeight(); } int getChildWidth(View child) { return child.getMeasuredWidth(); } @Override protected ViewGroup.LayoutParams generateDefaultLayoutParams() { return new ViewGroup.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT); } void recycleAllViews() { final int childCount = getChildCount(); final IcsAbsSpinner.RecycleBin recycleBin = mRecycler; final int position = mFirstPosition; // All views go in recycler for (int i = 0; i < childCount; i++) { View v = getChildAt(i); int index = position + i; recycleBin.put(index, v); } } /** * Jump directly to a specific item in the adapter data. */ public void setSelection(int position, boolean animate) { // Animate only if requested position is already on screen somewhere boolean shouldAnimate = animate && mFirstPosition <= position && position <= mFirstPosition + getChildCount() - 1; setSelectionInt(position, shouldAnimate); } @Override public void setSelection(int position) { setNextSelectedPositionInt(position); requestLayout(); invalidate(); } /** * Makes the item at the supplied position selected. * * @param position Position to select * @param animate Should the transition be animated * */ void setSelectionInt(int position, boolean animate) { if (position != mOldSelectedPosition) { mBlockLayoutRequests = true; int delta = position - mSelectedPosition; setNextSelectedPositionInt(position); layout(delta, animate); mBlockLayoutRequests = false; } } abstract void layout(int delta, boolean animate); @Override public View getSelectedView() { if (mItemCount > 0 && mSelectedPosition >= 0) { return getChildAt(mSelectedPosition - mFirstPosition); } else { return null; } } /** * Override to prevent spamming ourselves with layout requests * as we place views * * @see android.view.View#requestLayout() */ @Override public void requestLayout() { if (!mBlockLayoutRequests) { super.requestLayout(); } } @Override public SpinnerAdapter getAdapter() { return mAdapter; } @Override public int getCount() { return mItemCount; } /** * Maps a point to a position in the list. * * @param x X in local coordinate * @param y Y in local coordinate * @return The position of the item which contains the specified point, or * {@link #INVALID_POSITION} if the point does not intersect an item. */ public int pointToPosition(int x, int y) { Rect frame = mTouchFrame; if (frame == null) { mTouchFrame = new Rect(); frame = mTouchFrame; } final int count = getChildCount(); for (int i = count - 1; i >= 0; i--) { View child = getChildAt(i); if (child.getVisibility() == View.VISIBLE) { child.getHitRect(frame); if (frame.contains(x, y)) { return mFirstPosition + i; } } } return INVALID_POSITION; } static class SavedState extends BaseSavedState { long selectedId; int position; /** * Constructor called from {@link AbsSpinner#onSaveInstanceState()} */ SavedState(Parcelable superState) { super(superState); } /** * Constructor called from {@link #CREATOR} */ private SavedState(Parcel in) { super(in); selectedId = in.readLong(); position = in.readInt(); } @Override public void writeToParcel(Parcel out, int flags) { super.writeToParcel(out, flags); out.writeLong(selectedId); out.writeInt(position); } @Override public String toString() { return "AbsSpinner.SavedState{" + Integer.toHexString(System.identityHashCode(this)) + " selectedId=" + selectedId + " position=" + position + "}"; } public static final Parcelable.Creator<SavedState> CREATOR = new Parcelable.Creator<SavedState>() { public SavedState createFromParcel(Parcel in) { return new SavedState(in); } public SavedState[] newArray(int size) { return new SavedState[size]; } }; } @Override public Parcelable onSaveInstanceState() { Parcelable superState = super.onSaveInstanceState(); SavedState ss = new SavedState(superState); ss.selectedId = getSelectedItemId(); if (ss.selectedId >= 0) { ss.position = getSelectedItemPosition(); } else { ss.position = INVALID_POSITION; } return ss; } @Override public void onRestoreInstanceState(Parcelable state) { SavedState ss = (SavedState) state; super.onRestoreInstanceState(ss.getSuperState()); if (ss.selectedId >= 0) { mDataChanged = true; mNeedSync = true; mSyncRowId = ss.selectedId; mSyncPosition = ss.position; mSyncMode = SYNC_SELECTED_POSITION; requestLayout(); } } class RecycleBin { private final SparseArray<View> mScrapHeap = new SparseArray<View>(); public void put(int position, View v) { mScrapHeap.put(position, v); } View get(int position) { // System.out.print("Looking for " + position); View result = mScrapHeap.get(position); if (result != null) { // System.out.println(" HIT"); mScrapHeap.delete(position); } else { // System.out.println(" MISS"); } return result; } void clear() { final SparseArray<View> scrapHeap = mScrapHeap; final int count = scrapHeap.size(); for (int i = 0; i < count; i++) { final View view = scrapHeap.valueAt(i); if (view != null) { removeDetachedView(view, true); } } scrapHeap.clear(); } } }
Java
package com.actionbarsherlock.internal.widget; import com.actionbarsherlock.R; import android.content.Context; import android.content.res.Resources; import android.database.DataSetObserver; import android.graphics.Rect; import android.graphics.drawable.Drawable; import android.os.Build; import android.os.Handler; import android.util.AttributeSet; import android.view.ContextThemeWrapper; import android.view.MotionEvent; import android.view.View; import android.view.View.MeasureSpec; import android.view.View.OnTouchListener; import android.view.ViewGroup; import android.view.ViewParent; import android.widget.AbsListView; import android.widget.AdapterView; import android.widget.LinearLayout; import android.widget.ListAdapter; import android.widget.ListView; import android.widget.PopupWindow; /** * A proxy between pre- and post-Honeycomb implementations of this class. */ public class IcsListPopupWindow { /** * This value controls the length of time that the user * must leave a pointer down without scrolling to expand * the autocomplete dropdown list to cover the IME. */ private static final int EXPAND_LIST_TIMEOUT = 250; private Context mContext; private PopupWindow mPopup; private ListAdapter mAdapter; private DropDownListView mDropDownList; private int mDropDownHeight = ViewGroup.LayoutParams.WRAP_CONTENT; private int mDropDownWidth = ViewGroup.LayoutParams.WRAP_CONTENT; private int mDropDownHorizontalOffset; private int mDropDownVerticalOffset; private boolean mDropDownVerticalOffsetSet; private int mListItemExpandMaximum = Integer.MAX_VALUE; private View mPromptView; private int mPromptPosition = POSITION_PROMPT_ABOVE; private DataSetObserver mObserver; private View mDropDownAnchorView; private Drawable mDropDownListHighlight; private AdapterView.OnItemClickListener mItemClickListener; private AdapterView.OnItemSelectedListener mItemSelectedListener; private final ResizePopupRunnable mResizePopupRunnable = new ResizePopupRunnable(); private final PopupTouchInterceptor mTouchInterceptor = new PopupTouchInterceptor(); private final PopupScrollListener mScrollListener = new PopupScrollListener(); private final ListSelectorHider mHideSelector = new ListSelectorHider(); private Handler mHandler = new Handler(); private Rect mTempRect = new Rect(); private boolean mModal; public static final int POSITION_PROMPT_ABOVE = 0; public static final int POSITION_PROMPT_BELOW = 1; public IcsListPopupWindow(Context context) { this(context, null, R.attr.listPopupWindowStyle); } public IcsListPopupWindow(Context context, AttributeSet attrs, int defStyleAttr) { mContext = context; mPopup = new PopupWindow(context, attrs, defStyleAttr); mPopup.setInputMethodMode(PopupWindow.INPUT_METHOD_NEEDED); } public IcsListPopupWindow(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { mContext = context; if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) { Context wrapped = new ContextThemeWrapper(context, defStyleRes); mPopup = new PopupWindow(wrapped, attrs, defStyleAttr); } else { mPopup = new PopupWindow(context, attrs, defStyleAttr, defStyleRes); } mPopup.setInputMethodMode(PopupWindow.INPUT_METHOD_NEEDED); } public void setAdapter(ListAdapter adapter) { if (mObserver == null) { mObserver = new PopupDataSetObserver(); } else if (mAdapter != null) { mAdapter.unregisterDataSetObserver(mObserver); } mAdapter = adapter; if (mAdapter != null) { adapter.registerDataSetObserver(mObserver); } if (mDropDownList != null) { mDropDownList.setAdapter(mAdapter); } } public void setPromptPosition(int position) { mPromptPosition = position; } public void setModal(boolean modal) { mModal = true; mPopup.setFocusable(modal); } public void setBackgroundDrawable(Drawable d) { mPopup.setBackgroundDrawable(d); } public void setAnchorView(View anchor) { mDropDownAnchorView = anchor; } public void setHorizontalOffset(int offset) { mDropDownHorizontalOffset = offset; } public void setVerticalOffset(int offset) { mDropDownVerticalOffset = offset; mDropDownVerticalOffsetSet = true; } public void setContentWidth(int width) { Drawable popupBackground = mPopup.getBackground(); if (popupBackground != null) { popupBackground.getPadding(mTempRect); mDropDownWidth = mTempRect.left + mTempRect.right + width; } else { mDropDownWidth = width; } } public void setOnItemClickListener(AdapterView.OnItemClickListener clickListener) { mItemClickListener = clickListener; } public void show() { int height = buildDropDown(); int widthSpec = 0; int heightSpec = 0; boolean noInputMethod = isInputMethodNotNeeded(); //XXX mPopup.setAllowScrollingAnchorParent(!noInputMethod); if (mPopup.isShowing()) { if (mDropDownWidth == ViewGroup.LayoutParams.MATCH_PARENT) { // The call to PopupWindow's update method below can accept -1 for any // value you do not want to update. widthSpec = -1; } else if (mDropDownWidth == ViewGroup.LayoutParams.WRAP_CONTENT) { widthSpec = mDropDownAnchorView.getWidth(); } else { widthSpec = mDropDownWidth; } if (mDropDownHeight == ViewGroup.LayoutParams.MATCH_PARENT) { // The call to PopupWindow's update method below can accept -1 for any // value you do not want to update. heightSpec = noInputMethod ? height : ViewGroup.LayoutParams.MATCH_PARENT; if (noInputMethod) { mPopup.setWindowLayoutMode( mDropDownWidth == ViewGroup.LayoutParams.MATCH_PARENT ? ViewGroup.LayoutParams.MATCH_PARENT : 0, 0); } else { mPopup.setWindowLayoutMode( mDropDownWidth == ViewGroup.LayoutParams.MATCH_PARENT ? ViewGroup.LayoutParams.MATCH_PARENT : 0, ViewGroup.LayoutParams.MATCH_PARENT); } } else if (mDropDownHeight == ViewGroup.LayoutParams.WRAP_CONTENT) { heightSpec = height; } else { heightSpec = mDropDownHeight; } mPopup.setOutsideTouchable(true); mPopup.update(mDropDownAnchorView, mDropDownHorizontalOffset, mDropDownVerticalOffset, widthSpec, heightSpec); } else { if (mDropDownWidth == ViewGroup.LayoutParams.MATCH_PARENT) { widthSpec = ViewGroup.LayoutParams.MATCH_PARENT; } else { if (mDropDownWidth == ViewGroup.LayoutParams.WRAP_CONTENT) { mPopup.setWidth(mDropDownAnchorView.getWidth()); } else { mPopup.setWidth(mDropDownWidth); } } if (mDropDownHeight == ViewGroup.LayoutParams.MATCH_PARENT) { heightSpec = ViewGroup.LayoutParams.MATCH_PARENT; } else { if (mDropDownHeight == ViewGroup.LayoutParams.WRAP_CONTENT) { mPopup.setHeight(height); } else { mPopup.setHeight(mDropDownHeight); } } mPopup.setWindowLayoutMode(widthSpec, heightSpec); //XXX mPopup.setClipToScreenEnabled(true); // use outside touchable to dismiss drop down when touching outside of it, so // only set this if the dropdown is not always visible mPopup.setOutsideTouchable(true); mPopup.setTouchInterceptor(mTouchInterceptor); mPopup.showAsDropDown(mDropDownAnchorView, mDropDownHorizontalOffset, mDropDownVerticalOffset); mDropDownList.setSelection(ListView.INVALID_POSITION); if (!mModal || mDropDownList.isInTouchMode()) { clearListSelection(); } if (!mModal) { mHandler.post(mHideSelector); } } } public void dismiss() { mPopup.dismiss(); if (mPromptView != null) { final ViewParent parent = mPromptView.getParent(); if (parent instanceof ViewGroup) { final ViewGroup group = (ViewGroup) parent; group.removeView(mPromptView); } } mPopup.setContentView(null); mDropDownList = null; mHandler.removeCallbacks(mResizePopupRunnable); } public void setOnDismissListener(PopupWindow.OnDismissListener listener) { mPopup.setOnDismissListener(listener); } public void setInputMethodMode(int mode) { mPopup.setInputMethodMode(mode); } public void clearListSelection() { final DropDownListView list = mDropDownList; if (list != null) { // WARNING: Please read the comment where mListSelectionHidden is declared list.mListSelectionHidden = true; //XXX list.hideSelector(); list.requestLayout(); } } public boolean isShowing() { return mPopup.isShowing(); } private boolean isInputMethodNotNeeded() { return mPopup.getInputMethodMode() == PopupWindow.INPUT_METHOD_NOT_NEEDED; } public ListView getListView() { return mDropDownList; } private int buildDropDown() { ViewGroup dropDownView; int otherHeights = 0; if (mDropDownList == null) { Context context = mContext; mDropDownList = new DropDownListView(context, !mModal); if (mDropDownListHighlight != null) { mDropDownList.setSelector(mDropDownListHighlight); } mDropDownList.setAdapter(mAdapter); mDropDownList.setOnItemClickListener(mItemClickListener); mDropDownList.setFocusable(true); mDropDownList.setFocusableInTouchMode(true); mDropDownList.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { if (position != -1) { DropDownListView dropDownList = mDropDownList; if (dropDownList != null) { dropDownList.mListSelectionHidden = false; } } } public void onNothingSelected(AdapterView<?> parent) { } }); mDropDownList.setOnScrollListener(mScrollListener); if (mItemSelectedListener != null) { mDropDownList.setOnItemSelectedListener(mItemSelectedListener); } dropDownView = mDropDownList; View hintView = mPromptView; if (hintView != null) { // if an hint has been specified, we accomodate more space for it and // add a text view in the drop down menu, at the bottom of the list LinearLayout hintContainer = new LinearLayout(context); hintContainer.setOrientation(LinearLayout.VERTICAL); LinearLayout.LayoutParams hintParams = new LinearLayout.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, 0, 1.0f ); switch (mPromptPosition) { case POSITION_PROMPT_BELOW: hintContainer.addView(dropDownView, hintParams); hintContainer.addView(hintView); break; case POSITION_PROMPT_ABOVE: hintContainer.addView(hintView); hintContainer.addView(dropDownView, hintParams); break; default: break; } // measure the hint's height to find how much more vertical space // we need to add to the drop down's height int widthSpec = MeasureSpec.makeMeasureSpec(mDropDownWidth, MeasureSpec.AT_MOST); int heightSpec = MeasureSpec.UNSPECIFIED; hintView.measure(widthSpec, heightSpec); hintParams = (LinearLayout.LayoutParams) hintView.getLayoutParams(); otherHeights = hintView.getMeasuredHeight() + hintParams.topMargin + hintParams.bottomMargin; dropDownView = hintContainer; } mPopup.setContentView(dropDownView); } else { dropDownView = (ViewGroup) mPopup.getContentView(); final View view = mPromptView; if (view != null) { LinearLayout.LayoutParams hintParams = (LinearLayout.LayoutParams) view.getLayoutParams(); otherHeights = view.getMeasuredHeight() + hintParams.topMargin + hintParams.bottomMargin; } } // getMaxAvailableHeight() subtracts the padding, so we put it back // to get the available height for the whole window int padding = 0; Drawable background = mPopup.getBackground(); if (background != null) { background.getPadding(mTempRect); padding = mTempRect.top + mTempRect.bottom; // If we don't have an explicit vertical offset, determine one from the window // background so that content will line up. if (!mDropDownVerticalOffsetSet) { mDropDownVerticalOffset = -mTempRect.top; } } // Max height available on the screen for a popup. boolean ignoreBottomDecorations = mPopup.getInputMethodMode() == PopupWindow.INPUT_METHOD_NOT_NEEDED; final int maxHeight = /*mPopup.*/getMaxAvailableHeight( mDropDownAnchorView, mDropDownVerticalOffset, ignoreBottomDecorations); if (mDropDownHeight == ViewGroup.LayoutParams.MATCH_PARENT) { return maxHeight + padding; } final int listContent = /*mDropDownList.*/measureHeightOfChildren(MeasureSpec.UNSPECIFIED, 0, -1/*ListView.NO_POSITION*/, maxHeight - otherHeights, -1); // add padding only if the list has items in it, that way we don't show // the popup if it is not needed if (listContent > 0) otherHeights += padding; return listContent + otherHeights; } private int getMaxAvailableHeight(View anchor, int yOffset, boolean ignoreBottomDecorations) { final Rect displayFrame = new Rect(); anchor.getWindowVisibleDisplayFrame(displayFrame); final int[] anchorPos = new int[2]; anchor.getLocationOnScreen(anchorPos); int bottomEdge = displayFrame.bottom; if (ignoreBottomDecorations) { Resources res = anchor.getContext().getResources(); bottomEdge = res.getDisplayMetrics().heightPixels; } final int distanceToBottom = bottomEdge - (anchorPos[1] + anchor.getHeight()) - yOffset; final int distanceToTop = anchorPos[1] - displayFrame.top + yOffset; // anchorPos[1] is distance from anchor to top of screen int returnedHeight = Math.max(distanceToBottom, distanceToTop); if (mPopup.getBackground() != null) { mPopup.getBackground().getPadding(mTempRect); returnedHeight -= mTempRect.top + mTempRect.bottom; } return returnedHeight; } private int measureHeightOfChildren(int widthMeasureSpec, int startPosition, int endPosition, final int maxHeight, int disallowPartialChildPosition) { final ListAdapter adapter = mAdapter; if (adapter == null) { return mDropDownList.getListPaddingTop() + mDropDownList.getListPaddingBottom(); } // Include the padding of the list int returnedHeight = mDropDownList.getListPaddingTop() + mDropDownList.getListPaddingBottom(); final int dividerHeight = ((mDropDownList.getDividerHeight() > 0) && mDropDownList.getDivider() != null) ? mDropDownList.getDividerHeight() : 0; // The previous height value that was less than maxHeight and contained // no partial children int prevHeightWithoutPartialChild = 0; int i; View child; // mItemCount - 1 since endPosition parameter is inclusive endPosition = (endPosition == -1/*NO_POSITION*/) ? adapter.getCount() - 1 : endPosition; for (i = startPosition; i <= endPosition; ++i) { child = mAdapter.getView(i, null, mDropDownList); if (mDropDownList.getCacheColorHint() != 0) { child.setDrawingCacheBackgroundColor(mDropDownList.getCacheColorHint()); } measureScrapChild(child, i, widthMeasureSpec); if (i > 0) { // Count the divider for all but one child returnedHeight += dividerHeight; } returnedHeight += child.getMeasuredHeight(); if (returnedHeight >= maxHeight) { // We went over, figure out which height to return. If returnedHeight > maxHeight, // then the i'th position did not fit completely. return (disallowPartialChildPosition >= 0) // Disallowing is enabled (> -1) && (i > disallowPartialChildPosition) // We've past the min pos && (prevHeightWithoutPartialChild > 0) // We have a prev height && (returnedHeight != maxHeight) // i'th child did not fit completely ? prevHeightWithoutPartialChild : maxHeight; } if ((disallowPartialChildPosition >= 0) && (i >= disallowPartialChildPosition)) { prevHeightWithoutPartialChild = returnedHeight; } } // At this point, we went through the range of children, and they each // completely fit, so return the returnedHeight return returnedHeight; } private void measureScrapChild(View child, int position, int widthMeasureSpec) { ListView.LayoutParams p = (ListView.LayoutParams) child.getLayoutParams(); if (p == null) { p = new ListView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, 0); child.setLayoutParams(p); } //XXX p.viewType = mAdapter.getItemViewType(position); //XXX p.forceAdd = true; int childWidthSpec = ViewGroup.getChildMeasureSpec(widthMeasureSpec, mDropDownList.getPaddingLeft() + mDropDownList.getPaddingRight(), p.width); int lpHeight = p.height; int childHeightSpec; if (lpHeight > 0) { childHeightSpec = MeasureSpec.makeMeasureSpec(lpHeight, MeasureSpec.EXACTLY); } else { childHeightSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED); } child.measure(childWidthSpec, childHeightSpec); } private static class DropDownListView extends ListView { /* * WARNING: This is a workaround for a touch mode issue. * * Touch mode is propagated lazily to windows. This causes problems in * the following scenario: * - Type something in the AutoCompleteTextView and get some results * - Move down with the d-pad to select an item in the list * - Move up with the d-pad until the selection disappears * - Type more text in the AutoCompleteTextView *using the soft keyboard* * and get new results; you are now in touch mode * - The selection comes back on the first item in the list, even though * the list is supposed to be in touch mode * * Using the soft keyboard triggers the touch mode change but that change * is propagated to our window only after the first list layout, therefore * after the list attempts to resurrect the selection. * * The trick to work around this issue is to pretend the list is in touch * mode when we know that the selection should not appear, that is when * we know the user moved the selection away from the list. * * This boolean is set to true whenever we explicitly hide the list's * selection and reset to false whenever we know the user moved the * selection back to the list. * * When this boolean is true, isInTouchMode() returns true, otherwise it * returns super.isInTouchMode(). */ private boolean mListSelectionHidden; private boolean mHijackFocus; public DropDownListView(Context context, boolean hijackFocus) { super(context, null, /*com.android.internal.*/R.attr.dropDownListViewStyle); mHijackFocus = hijackFocus; // TODO: Add an API to control this setCacheColorHint(0); // Transparent, since the background drawable could be anything. } //XXX @Override //View obtainView(int position, boolean[] isScrap) { // View view = super.obtainView(position, isScrap); // if (view instanceof TextView) { // ((TextView) view).setHorizontallyScrolling(true); // } // return view; //} @Override public boolean isInTouchMode() { // WARNING: Please read the comment where mListSelectionHidden is declared return (mHijackFocus && mListSelectionHidden) || super.isInTouchMode(); } @Override public boolean hasWindowFocus() { return mHijackFocus || super.hasWindowFocus(); } @Override public boolean isFocused() { return mHijackFocus || super.isFocused(); } @Override public boolean hasFocus() { return mHijackFocus || super.hasFocus(); } } private class PopupDataSetObserver extends DataSetObserver { @Override public void onChanged() { if (isShowing()) { // Resize the popup to fit new content show(); } } @Override public void onInvalidated() { dismiss(); } } private class ListSelectorHider implements Runnable { public void run() { clearListSelection(); } } private class ResizePopupRunnable implements Runnable { public void run() { if (mDropDownList != null && mDropDownList.getCount() > mDropDownList.getChildCount() && mDropDownList.getChildCount() <= mListItemExpandMaximum) { mPopup.setInputMethodMode(PopupWindow.INPUT_METHOD_NOT_NEEDED); show(); } } } private class PopupTouchInterceptor implements OnTouchListener { public boolean onTouch(View v, MotionEvent event) { final int action = event.getAction(); final int x = (int) event.getX(); final int y = (int) event.getY(); if (action == MotionEvent.ACTION_DOWN && mPopup != null && mPopup.isShowing() && (x >= 0 && x < mPopup.getWidth() && y >= 0 && y < mPopup.getHeight())) { mHandler.postDelayed(mResizePopupRunnable, EXPAND_LIST_TIMEOUT); } else if (action == MotionEvent.ACTION_UP) { mHandler.removeCallbacks(mResizePopupRunnable); } return false; } } private class PopupScrollListener implements ListView.OnScrollListener { public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { } public void onScrollStateChanged(AbsListView view, int scrollState) { if (scrollState == SCROLL_STATE_TOUCH_SCROLL && !isInputMethodNotNeeded() && mPopup.getContentView() != null) { mHandler.removeCallbacks(mResizePopupRunnable); mResizePopupRunnable.run(); } } } }
Java
/* * Copyright (C) 2011 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.actionbarsherlock.internal.widget; import android.content.Context; import android.content.res.Configuration; import android.content.res.TypedArray; import android.os.Build; import android.util.AttributeSet; import android.view.View; import android.view.animation.DecelerateInterpolator; import android.view.animation.Interpolator; import com.actionbarsherlock.R; import com.actionbarsherlock.internal.nineoldandroids.animation.Animator; import com.actionbarsherlock.internal.nineoldandroids.animation.AnimatorSet; import com.actionbarsherlock.internal.nineoldandroids.animation.ObjectAnimator; import com.actionbarsherlock.internal.nineoldandroids.view.NineViewGroup; import com.actionbarsherlock.internal.view.menu.ActionMenuPresenter; import com.actionbarsherlock.internal.view.menu.ActionMenuView; import static com.actionbarsherlock.internal.ResourcesCompat.getResources_getBoolean; public abstract class AbsActionBarView extends NineViewGroup { protected ActionMenuView mMenuView; protected ActionMenuPresenter mActionMenuPresenter; protected ActionBarContainer mSplitView; protected boolean mSplitActionBar; protected boolean mSplitWhenNarrow; protected int mContentHeight; final Context mContext; protected Animator mVisibilityAnim; protected final VisibilityAnimListener mVisAnimListener = new VisibilityAnimListener(); private static final /*Time*/Interpolator sAlphaInterpolator = new DecelerateInterpolator(); private static final int FADE_DURATION = 200; public AbsActionBarView(Context context) { super(context); mContext = context; } public AbsActionBarView(Context context, AttributeSet attrs) { super(context, attrs); mContext = context; } public AbsActionBarView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); mContext = context; } /* * Must be public so we can dispatch pre-2.2 via ActionBarImpl. */ @Override public void onConfigurationChanged(Configuration newConfig) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO) { super.onConfigurationChanged(newConfig); } else if (mMenuView != null) { mMenuView.onConfigurationChanged(newConfig); } // Action bar can change size on configuration changes. // Reread the desired height from the theme-specified style. TypedArray a = getContext().obtainStyledAttributes(null, R.styleable.SherlockActionBar, R.attr.actionBarStyle, 0); setContentHeight(a.getLayoutDimension(R.styleable.SherlockActionBar_height, 0)); a.recycle(); if (mSplitWhenNarrow) { setSplitActionBar(getResources_getBoolean(getContext(), R.bool.abs__split_action_bar_is_narrow)); } if (mActionMenuPresenter != null) { mActionMenuPresenter.onConfigurationChanged(newConfig); } } /** * Sets whether the bar should be split right now, no questions asked. * @param split true if the bar should split */ public void setSplitActionBar(boolean split) { mSplitActionBar = split; } /** * Sets whether the bar should split if we enter a narrow screen configuration. * @param splitWhenNarrow true if the bar should check to split after a config change */ public void setSplitWhenNarrow(boolean splitWhenNarrow) { mSplitWhenNarrow = splitWhenNarrow; } public void setContentHeight(int height) { mContentHeight = height; requestLayout(); } public int getContentHeight() { return mContentHeight; } public void setSplitView(ActionBarContainer splitView) { mSplitView = splitView; } /** * @return Current visibility or if animating, the visibility being animated to. */ public int getAnimatedVisibility() { if (mVisibilityAnim != null) { return mVisAnimListener.mFinalVisibility; } return getVisibility(); } public void animateToVisibility(int visibility) { if (mVisibilityAnim != null) { mVisibilityAnim.cancel(); } if (visibility == VISIBLE) { if (getVisibility() != VISIBLE) { setAlpha(0); if (mSplitView != null && mMenuView != null) { mMenuView.setAlpha(0); } } ObjectAnimator anim = ObjectAnimator.ofFloat(this, "alpha", 1); anim.setDuration(FADE_DURATION); anim.setInterpolator(sAlphaInterpolator); if (mSplitView != null && mMenuView != null) { AnimatorSet set = new AnimatorSet(); ObjectAnimator splitAnim = ObjectAnimator.ofFloat(mMenuView, "alpha", 1); splitAnim.setDuration(FADE_DURATION); set.addListener(mVisAnimListener.withFinalVisibility(visibility)); set.play(anim).with(splitAnim); set.start(); } else { anim.addListener(mVisAnimListener.withFinalVisibility(visibility)); anim.start(); } } else { ObjectAnimator anim = ObjectAnimator.ofFloat(this, "alpha", 0); anim.setDuration(FADE_DURATION); anim.setInterpolator(sAlphaInterpolator); if (mSplitView != null && mMenuView != null) { AnimatorSet set = new AnimatorSet(); ObjectAnimator splitAnim = ObjectAnimator.ofFloat(mMenuView, "alpha", 0); splitAnim.setDuration(FADE_DURATION); set.addListener(mVisAnimListener.withFinalVisibility(visibility)); set.play(anim).with(splitAnim); set.start(); } else { anim.addListener(mVisAnimListener.withFinalVisibility(visibility)); anim.start(); } } } @Override public void setVisibility(int visibility) { if (mVisibilityAnim != null) { mVisibilityAnim.end(); } super.setVisibility(visibility); } public boolean showOverflowMenu() { if (mActionMenuPresenter != null) { return mActionMenuPresenter.showOverflowMenu(); } return false; } public void postShowOverflowMenu() { post(new Runnable() { public void run() { showOverflowMenu(); } }); } public boolean hideOverflowMenu() { if (mActionMenuPresenter != null) { return mActionMenuPresenter.hideOverflowMenu(); } return false; } public boolean isOverflowMenuShowing() { if (mActionMenuPresenter != null) { return mActionMenuPresenter.isOverflowMenuShowing(); } return false; } public boolean isOverflowReserved() { return mActionMenuPresenter != null && mActionMenuPresenter.isOverflowReserved(); } public void dismissPopupMenus() { if (mActionMenuPresenter != null) { mActionMenuPresenter.dismissPopupMenus(); } } protected int measureChildView(View child, int availableWidth, int childSpecHeight, int spacing) { child.measure(MeasureSpec.makeMeasureSpec(availableWidth, MeasureSpec.AT_MOST), childSpecHeight); availableWidth -= child.getMeasuredWidth(); availableWidth -= spacing; return Math.max(0, availableWidth); } protected int positionChild(View child, int x, int y, int contentHeight) { int childWidth = child.getMeasuredWidth(); int childHeight = child.getMeasuredHeight(); int childTop = y + (contentHeight - childHeight) / 2; child.layout(x, childTop, x + childWidth, childTop + childHeight); return childWidth; } protected int positionChildInverse(View child, int x, int y, int contentHeight) { int childWidth = child.getMeasuredWidth(); int childHeight = child.getMeasuredHeight(); int childTop = y + (contentHeight - childHeight) / 2; child.layout(x - childWidth, childTop, x, childTop + childHeight); return childWidth; } protected class VisibilityAnimListener implements Animator.AnimatorListener { private boolean mCanceled = false; int mFinalVisibility; public VisibilityAnimListener withFinalVisibility(int visibility) { mFinalVisibility = visibility; return this; } @Override public void onAnimationStart(Animator animation) { setVisibility(VISIBLE); mVisibilityAnim = animation; mCanceled = false; } @Override public void onAnimationEnd(Animator animation) { if (mCanceled) return; mVisibilityAnim = null; setVisibility(mFinalVisibility); if (mSplitView != null && mMenuView != null) { mMenuView.setVisibility(mFinalVisibility); } } @Override public void onAnimationCancel(Animator animation) { mCanceled = true; } @Override public void onAnimationRepeat(Animator animation) { } } }
Java
/* * Copyright (C) 2011 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.actionbarsherlock.internal.widget; import android.content.Context; import android.content.res.Configuration; import android.content.res.TypedArray; import android.graphics.drawable.Drawable; import android.text.TextUtils.TruncateAt; import android.util.AttributeSet; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.ViewParent; import android.view.animation.DecelerateInterpolator; import android.view.animation.Interpolator; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ListView; import com.actionbarsherlock.R; import com.actionbarsherlock.app.ActionBar; import com.actionbarsherlock.internal.nineoldandroids.animation.Animator; import com.actionbarsherlock.internal.nineoldandroids.animation.ObjectAnimator; import com.actionbarsherlock.internal.nineoldandroids.widget.NineHorizontalScrollView; /** * This widget implements the dynamic action bar tab behavior that can change * across different configurations or circumstances. */ public class ScrollingTabContainerView extends NineHorizontalScrollView implements IcsAdapterView.OnItemSelectedListener { //UNUSED private static final String TAG = "ScrollingTabContainerView"; Runnable mTabSelector; private TabClickListener mTabClickListener; private IcsLinearLayout mTabLayout; private IcsSpinner mTabSpinner; private boolean mAllowCollapse; private LayoutInflater mInflater; int mMaxTabWidth; private int mContentHeight; private int mSelectedTabIndex; protected Animator mVisibilityAnim; protected final VisibilityAnimListener mVisAnimListener = new VisibilityAnimListener(); private static final /*Time*/Interpolator sAlphaInterpolator = new DecelerateInterpolator(); private static final int FADE_DURATION = 200; public ScrollingTabContainerView(Context context) { super(context); setHorizontalScrollBarEnabled(false); TypedArray a = getContext().obtainStyledAttributes(null, R.styleable.SherlockActionBar, R.attr.actionBarStyle, 0); setContentHeight(a.getLayoutDimension(R.styleable.SherlockActionBar_height, 0)); a.recycle(); mInflater = LayoutInflater.from(context); mTabLayout = createTabLayout(); addView(mTabLayout, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT)); } @Override public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { final int widthMode = MeasureSpec.getMode(widthMeasureSpec); final boolean lockedExpanded = widthMode == MeasureSpec.EXACTLY; setFillViewport(lockedExpanded); final int childCount = mTabLayout.getChildCount(); if (childCount > 1 && (widthMode == MeasureSpec.EXACTLY || widthMode == MeasureSpec.AT_MOST)) { if (childCount > 2) { mMaxTabWidth = (int) (MeasureSpec.getSize(widthMeasureSpec) * 0.4f); } else { mMaxTabWidth = MeasureSpec.getSize(widthMeasureSpec) / 2; } } else { mMaxTabWidth = -1; } heightMeasureSpec = MeasureSpec.makeMeasureSpec(mContentHeight, MeasureSpec.EXACTLY); final boolean canCollapse = !lockedExpanded && mAllowCollapse; if (canCollapse) { // See if we should expand mTabLayout.measure(MeasureSpec.UNSPECIFIED, heightMeasureSpec); if (mTabLayout.getMeasuredWidth() > MeasureSpec.getSize(widthMeasureSpec)) { performCollapse(); } else { performExpand(); } } else { performExpand(); } final int oldWidth = getMeasuredWidth(); super.onMeasure(widthMeasureSpec, heightMeasureSpec); final int newWidth = getMeasuredWidth(); if (lockedExpanded && oldWidth != newWidth) { // Recenter the tab display if we're at a new (scrollable) size. setTabSelected(mSelectedTabIndex); } } /** * Indicates whether this view is collapsed into a dropdown menu instead * of traditional tabs. * @return true if showing as a spinner */ private boolean isCollapsed() { return mTabSpinner != null && mTabSpinner.getParent() == this; } public void setAllowCollapse(boolean allowCollapse) { mAllowCollapse = allowCollapse; } private void performCollapse() { if (isCollapsed()) return; if (mTabSpinner == null) { mTabSpinner = createSpinner(); } removeView(mTabLayout); addView(mTabSpinner, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT)); if (mTabSpinner.getAdapter() == null) { mTabSpinner.setAdapter(new TabAdapter()); } if (mTabSelector != null) { removeCallbacks(mTabSelector); mTabSelector = null; } mTabSpinner.setSelection(mSelectedTabIndex); } private boolean performExpand() { if (!isCollapsed()) return false; removeView(mTabSpinner); addView(mTabLayout, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT)); setTabSelected(mTabSpinner.getSelectedItemPosition()); return false; } public void setTabSelected(int position) { mSelectedTabIndex = position; final int tabCount = mTabLayout.getChildCount(); for (int i = 0; i < tabCount; i++) { final View child = mTabLayout.getChildAt(i); final boolean isSelected = i == position; child.setSelected(isSelected); if (isSelected) { animateToTab(position); } } } public void setContentHeight(int contentHeight) { mContentHeight = contentHeight; requestLayout(); } private IcsLinearLayout createTabLayout() { final IcsLinearLayout tabLayout = (IcsLinearLayout) LayoutInflater.from(getContext()) .inflate(R.layout.abs__action_bar_tab_bar_view, null); tabLayout.setLayoutParams(new LinearLayout.LayoutParams( LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.MATCH_PARENT)); return tabLayout; } private IcsSpinner createSpinner() { final IcsSpinner spinner = new IcsSpinner(getContext(), null, R.attr.actionDropDownStyle); spinner.setLayoutParams(new LinearLayout.LayoutParams( LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.MATCH_PARENT)); spinner.setOnItemSelectedListener(this); return spinner; } @Override protected void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); // Action bar can change size on configuration changes. // Reread the desired height from the theme-specified style. TypedArray a = getContext().obtainStyledAttributes(null, R.styleable.SherlockActionBar, R.attr.actionBarStyle, 0); setContentHeight(a.getLayoutDimension(R.styleable.SherlockActionBar_height, 0)); a.recycle(); } public void animateToVisibility(int visibility) { if (mVisibilityAnim != null) { mVisibilityAnim.cancel(); } if (visibility == VISIBLE) { if (getVisibility() != VISIBLE) { setAlpha(0); } ObjectAnimator anim = ObjectAnimator.ofFloat(this, "alpha", 1); anim.setDuration(FADE_DURATION); anim.setInterpolator(sAlphaInterpolator); anim.addListener(mVisAnimListener.withFinalVisibility(visibility)); anim.start(); } else { ObjectAnimator anim = ObjectAnimator.ofFloat(this, "alpha", 0); anim.setDuration(FADE_DURATION); anim.setInterpolator(sAlphaInterpolator); anim.addListener(mVisAnimListener.withFinalVisibility(visibility)); anim.start(); } } public void animateToTab(final int position) { final View tabView = mTabLayout.getChildAt(position); if (mTabSelector != null) { removeCallbacks(mTabSelector); } mTabSelector = new Runnable() { public void run() { final int scrollPos = tabView.getLeft() - (getWidth() - tabView.getWidth()) / 2; smoothScrollTo(scrollPos, 0); mTabSelector = null; } }; post(mTabSelector); } @Override public void onAttachedToWindow() { super.onAttachedToWindow(); if (mTabSelector != null) { // Re-post the selector we saved post(mTabSelector); } } @Override public void onDetachedFromWindow() { super.onDetachedFromWindow(); if (mTabSelector != null) { removeCallbacks(mTabSelector); } } private TabView createTabView(ActionBar.Tab tab, boolean forAdapter) { //Workaround for not being able to pass a defStyle on pre-3.0 final TabView tabView = (TabView)mInflater.inflate(R.layout.abs__action_bar_tab, null); tabView.init(this, tab, forAdapter); if (forAdapter) { tabView.setBackgroundDrawable(null); tabView.setLayoutParams(new ListView.LayoutParams(ListView.LayoutParams.MATCH_PARENT, mContentHeight)); } else { tabView.setFocusable(true); if (mTabClickListener == null) { mTabClickListener = new TabClickListener(); } tabView.setOnClickListener(mTabClickListener); } return tabView; } public void addTab(ActionBar.Tab tab, boolean setSelected) { TabView tabView = createTabView(tab, false); mTabLayout.addView(tabView, new IcsLinearLayout.LayoutParams(0, LayoutParams.MATCH_PARENT, 1)); if (mTabSpinner != null) { ((TabAdapter) mTabSpinner.getAdapter()).notifyDataSetChanged(); } if (setSelected) { tabView.setSelected(true); } if (mAllowCollapse) { requestLayout(); } } public void addTab(ActionBar.Tab tab, int position, boolean setSelected) { final TabView tabView = createTabView(tab, false); mTabLayout.addView(tabView, position, new IcsLinearLayout.LayoutParams( 0, LayoutParams.MATCH_PARENT, 1)); if (mTabSpinner != null) { ((TabAdapter) mTabSpinner.getAdapter()).notifyDataSetChanged(); } if (setSelected) { tabView.setSelected(true); } if (mAllowCollapse) { requestLayout(); } } public void updateTab(int position) { ((TabView) mTabLayout.getChildAt(position)).update(); if (mTabSpinner != null) { ((TabAdapter) mTabSpinner.getAdapter()).notifyDataSetChanged(); } if (mAllowCollapse) { requestLayout(); } } public void removeTabAt(int position) { mTabLayout.removeViewAt(position); if (mTabSpinner != null) { ((TabAdapter) mTabSpinner.getAdapter()).notifyDataSetChanged(); } if (mAllowCollapse) { requestLayout(); } } public void removeAllTabs() { mTabLayout.removeAllViews(); if (mTabSpinner != null) { ((TabAdapter) mTabSpinner.getAdapter()).notifyDataSetChanged(); } if (mAllowCollapse) { requestLayout(); } } @Override public void onItemSelected(IcsAdapterView<?> parent, View view, int position, long id) { TabView tabView = (TabView) view; tabView.getTab().select(); } @Override public void onNothingSelected(IcsAdapterView<?> parent) { } public static class TabView extends LinearLayout { private ScrollingTabContainerView mParent; private ActionBar.Tab mTab; private CapitalizingTextView mTextView; private ImageView mIconView; private View mCustomView; public TabView(Context context, AttributeSet attrs) { //TODO super(context, null, R.attr.actionBarTabStyle); super(context, attrs); } public void init(ScrollingTabContainerView parent, ActionBar.Tab tab, boolean forList) { mParent = parent; mTab = tab; if (forList) { setGravity(Gravity.LEFT | Gravity.CENTER_VERTICAL); } update(); } public void bindTab(ActionBar.Tab tab) { mTab = tab; update(); } @Override public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); // Re-measure if we went beyond our maximum size. if (mParent.mMaxTabWidth > 0 && getMeasuredWidth() > mParent.mMaxTabWidth) { super.onMeasure(MeasureSpec.makeMeasureSpec(mParent.mMaxTabWidth, MeasureSpec.EXACTLY), heightMeasureSpec); } } public void update() { final ActionBar.Tab tab = mTab; final View custom = tab.getCustomView(); if (custom != null) { final ViewParent customParent = custom.getParent(); if (customParent != this) { if (customParent != null) ((ViewGroup) customParent).removeView(custom); addView(custom); } mCustomView = custom; if (mTextView != null) mTextView.setVisibility(GONE); if (mIconView != null) { mIconView.setVisibility(GONE); mIconView.setImageDrawable(null); } } else { if (mCustomView != null) { removeView(mCustomView); mCustomView = null; } final Drawable icon = tab.getIcon(); final CharSequence text = tab.getText(); if (icon != null) { if (mIconView == null) { ImageView iconView = new ImageView(getContext()); LayoutParams lp = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); lp.gravity = Gravity.CENTER_VERTICAL; iconView.setLayoutParams(lp); addView(iconView, 0); mIconView = iconView; } mIconView.setImageDrawable(icon); mIconView.setVisibility(VISIBLE); } else if (mIconView != null) { mIconView.setVisibility(GONE); mIconView.setImageDrawable(null); } if (text != null) { if (mTextView == null) { CapitalizingTextView textView = new CapitalizingTextView(getContext(), null, R.attr.actionBarTabTextStyle); textView.setEllipsize(TruncateAt.END); LayoutParams lp = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); lp.gravity = Gravity.CENTER_VERTICAL; textView.setLayoutParams(lp); addView(textView); mTextView = textView; } mTextView.setTextCompat(text); mTextView.setVisibility(VISIBLE); } else if (mTextView != null) { mTextView.setVisibility(GONE); mTextView.setText(null); } if (mIconView != null) { mIconView.setContentDescription(tab.getContentDescription()); } } } public ActionBar.Tab getTab() { return mTab; } } private class TabAdapter extends BaseAdapter { @Override public int getCount() { return mTabLayout.getChildCount(); } @Override public Object getItem(int position) { return ((TabView) mTabLayout.getChildAt(position)).getTab(); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { if (convertView == null) { convertView = createTabView((ActionBar.Tab) getItem(position), true); } else { ((TabView) convertView).bindTab((ActionBar.Tab) getItem(position)); } return convertView; } } private class TabClickListener implements OnClickListener { public void onClick(View view) { TabView tabView = (TabView) view; tabView.getTab().select(); final int tabCount = mTabLayout.getChildCount(); for (int i = 0; i < tabCount; i++) { final View child = mTabLayout.getChildAt(i); child.setSelected(child == view); } } } protected class VisibilityAnimListener implements Animator.AnimatorListener { private boolean mCanceled = false; private int mFinalVisibility; public VisibilityAnimListener withFinalVisibility(int visibility) { mFinalVisibility = visibility; return this; } @Override public void onAnimationStart(Animator animation) { setVisibility(VISIBLE); mVisibilityAnim = animation; mCanceled = false; } @Override public void onAnimationEnd(Animator animation) { if (mCanceled) return; mVisibilityAnim = null; setVisibility(mFinalVisibility); } @Override public void onAnimationCancel(Animator animation) { mCanceled = true; } @Override public void onAnimationRepeat(Animator animation) { } } }
Java
/* * Copyright (C) 2007 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.actionbarsherlock.internal.widget; import static android.view.ViewGroup.LayoutParams.MATCH_PARENT; import static android.view.ViewGroup.LayoutParams.WRAP_CONTENT; import com.actionbarsherlock.R; import android.content.Context; import android.content.DialogInterface; import android.content.DialogInterface.OnClickListener; import android.content.res.TypedArray; import android.database.DataSetObserver; import android.graphics.Rect; import android.graphics.drawable.Drawable; import android.util.AttributeSet; import android.view.Gravity; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ListAdapter; import android.widget.ListView; import android.widget.PopupWindow; import android.widget.SpinnerAdapter; /** * A view that displays one child at a time and lets the user pick among them. * The items in the Spinner come from the {@link Adapter} associated with * this view. * * <p>See the <a href="{@docRoot}resources/tutorials/views/hello-spinner.html">Spinner * tutorial</a>.</p> * * @attr ref android.R.styleable#Spinner_prompt */ public class IcsSpinner extends IcsAbsSpinner implements OnClickListener { //private static final String TAG = "Spinner"; // Only measure this many items to get a decent max width. private static final int MAX_ITEMS_MEASURED = 15; /** * Use a dialog window for selecting spinner options. */ //public static final int MODE_DIALOG = 0; /** * Use a dropdown anchored to the Spinner for selecting spinner options. */ public static final int MODE_DROPDOWN = 1; /** * Use the theme-supplied value to select the dropdown mode. */ //private static final int MODE_THEME = -1; private SpinnerPopup mPopup; private DropDownAdapter mTempAdapter; int mDropDownWidth; private int mGravity; private boolean mDisableChildrenWhenDisabled; private Rect mTempRect = new Rect(); public IcsSpinner(Context context, AttributeSet attrs) { this(context, attrs, R.attr.actionDropDownStyle); } /** * Construct a new spinner with the given context's theme, the supplied attribute set, * and default style. * * @param context The Context the view is running in, through which it can * access the current theme, resources, etc. * @param attrs The attributes of the XML tag that is inflating the view. * @param defStyle The default style to apply to this view. If 0, no style * will be applied (beyond what is included in the theme). This may * either be an attribute resource, whose value will be retrieved * from the current theme, or an explicit style resource. */ public IcsSpinner(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.SherlockSpinner, defStyle, 0); DropdownPopup popup = new DropdownPopup(context, attrs, defStyle); mDropDownWidth = a.getLayoutDimension( R.styleable.SherlockSpinner_android_dropDownWidth, ViewGroup.LayoutParams.WRAP_CONTENT); popup.setBackgroundDrawable(a.getDrawable( R.styleable.SherlockSpinner_android_popupBackground)); final int verticalOffset = a.getDimensionPixelOffset( R.styleable.SherlockSpinner_android_dropDownVerticalOffset, 0); if (verticalOffset != 0) { popup.setVerticalOffset(verticalOffset); } final int horizontalOffset = a.getDimensionPixelOffset( R.styleable.SherlockSpinner_android_dropDownHorizontalOffset, 0); if (horizontalOffset != 0) { popup.setHorizontalOffset(horizontalOffset); } mPopup = popup; mGravity = a.getInt(R.styleable.SherlockSpinner_android_gravity, Gravity.CENTER); mPopup.setPromptText(a.getString(R.styleable.SherlockSpinner_android_prompt)); mDisableChildrenWhenDisabled = true; a.recycle(); // Base constructor can call setAdapter before we initialize mPopup. // Finish setting things up if this happened. if (mTempAdapter != null) { mPopup.setAdapter(mTempAdapter); mTempAdapter = null; } } @Override public void setEnabled(boolean enabled) { super.setEnabled(enabled); if (mDisableChildrenWhenDisabled) { final int count = getChildCount(); for (int i = 0; i < count; i++) { getChildAt(i).setEnabled(enabled); } } } /** * Describes how the selected item view is positioned. Currently only the horizontal component * is used. The default is determined by the current theme. * * @param gravity See {@link android.view.Gravity} * * @attr ref android.R.styleable#Spinner_gravity */ public void setGravity(int gravity) { if (mGravity != gravity) { if ((gravity & Gravity.HORIZONTAL_GRAVITY_MASK) == 0) { gravity |= Gravity.LEFT; } mGravity = gravity; requestLayout(); } } @Override public void setAdapter(SpinnerAdapter adapter) { super.setAdapter(adapter); if (mPopup != null) { mPopup.setAdapter(new DropDownAdapter(adapter)); } else { mTempAdapter = new DropDownAdapter(adapter); } } @Override public int getBaseline() { View child = null; if (getChildCount() > 0) { child = getChildAt(0); } else if (mAdapter != null && mAdapter.getCount() > 0) { child = makeAndAddView(0); mRecycler.put(0, child); removeAllViewsInLayout(); } if (child != null) { final int childBaseline = child.getBaseline(); return childBaseline >= 0 ? child.getTop() + childBaseline : -1; } else { return -1; } } @Override protected void onDetachedFromWindow() { super.onDetachedFromWindow(); if (mPopup != null && mPopup.isShowing()) { mPopup.dismiss(); } } /** * <p>A spinner does not support item click events. Calling this method * will raise an exception.</p> * * @param l this listener will be ignored */ @Override public void setOnItemClickListener(OnItemClickListener l) { throw new RuntimeException("setOnItemClickListener cannot be used with a spinner."); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); if (mPopup != null && MeasureSpec.getMode(widthMeasureSpec) == MeasureSpec.AT_MOST) { final int measuredWidth = getMeasuredWidth(); setMeasuredDimension(Math.min(Math.max(measuredWidth, measureContentWidth(getAdapter(), getBackground())), MeasureSpec.getSize(widthMeasureSpec)), getMeasuredHeight()); } } /** * @see android.view.View#onLayout(boolean,int,int,int,int) * * Creates and positions all views * */ @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { super.onLayout(changed, l, t, r, b); mInLayout = true; layout(0, false); mInLayout = false; } /** * Creates and positions all views for this Spinner. * * @param delta Change in the selected position. +1 moves selection is moving to the right, * so views are scrolling to the left. -1 means selection is moving to the left. */ @Override void layout(int delta, boolean animate) { int childrenLeft = mSpinnerPadding.left; int childrenWidth = getRight() - getLeft() - mSpinnerPadding.left - mSpinnerPadding.right; if (mDataChanged) { handleDataChanged(); } // Handle the empty set by removing all views if (mItemCount == 0) { resetList(); return; } if (mNextSelectedPosition >= 0) { setSelectedPositionInt(mNextSelectedPosition); } recycleAllViews(); // Clear out old views removeAllViewsInLayout(); // Make selected view and position it mFirstPosition = mSelectedPosition; View sel = makeAndAddView(mSelectedPosition); int width = sel.getMeasuredWidth(); int selectedOffset = childrenLeft; switch (mGravity & Gravity.HORIZONTAL_GRAVITY_MASK) { case Gravity.CENTER_HORIZONTAL: selectedOffset = childrenLeft + (childrenWidth / 2) - (width / 2); break; case Gravity.RIGHT: selectedOffset = childrenLeft + childrenWidth - width; break; } sel.offsetLeftAndRight(selectedOffset); // Flush any cached views that did not get reused above mRecycler.clear(); invalidate(); checkSelectionChanged(); mDataChanged = false; mNeedSync = false; setNextSelectedPositionInt(mSelectedPosition); } /** * Obtain a view, either by pulling an existing view from the recycler or * by getting a new one from the adapter. If we are animating, make sure * there is enough information in the view's layout parameters to animate * from the old to new positions. * * @param position Position in the spinner for the view to obtain * @return A view that has been added to the spinner */ private View makeAndAddView(int position) { View child; if (!mDataChanged) { child = mRecycler.get(position); if (child != null) { // Position the view setUpChild(child); return child; } } // Nothing found in the recycler -- ask the adapter for a view child = mAdapter.getView(position, null, this); // Position the view setUpChild(child); return child; } /** * Helper for makeAndAddView to set the position of a view * and fill out its layout paramters. * * @param child The view to position */ private void setUpChild(View child) { // Respect layout params that are already in the view. Otherwise // make some up... ViewGroup.LayoutParams lp = child.getLayoutParams(); if (lp == null) { lp = generateDefaultLayoutParams(); } addViewInLayout(child, 0, lp); child.setSelected(hasFocus()); if (mDisableChildrenWhenDisabled) { child.setEnabled(isEnabled()); } // Get measure specs int childHeightSpec = ViewGroup.getChildMeasureSpec(mHeightMeasureSpec, mSpinnerPadding.top + mSpinnerPadding.bottom, lp.height); int childWidthSpec = ViewGroup.getChildMeasureSpec(mWidthMeasureSpec, mSpinnerPadding.left + mSpinnerPadding.right, lp.width); // Measure child child.measure(childWidthSpec, childHeightSpec); int childLeft; int childRight; // Position vertically based on gravity setting int childTop = mSpinnerPadding.top + ((getMeasuredHeight() - mSpinnerPadding.bottom - mSpinnerPadding.top - child.getMeasuredHeight()) / 2); int childBottom = childTop + child.getMeasuredHeight(); int width = child.getMeasuredWidth(); childLeft = 0; childRight = childLeft + width; child.layout(childLeft, childTop, childRight, childBottom); } @Override public boolean performClick() { boolean handled = super.performClick(); if (!handled) { handled = true; if (!mPopup.isShowing()) { mPopup.show(); } } return handled; } public void onClick(DialogInterface dialog, int which) { setSelection(which); dialog.dismiss(); } /** * Sets the prompt to display when the dialog is shown. * @param prompt the prompt to set */ public void setPrompt(CharSequence prompt) { mPopup.setPromptText(prompt); } /** * Sets the prompt to display when the dialog is shown. * @param promptId the resource ID of the prompt to display when the dialog is shown */ public void setPromptId(int promptId) { setPrompt(getContext().getText(promptId)); } /** * @return The prompt to display when the dialog is shown */ public CharSequence getPrompt() { return mPopup.getHintText(); } int measureContentWidth(SpinnerAdapter adapter, Drawable background) { if (adapter == null) { return 0; } int width = 0; View itemView = null; int itemType = 0; final int widthMeasureSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED); final int heightMeasureSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED); // Make sure the number of items we'll measure is capped. If it's a huge data set // with wildly varying sizes, oh well. int start = Math.max(0, getSelectedItemPosition()); final int end = Math.min(adapter.getCount(), start + MAX_ITEMS_MEASURED); final int count = end - start; start = Math.max(0, start - (MAX_ITEMS_MEASURED - count)); for (int i = start; i < end; i++) { final int positionType = adapter.getItemViewType(i); if (positionType != itemType) { itemType = positionType; itemView = null; } itemView = adapter.getView(i, itemView, this); if (itemView.getLayoutParams() == null) { itemView.setLayoutParams(new ViewGroup.LayoutParams( ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT)); } itemView.measure(widthMeasureSpec, heightMeasureSpec); width = Math.max(width, itemView.getMeasuredWidth()); } // Add background padding to measured width if (background != null) { background.getPadding(mTempRect); width += mTempRect.left + mTempRect.right; } return width; } /** * <p>Wrapper class for an Adapter. Transforms the embedded Adapter instance * into a ListAdapter.</p> */ private static class DropDownAdapter implements ListAdapter, SpinnerAdapter { private SpinnerAdapter mAdapter; private ListAdapter mListAdapter; /** * <p>Creates a new ListAdapter wrapper for the specified adapter.</p> * * @param adapter the Adapter to transform into a ListAdapter */ public DropDownAdapter(SpinnerAdapter adapter) { this.mAdapter = adapter; if (adapter instanceof ListAdapter) { this.mListAdapter = (ListAdapter) adapter; } } public int getCount() { return mAdapter == null ? 0 : mAdapter.getCount(); } public Object getItem(int position) { return mAdapter == null ? null : mAdapter.getItem(position); } public long getItemId(int position) { return mAdapter == null ? -1 : mAdapter.getItemId(position); } public View getView(int position, View convertView, ViewGroup parent) { return getDropDownView(position, convertView, parent); } public View getDropDownView(int position, View convertView, ViewGroup parent) { return mAdapter == null ? null : mAdapter.getDropDownView(position, convertView, parent); } public boolean hasStableIds() { return mAdapter != null && mAdapter.hasStableIds(); } public void registerDataSetObserver(DataSetObserver observer) { if (mAdapter != null) { mAdapter.registerDataSetObserver(observer); } } public void unregisterDataSetObserver(DataSetObserver observer) { if (mAdapter != null) { mAdapter.unregisterDataSetObserver(observer); } } /** * If the wrapped SpinnerAdapter is also a ListAdapter, delegate this call. * Otherwise, return true. */ public boolean areAllItemsEnabled() { final ListAdapter adapter = mListAdapter; if (adapter != null) { return adapter.areAllItemsEnabled(); } else { return true; } } /** * If the wrapped SpinnerAdapter is also a ListAdapter, delegate this call. * Otherwise, return true. */ public boolean isEnabled(int position) { final ListAdapter adapter = mListAdapter; if (adapter != null) { return adapter.isEnabled(position); } else { return true; } } public int getItemViewType(int position) { return 0; } public int getViewTypeCount() { return 1; } public boolean isEmpty() { return getCount() == 0; } } /** * Implements some sort of popup selection interface for selecting a spinner option. * Allows for different spinner modes. */ private interface SpinnerPopup { public void setAdapter(ListAdapter adapter); /** * Show the popup */ public void show(); /** * Dismiss the popup */ public void dismiss(); /** * @return true if the popup is showing, false otherwise. */ public boolean isShowing(); /** * Set hint text to be displayed to the user. This should provide * a description of the choice being made. * @param hintText Hint text to set. */ public void setPromptText(CharSequence hintText); public CharSequence getHintText(); } /* private class DialogPopup implements SpinnerPopup, DialogInterface.OnClickListener { private AlertDialog mPopup; private ListAdapter mListAdapter; private CharSequence mPrompt; public void dismiss() { mPopup.dismiss(); mPopup = null; } public boolean isShowing() { return mPopup != null ? mPopup.isShowing() : false; } public void setAdapter(ListAdapter adapter) { mListAdapter = adapter; } public void setPromptText(CharSequence hintText) { mPrompt = hintText; } public CharSequence getHintText() { return mPrompt; } public void show() { AlertDialog.Builder builder = new AlertDialog.Builder(getContext()); if (mPrompt != null) { builder.setTitle(mPrompt); } mPopup = builder.setSingleChoiceItems(mListAdapter, getSelectedItemPosition(), this).show(); } public void onClick(DialogInterface dialog, int which) { setSelection(which); dismiss(); } } */ private class DropdownPopup extends IcsListPopupWindow implements SpinnerPopup { private CharSequence mHintText; private ListAdapter mAdapter; public DropdownPopup(Context context, AttributeSet attrs, int defStyleRes) { super(context, attrs, 0, defStyleRes); setAnchorView(IcsSpinner.this); setModal(true); setPromptPosition(POSITION_PROMPT_ABOVE); setOnItemClickListener(new OnItemClickListener() { @SuppressWarnings("rawtypes") public void onItemClick(AdapterView parent, View v, int position, long id) { IcsSpinner.this.setSelection(position); dismiss(); } }); } @Override public void setAdapter(ListAdapter adapter) { super.setAdapter(adapter); mAdapter = adapter; } public CharSequence getHintText() { return mHintText; } public void setPromptText(CharSequence hintText) { // Hint text is ignored for dropdowns, but maintain it here. mHintText = hintText; } @Override public void show() { final int spinnerPaddingLeft = IcsSpinner.this.getPaddingLeft(); if (mDropDownWidth == WRAP_CONTENT) { final int spinnerWidth = IcsSpinner.this.getWidth(); final int spinnerPaddingRight = IcsSpinner.this.getPaddingRight(); setContentWidth(Math.max( measureContentWidth((SpinnerAdapter) mAdapter, getBackground()), spinnerWidth - spinnerPaddingLeft - spinnerPaddingRight)); } else if (mDropDownWidth == MATCH_PARENT) { final int spinnerWidth = IcsSpinner.this.getWidth(); final int spinnerPaddingRight = IcsSpinner.this.getPaddingRight(); setContentWidth(spinnerWidth - spinnerPaddingLeft - spinnerPaddingRight); } else { setContentWidth(mDropDownWidth); } final Drawable background = getBackground(); int bgOffset = 0; if (background != null) { background.getPadding(mTempRect); bgOffset = -mTempRect.left; } setHorizontalOffset(bgOffset + spinnerPaddingLeft); setInputMethodMode(PopupWindow.INPUT_METHOD_NOT_NEEDED); super.show(); getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE); setSelection(IcsSpinner.this.getSelectedItemPosition()); } } }
Java
/* * Copyright (C) 2010 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.actionbarsherlock.internal.widget; import org.xmlpull.v1.XmlPullParser; import android.app.Activity; import android.content.Context; import android.content.pm.ApplicationInfo; import android.content.pm.PackageManager; import android.content.pm.PackageManager.NameNotFoundException; import android.content.res.AssetManager; import android.content.res.Configuration; import android.content.res.TypedArray; import android.content.res.XmlResourceParser; import android.graphics.drawable.Drawable; import android.os.Build; import android.os.Parcel; import android.os.Parcelable; import android.text.TextUtils; import android.util.AttributeSet; import android.util.Log; import android.view.Gravity; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.view.ViewParent; import android.view.accessibility.AccessibilityEvent; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.SpinnerAdapter; import android.widget.TextView; import com.actionbarsherlock.R; import com.actionbarsherlock.app.ActionBar; import com.actionbarsherlock.app.ActionBar.OnNavigationListener; import com.actionbarsherlock.internal.ActionBarSherlockCompat; import com.actionbarsherlock.internal.view.menu.ActionMenuItem; import com.actionbarsherlock.internal.view.menu.ActionMenuPresenter; import com.actionbarsherlock.internal.view.menu.ActionMenuView; import com.actionbarsherlock.internal.view.menu.MenuBuilder; import com.actionbarsherlock.internal.view.menu.MenuItemImpl; import com.actionbarsherlock.internal.view.menu.MenuPresenter; import com.actionbarsherlock.internal.view.menu.MenuView; import com.actionbarsherlock.internal.view.menu.SubMenuBuilder; import com.actionbarsherlock.view.CollapsibleActionView; import com.actionbarsherlock.view.Menu; import com.actionbarsherlock.view.MenuItem; import com.actionbarsherlock.view.Window; import static com.actionbarsherlock.internal.ResourcesCompat.getResources_getBoolean; /** * @hide */ public class ActionBarView extends AbsActionBarView { private static final String TAG = "ActionBarView"; private static final boolean DEBUG = false; /** * Display options applied by default */ public static final int DISPLAY_DEFAULT = 0; /** * Display options that require re-layout as opposed to a simple invalidate */ private static final int DISPLAY_RELAYOUT_MASK = ActionBar.DISPLAY_SHOW_HOME | ActionBar.DISPLAY_USE_LOGO | ActionBar.DISPLAY_HOME_AS_UP | ActionBar.DISPLAY_SHOW_CUSTOM | ActionBar.DISPLAY_SHOW_TITLE; private static final int DEFAULT_CUSTOM_GRAVITY = Gravity.LEFT | Gravity.CENTER_VERTICAL; private int mNavigationMode; private int mDisplayOptions = -1; private CharSequence mTitle; private CharSequence mSubtitle; private Drawable mIcon; private Drawable mLogo; private HomeView mHomeLayout; private HomeView mExpandedHomeLayout; private LinearLayout mTitleLayout; private TextView mTitleView; private TextView mSubtitleView; private View mTitleUpView; private IcsSpinner mSpinner; private IcsLinearLayout mListNavLayout; private ScrollingTabContainerView mTabScrollView; private View mCustomNavView; private IcsProgressBar mProgressView; private IcsProgressBar mIndeterminateProgressView; private int mProgressBarPadding; private int mItemPadding; private int mTitleStyleRes; private int mSubtitleStyleRes; private int mProgressStyle; private int mIndeterminateProgressStyle; private boolean mUserTitle; private boolean mIncludeTabs; private boolean mIsCollapsable; private boolean mIsCollapsed; private MenuBuilder mOptionsMenu; private ActionBarContextView mContextView; private ActionMenuItem mLogoNavItem; private SpinnerAdapter mSpinnerAdapter; private OnNavigationListener mCallback; //UNUSED private Runnable mTabSelector; private ExpandedActionViewMenuPresenter mExpandedMenuPresenter; View mExpandedActionView; Window.Callback mWindowCallback; @SuppressWarnings("rawtypes") private final IcsAdapterView.OnItemSelectedListener mNavItemSelectedListener = new IcsAdapterView.OnItemSelectedListener() { public void onItemSelected(IcsAdapterView parent, View view, int position, long id) { if (mCallback != null) { mCallback.onNavigationItemSelected(position, id); } } public void onNothingSelected(IcsAdapterView parent) { // Do nothing } }; private final OnClickListener mExpandedActionViewUpListener = new OnClickListener() { @Override public void onClick(View v) { final MenuItemImpl item = mExpandedMenuPresenter.mCurrentExpandedItem; if (item != null) { item.collapseActionView(); } } }; private final OnClickListener mUpClickListener = new OnClickListener() { public void onClick(View v) { mWindowCallback.onMenuItemSelected(Window.FEATURE_OPTIONS_PANEL, mLogoNavItem); } }; public ActionBarView(Context context, AttributeSet attrs) { super(context, attrs); // Background is always provided by the container. setBackgroundResource(0); TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.SherlockActionBar, R.attr.actionBarStyle, 0); ApplicationInfo appInfo = context.getApplicationInfo(); PackageManager pm = context.getPackageManager(); mNavigationMode = a.getInt(R.styleable.SherlockActionBar_navigationMode, ActionBar.NAVIGATION_MODE_STANDARD); mTitle = a.getText(R.styleable.SherlockActionBar_title); mSubtitle = a.getText(R.styleable.SherlockActionBar_subtitle); mLogo = a.getDrawable(R.styleable.SherlockActionBar_logo); if (mLogo == null) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) { if (context instanceof Activity) { //Even though native methods existed in API 9 and 10 they don't work //so just parse the manifest to look for the logo pre-Honeycomb final int resId = loadLogoFromManifest((Activity) context); if (resId != 0) { mLogo = context.getResources().getDrawable(resId); } } } else { if (context instanceof Activity) { try { mLogo = pm.getActivityLogo(((Activity) context).getComponentName()); } catch (NameNotFoundException e) { Log.e(TAG, "Activity component name not found!", e); } } if (mLogo == null) { mLogo = appInfo.loadLogo(pm); } } } mIcon = a.getDrawable(R.styleable.SherlockActionBar_icon); if (mIcon == null) { if (context instanceof Activity) { try { mIcon = pm.getActivityIcon(((Activity) context).getComponentName()); } catch (NameNotFoundException e) { Log.e(TAG, "Activity component name not found!", e); } } if (mIcon == null) { mIcon = appInfo.loadIcon(pm); } } final LayoutInflater inflater = LayoutInflater.from(context); final int homeResId = a.getResourceId( R.styleable.SherlockActionBar_homeLayout, R.layout.abs__action_bar_home); mHomeLayout = (HomeView) inflater.inflate(homeResId, this, false); mExpandedHomeLayout = (HomeView) inflater.inflate(homeResId, this, false); mExpandedHomeLayout.setUp(true); mExpandedHomeLayout.setOnClickListener(mExpandedActionViewUpListener); mExpandedHomeLayout.setContentDescription(getResources().getText( R.string.abs__action_bar_up_description)); mTitleStyleRes = a.getResourceId(R.styleable.SherlockActionBar_titleTextStyle, 0); mSubtitleStyleRes = a.getResourceId(R.styleable.SherlockActionBar_subtitleTextStyle, 0); mProgressStyle = a.getResourceId(R.styleable.SherlockActionBar_progressBarStyle, 0); mIndeterminateProgressStyle = a.getResourceId( R.styleable.SherlockActionBar_indeterminateProgressStyle, 0); mProgressBarPadding = a.getDimensionPixelOffset(R.styleable.SherlockActionBar_progressBarPadding, 0); mItemPadding = a.getDimensionPixelOffset(R.styleable.SherlockActionBar_itemPadding, 0); setDisplayOptions(a.getInt(R.styleable.SherlockActionBar_displayOptions, DISPLAY_DEFAULT)); final int customNavId = a.getResourceId(R.styleable.SherlockActionBar_customNavigationLayout, 0); if (customNavId != 0) { mCustomNavView = inflater.inflate(customNavId, this, false); mNavigationMode = ActionBar.NAVIGATION_MODE_STANDARD; setDisplayOptions(mDisplayOptions | ActionBar.DISPLAY_SHOW_CUSTOM); } mContentHeight = a.getLayoutDimension(R.styleable.SherlockActionBar_height, 0); a.recycle(); mLogoNavItem = new ActionMenuItem(context, 0, android.R.id.home, 0, 0, mTitle); mHomeLayout.setOnClickListener(mUpClickListener); mHomeLayout.setClickable(true); mHomeLayout.setFocusable(true); } /** * Attempt to programmatically load the logo from the manifest file of an * activity by using an XML pull parser. This should allow us to read the * logo attribute regardless of the platform it is being run on. * * @param activity Activity instance. * @return Logo resource ID. */ private static int loadLogoFromManifest(Activity activity) { int logo = 0; try { final String thisPackage = activity.getClass().getName(); if (DEBUG) Log.i(TAG, "Parsing AndroidManifest.xml for " + thisPackage); final String packageName = activity.getApplicationInfo().packageName; final AssetManager am = activity.createPackageContext(packageName, 0).getAssets(); final XmlResourceParser xml = am.openXmlResourceParser("AndroidManifest.xml"); int eventType = xml.getEventType(); while (eventType != XmlPullParser.END_DOCUMENT) { if (eventType == XmlPullParser.START_TAG) { String name = xml.getName(); if ("application".equals(name)) { //Check if the <application> has the attribute if (DEBUG) Log.d(TAG, "Got <application>"); for (int i = xml.getAttributeCount() - 1; i >= 0; i--) { if (DEBUG) Log.d(TAG, xml.getAttributeName(i) + ": " + xml.getAttributeValue(i)); if ("logo".equals(xml.getAttributeName(i))) { logo = xml.getAttributeResourceValue(i, 0); break; //out of for loop } } } else if ("activity".equals(name)) { //Check if the <activity> is us and has the attribute if (DEBUG) Log.d(TAG, "Got <activity>"); Integer activityLogo = null; String activityPackage = null; boolean isOurActivity = false; for (int i = xml.getAttributeCount() - 1; i >= 0; i--) { if (DEBUG) Log.d(TAG, xml.getAttributeName(i) + ": " + xml.getAttributeValue(i)); //We need both uiOptions and name attributes String attrName = xml.getAttributeName(i); if ("logo".equals(attrName)) { activityLogo = xml.getAttributeResourceValue(i, 0); } else if ("name".equals(attrName)) { activityPackage = ActionBarSherlockCompat.cleanActivityName(packageName, xml.getAttributeValue(i)); if (!thisPackage.equals(activityPackage)) { break; //on to the next } isOurActivity = true; } //Make sure we have both attributes before processing if ((activityLogo != null) && (activityPackage != null)) { //Our activity, logo specified, override with our value logo = activityLogo.intValue(); } } if (isOurActivity) { //If we matched our activity but it had no logo don't //do any more processing of the manifest break; } } } eventType = xml.nextToken(); } } catch (Exception e) { e.printStackTrace(); } if (DEBUG) Log.i(TAG, "Returning " + Integer.toHexString(logo)); return logo; } /* * Must be public so we can dispatch pre-2.2 via ActionBarImpl. */ @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); mTitleView = null; mSubtitleView = null; mTitleUpView = null; if (mTitleLayout != null && mTitleLayout.getParent() == this) { removeView(mTitleLayout); } mTitleLayout = null; if ((mDisplayOptions & ActionBar.DISPLAY_SHOW_TITLE) != 0) { initTitle(); } if (mTabScrollView != null && mIncludeTabs) { ViewGroup.LayoutParams lp = mTabScrollView.getLayoutParams(); if (lp != null) { lp.width = LayoutParams.WRAP_CONTENT; lp.height = LayoutParams.MATCH_PARENT; } mTabScrollView.setAllowCollapse(true); } } /** * Set the window callback used to invoke menu items; used for dispatching home button presses. * @param cb Window callback to dispatch to */ public void setWindowCallback(Window.Callback cb) { mWindowCallback = cb; } @Override public void onDetachedFromWindow() { super.onDetachedFromWindow(); //UNUSED removeCallbacks(mTabSelector); if (mActionMenuPresenter != null) { mActionMenuPresenter.hideOverflowMenu(); mActionMenuPresenter.hideSubMenus(); } } @Override public boolean shouldDelayChildPressedState() { return false; } public void initProgress() { mProgressView = new IcsProgressBar(mContext, null, 0, mProgressStyle); mProgressView.setId(R.id.abs__progress_horizontal); mProgressView.setMax(10000); addView(mProgressView); } public void initIndeterminateProgress() { mIndeterminateProgressView = new IcsProgressBar(mContext, null, 0, mIndeterminateProgressStyle); mIndeterminateProgressView.setId(R.id.abs__progress_circular); addView(mIndeterminateProgressView); } @Override public void setSplitActionBar(boolean splitActionBar) { if (mSplitActionBar != splitActionBar) { if (mMenuView != null) { final ViewGroup oldParent = (ViewGroup) mMenuView.getParent(); if (oldParent != null) { oldParent.removeView(mMenuView); } if (splitActionBar) { if (mSplitView != null) { mSplitView.addView(mMenuView); } } else { addView(mMenuView); } } if (mSplitView != null) { mSplitView.setVisibility(splitActionBar ? VISIBLE : GONE); } super.setSplitActionBar(splitActionBar); } } public boolean isSplitActionBar() { return mSplitActionBar; } public boolean hasEmbeddedTabs() { return mIncludeTabs; } public void setEmbeddedTabView(ScrollingTabContainerView tabs) { if (mTabScrollView != null) { removeView(mTabScrollView); } mTabScrollView = tabs; mIncludeTabs = tabs != null; if (mIncludeTabs && mNavigationMode == ActionBar.NAVIGATION_MODE_TABS) { addView(mTabScrollView); ViewGroup.LayoutParams lp = mTabScrollView.getLayoutParams(); lp.width = LayoutParams.WRAP_CONTENT; lp.height = LayoutParams.MATCH_PARENT; tabs.setAllowCollapse(true); } } public void setCallback(OnNavigationListener callback) { mCallback = callback; } public void setMenu(Menu menu, MenuPresenter.Callback cb) { if (menu == mOptionsMenu) return; if (mOptionsMenu != null) { mOptionsMenu.removeMenuPresenter(mActionMenuPresenter); mOptionsMenu.removeMenuPresenter(mExpandedMenuPresenter); } MenuBuilder builder = (MenuBuilder) menu; mOptionsMenu = builder; if (mMenuView != null) { final ViewGroup oldParent = (ViewGroup) mMenuView.getParent(); if (oldParent != null) { oldParent.removeView(mMenuView); } } if (mActionMenuPresenter == null) { mActionMenuPresenter = new ActionMenuPresenter(mContext); mActionMenuPresenter.setCallback(cb); mActionMenuPresenter.setId(R.id.abs__action_menu_presenter); mExpandedMenuPresenter = new ExpandedActionViewMenuPresenter(); } ActionMenuView menuView; final LayoutParams layoutParams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT); if (!mSplitActionBar) { mActionMenuPresenter.setExpandedActionViewsExclusive( getResources_getBoolean(getContext(), R.bool.abs__action_bar_expanded_action_views_exclusive)); configPresenters(builder); menuView = (ActionMenuView) mActionMenuPresenter.getMenuView(this); final ViewGroup oldParent = (ViewGroup) menuView.getParent(); if (oldParent != null && oldParent != this) { oldParent.removeView(menuView); } addView(menuView, layoutParams); } else { mActionMenuPresenter.setExpandedActionViewsExclusive(false); // Allow full screen width in split mode. mActionMenuPresenter.setWidthLimit( getContext().getResources().getDisplayMetrics().widthPixels, true); // No limit to the item count; use whatever will fit. mActionMenuPresenter.setItemLimit(Integer.MAX_VALUE); // Span the whole width layoutParams.width = LayoutParams.MATCH_PARENT; configPresenters(builder); menuView = (ActionMenuView) mActionMenuPresenter.getMenuView(this); if (mSplitView != null) { final ViewGroup oldParent = (ViewGroup) menuView.getParent(); if (oldParent != null && oldParent != mSplitView) { oldParent.removeView(menuView); } menuView.setVisibility(getAnimatedVisibility()); mSplitView.addView(menuView, layoutParams); } else { // We'll add this later if we missed it this time. menuView.setLayoutParams(layoutParams); } } mMenuView = menuView; } private void configPresenters(MenuBuilder builder) { if (builder != null) { builder.addMenuPresenter(mActionMenuPresenter); builder.addMenuPresenter(mExpandedMenuPresenter); } else { mActionMenuPresenter.initForMenu(mContext, null); mExpandedMenuPresenter.initForMenu(mContext, null); mActionMenuPresenter.updateMenuView(true); mExpandedMenuPresenter.updateMenuView(true); } } public boolean hasExpandedActionView() { return mExpandedMenuPresenter != null && mExpandedMenuPresenter.mCurrentExpandedItem != null; } public void collapseActionView() { final MenuItemImpl item = mExpandedMenuPresenter == null ? null : mExpandedMenuPresenter.mCurrentExpandedItem; if (item != null) { item.collapseActionView(); } } public void setCustomNavigationView(View view) { final boolean showCustom = (mDisplayOptions & ActionBar.DISPLAY_SHOW_CUSTOM) != 0; if (mCustomNavView != null && showCustom) { removeView(mCustomNavView); } mCustomNavView = view; if (mCustomNavView != null && showCustom) { addView(mCustomNavView); } } public CharSequence getTitle() { return mTitle; } /** * Set the action bar title. This will always replace or override window titles. * @param title Title to set * * @see #setWindowTitle(CharSequence) */ public void setTitle(CharSequence title) { mUserTitle = true; setTitleImpl(title); } /** * Set the window title. A window title will always be replaced or overridden by a user title. * @param title Title to set * * @see #setTitle(CharSequence) */ public void setWindowTitle(CharSequence title) { if (!mUserTitle) { setTitleImpl(title); } } private void setTitleImpl(CharSequence title) { mTitle = title; if (mTitleView != null) { mTitleView.setText(title); final boolean visible = mExpandedActionView == null && (mDisplayOptions & ActionBar.DISPLAY_SHOW_TITLE) != 0 && (!TextUtils.isEmpty(mTitle) || !TextUtils.isEmpty(mSubtitle)); mTitleLayout.setVisibility(visible ? VISIBLE : GONE); } if (mLogoNavItem != null) { mLogoNavItem.setTitle(title); } } public CharSequence getSubtitle() { return mSubtitle; } public void setSubtitle(CharSequence subtitle) { mSubtitle = subtitle; if (mSubtitleView != null) { mSubtitleView.setText(subtitle); mSubtitleView.setVisibility(subtitle != null ? VISIBLE : GONE); final boolean visible = mExpandedActionView == null && (mDisplayOptions & ActionBar.DISPLAY_SHOW_TITLE) != 0 && (!TextUtils.isEmpty(mTitle) || !TextUtils.isEmpty(mSubtitle)); mTitleLayout.setVisibility(visible ? VISIBLE : GONE); } } public void setHomeButtonEnabled(boolean enable) { mHomeLayout.setEnabled(enable); mHomeLayout.setFocusable(enable); // Make sure the home button has an accurate content description for accessibility. if (!enable) { mHomeLayout.setContentDescription(null); } else if ((mDisplayOptions & ActionBar.DISPLAY_HOME_AS_UP) != 0) { mHomeLayout.setContentDescription(mContext.getResources().getText( R.string.abs__action_bar_up_description)); } else { mHomeLayout.setContentDescription(mContext.getResources().getText( R.string.abs__action_bar_home_description)); } } public void setDisplayOptions(int options) { final int flagsChanged = mDisplayOptions == -1 ? -1 : options ^ mDisplayOptions; mDisplayOptions = options; if ((flagsChanged & DISPLAY_RELAYOUT_MASK) != 0) { final boolean showHome = (options & ActionBar.DISPLAY_SHOW_HOME) != 0; final int vis = showHome && mExpandedActionView == null ? VISIBLE : GONE; mHomeLayout.setVisibility(vis); if ((flagsChanged & ActionBar.DISPLAY_HOME_AS_UP) != 0) { final boolean setUp = (options & ActionBar.DISPLAY_HOME_AS_UP) != 0; mHomeLayout.setUp(setUp); // Showing home as up implicitly enables interaction with it. // In honeycomb it was always enabled, so make this transition // a bit easier for developers in the common case. // (It would be silly to show it as up without responding to it.) if (setUp) { setHomeButtonEnabled(true); } } if ((flagsChanged & ActionBar.DISPLAY_USE_LOGO) != 0) { final boolean logoVis = mLogo != null && (options & ActionBar.DISPLAY_USE_LOGO) != 0; mHomeLayout.setIcon(logoVis ? mLogo : mIcon); } if ((flagsChanged & ActionBar.DISPLAY_SHOW_TITLE) != 0) { if ((options & ActionBar.DISPLAY_SHOW_TITLE) != 0) { initTitle(); } else { removeView(mTitleLayout); } } if (mTitleLayout != null && (flagsChanged & (ActionBar.DISPLAY_HOME_AS_UP | ActionBar.DISPLAY_SHOW_HOME)) != 0) { final boolean homeAsUp = (mDisplayOptions & ActionBar.DISPLAY_HOME_AS_UP) != 0; mTitleUpView.setVisibility(!showHome ? (homeAsUp ? VISIBLE : INVISIBLE) : GONE); mTitleLayout.setEnabled(!showHome && homeAsUp); } if ((flagsChanged & ActionBar.DISPLAY_SHOW_CUSTOM) != 0 && mCustomNavView != null) { if ((options & ActionBar.DISPLAY_SHOW_CUSTOM) != 0) { addView(mCustomNavView); } else { removeView(mCustomNavView); } } requestLayout(); } else { invalidate(); } // Make sure the home button has an accurate content description for accessibility. if (!mHomeLayout.isEnabled()) { mHomeLayout.setContentDescription(null); } else if ((options & ActionBar.DISPLAY_HOME_AS_UP) != 0) { mHomeLayout.setContentDescription(mContext.getResources().getText( R.string.abs__action_bar_up_description)); } else { mHomeLayout.setContentDescription(mContext.getResources().getText( R.string.abs__action_bar_home_description)); } } public void setIcon(Drawable icon) { mIcon = icon; if (icon != null && ((mDisplayOptions & ActionBar.DISPLAY_USE_LOGO) == 0 || mLogo == null)) { mHomeLayout.setIcon(icon); } } public void setIcon(int resId) { setIcon(mContext.getResources().getDrawable(resId)); } public void setLogo(Drawable logo) { mLogo = logo; if (logo != null && (mDisplayOptions & ActionBar.DISPLAY_USE_LOGO) != 0) { mHomeLayout.setIcon(logo); } } public void setLogo(int resId) { setLogo(mContext.getResources().getDrawable(resId)); } public void setNavigationMode(int mode) { final int oldMode = mNavigationMode; if (mode != oldMode) { switch (oldMode) { case ActionBar.NAVIGATION_MODE_LIST: if (mListNavLayout != null) { removeView(mListNavLayout); } break; case ActionBar.NAVIGATION_MODE_TABS: if (mTabScrollView != null && mIncludeTabs) { removeView(mTabScrollView); } } switch (mode) { case ActionBar.NAVIGATION_MODE_LIST: if (mSpinner == null) { mSpinner = new IcsSpinner(mContext, null, R.attr.actionDropDownStyle); mListNavLayout = (IcsLinearLayout) LayoutInflater.from(mContext) .inflate(R.layout.abs__action_bar_tab_bar_view, null); LinearLayout.LayoutParams params = new LinearLayout.LayoutParams( LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT); params.gravity = Gravity.CENTER; mListNavLayout.addView(mSpinner, params); } if (mSpinner.getAdapter() != mSpinnerAdapter) { mSpinner.setAdapter(mSpinnerAdapter); } mSpinner.setOnItemSelectedListener(mNavItemSelectedListener); addView(mListNavLayout); break; case ActionBar.NAVIGATION_MODE_TABS: if (mTabScrollView != null && mIncludeTabs) { addView(mTabScrollView); } break; } mNavigationMode = mode; requestLayout(); } } public void setDropdownAdapter(SpinnerAdapter adapter) { mSpinnerAdapter = adapter; if (mSpinner != null) { mSpinner.setAdapter(adapter); } } public SpinnerAdapter getDropdownAdapter() { return mSpinnerAdapter; } public void setDropdownSelectedPosition(int position) { mSpinner.setSelection(position); } public int getDropdownSelectedPosition() { return mSpinner.getSelectedItemPosition(); } public View getCustomNavigationView() { return mCustomNavView; } public int getNavigationMode() { return mNavigationMode; } public int getDisplayOptions() { return mDisplayOptions; } @Override protected ViewGroup.LayoutParams generateDefaultLayoutParams() { // Used by custom nav views if they don't supply layout params. Everything else // added to an ActionBarView should have them already. return new ActionBar.LayoutParams(DEFAULT_CUSTOM_GRAVITY); } @Override protected void onFinishInflate() { super.onFinishInflate(); addView(mHomeLayout); if (mCustomNavView != null && (mDisplayOptions & ActionBar.DISPLAY_SHOW_CUSTOM) != 0) { final ViewParent parent = mCustomNavView.getParent(); if (parent != this) { if (parent instanceof ViewGroup) { ((ViewGroup) parent).removeView(mCustomNavView); } addView(mCustomNavView); } } } private void initTitle() { if (mTitleLayout == null) { LayoutInflater inflater = LayoutInflater.from(getContext()); mTitleLayout = (LinearLayout) inflater.inflate(R.layout.abs__action_bar_title_item, this, false); mTitleView = (TextView) mTitleLayout.findViewById(R.id.abs__action_bar_title); mSubtitleView = (TextView) mTitleLayout.findViewById(R.id.abs__action_bar_subtitle); mTitleUpView = mTitleLayout.findViewById(R.id.abs__up); mTitleLayout.setOnClickListener(mUpClickListener); if (mTitleStyleRes != 0) { mTitleView.setTextAppearance(mContext, mTitleStyleRes); } if (mTitle != null) { mTitleView.setText(mTitle); } if (mSubtitleStyleRes != 0) { mSubtitleView.setTextAppearance(mContext, mSubtitleStyleRes); } if (mSubtitle != null) { mSubtitleView.setText(mSubtitle); mSubtitleView.setVisibility(VISIBLE); } final boolean homeAsUp = (mDisplayOptions & ActionBar.DISPLAY_HOME_AS_UP) != 0; final boolean showHome = (mDisplayOptions & ActionBar.DISPLAY_SHOW_HOME) != 0; mTitleUpView.setVisibility(!showHome ? (homeAsUp ? VISIBLE : INVISIBLE) : GONE); mTitleLayout.setEnabled(homeAsUp && !showHome); } addView(mTitleLayout); if (mExpandedActionView != null || (TextUtils.isEmpty(mTitle) && TextUtils.isEmpty(mSubtitle))) { // Don't show while in expanded mode or with empty text mTitleLayout.setVisibility(GONE); } } public void setContextView(ActionBarContextView view) { mContextView = view; } public void setCollapsable(boolean collapsable) { mIsCollapsable = collapsable; } public boolean isCollapsed() { return mIsCollapsed; } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { final int childCount = getChildCount(); if (mIsCollapsable) { int visibleChildren = 0; for (int i = 0; i < childCount; i++) { final View child = getChildAt(i); if (child.getVisibility() != GONE && !(child == mMenuView && mMenuView.getChildCount() == 0)) { visibleChildren++; } } if (visibleChildren == 0) { // No size for an empty action bar when collapsable. setMeasuredDimension(0, 0); mIsCollapsed = true; return; } } mIsCollapsed = false; int widthMode = MeasureSpec.getMode(widthMeasureSpec); if (widthMode != MeasureSpec.EXACTLY) { throw new IllegalStateException(getClass().getSimpleName() + " can only be used " + "with android:layout_width=\"match_parent\" (or fill_parent)"); } int heightMode = MeasureSpec.getMode(heightMeasureSpec); if (heightMode != MeasureSpec.AT_MOST) { throw new IllegalStateException(getClass().getSimpleName() + " can only be used " + "with android:layout_height=\"wrap_content\""); } int contentWidth = MeasureSpec.getSize(widthMeasureSpec); int maxHeight = mContentHeight > 0 ? mContentHeight : MeasureSpec.getSize(heightMeasureSpec); final int verticalPadding = getPaddingTop() + getPaddingBottom(); final int paddingLeft = getPaddingLeft(); final int paddingRight = getPaddingRight(); final int height = maxHeight - verticalPadding; final int childSpecHeight = MeasureSpec.makeMeasureSpec(height, MeasureSpec.AT_MOST); int availableWidth = contentWidth - paddingLeft - paddingRight; int leftOfCenter = availableWidth / 2; int rightOfCenter = leftOfCenter; HomeView homeLayout = mExpandedActionView != null ? mExpandedHomeLayout : mHomeLayout; if (homeLayout.getVisibility() != GONE) { final ViewGroup.LayoutParams lp = homeLayout.getLayoutParams(); int homeWidthSpec; if (lp.width < 0) { homeWidthSpec = MeasureSpec.makeMeasureSpec(availableWidth, MeasureSpec.AT_MOST); } else { homeWidthSpec = MeasureSpec.makeMeasureSpec(lp.width, MeasureSpec.EXACTLY); } homeLayout.measure(homeWidthSpec, MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY)); final int homeWidth = homeLayout.getMeasuredWidth() + homeLayout.getLeftOffset(); availableWidth = Math.max(0, availableWidth - homeWidth); leftOfCenter = Math.max(0, availableWidth - homeWidth); } if (mMenuView != null && mMenuView.getParent() == this) { availableWidth = measureChildView(mMenuView, availableWidth, childSpecHeight, 0); rightOfCenter = Math.max(0, rightOfCenter - mMenuView.getMeasuredWidth()); } if (mIndeterminateProgressView != null && mIndeterminateProgressView.getVisibility() != GONE) { availableWidth = measureChildView(mIndeterminateProgressView, availableWidth, childSpecHeight, 0); rightOfCenter = Math.max(0, rightOfCenter - mIndeterminateProgressView.getMeasuredWidth()); } final boolean showTitle = mTitleLayout != null && mTitleLayout.getVisibility() != GONE && (mDisplayOptions & ActionBar.DISPLAY_SHOW_TITLE) != 0; if (mExpandedActionView == null) { switch (mNavigationMode) { case ActionBar.NAVIGATION_MODE_LIST: if (mListNavLayout != null) { final int itemPaddingSize = showTitle ? mItemPadding * 2 : mItemPadding; availableWidth = Math.max(0, availableWidth - itemPaddingSize); leftOfCenter = Math.max(0, leftOfCenter - itemPaddingSize); mListNavLayout.measure( MeasureSpec.makeMeasureSpec(availableWidth, MeasureSpec.AT_MOST), MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY)); final int listNavWidth = mListNavLayout.getMeasuredWidth(); availableWidth = Math.max(0, availableWidth - listNavWidth); leftOfCenter = Math.max(0, leftOfCenter - listNavWidth); } break; case ActionBar.NAVIGATION_MODE_TABS: if (mTabScrollView != null) { final int itemPaddingSize = showTitle ? mItemPadding * 2 : mItemPadding; availableWidth = Math.max(0, availableWidth - itemPaddingSize); leftOfCenter = Math.max(0, leftOfCenter - itemPaddingSize); mTabScrollView.measure( MeasureSpec.makeMeasureSpec(availableWidth, MeasureSpec.AT_MOST), MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY)); final int tabWidth = mTabScrollView.getMeasuredWidth(); availableWidth = Math.max(0, availableWidth - tabWidth); leftOfCenter = Math.max(0, leftOfCenter - tabWidth); } break; } } View customView = null; if (mExpandedActionView != null) { customView = mExpandedActionView; } else if ((mDisplayOptions & ActionBar.DISPLAY_SHOW_CUSTOM) != 0 && mCustomNavView != null) { customView = mCustomNavView; } if (customView != null) { final ViewGroup.LayoutParams lp = generateLayoutParams(customView.getLayoutParams()); final ActionBar.LayoutParams ablp = lp instanceof ActionBar.LayoutParams ? (ActionBar.LayoutParams) lp : null; int horizontalMargin = 0; int verticalMargin = 0; if (ablp != null) { horizontalMargin = ablp.leftMargin + ablp.rightMargin; verticalMargin = ablp.topMargin + ablp.bottomMargin; } // If the action bar is wrapping to its content height, don't allow a custom // view to MATCH_PARENT. int customNavHeightMode; if (mContentHeight <= 0) { customNavHeightMode = MeasureSpec.AT_MOST; } else { customNavHeightMode = lp.height != LayoutParams.WRAP_CONTENT ? MeasureSpec.EXACTLY : MeasureSpec.AT_MOST; } final int customNavHeight = Math.max(0, (lp.height >= 0 ? Math.min(lp.height, height) : height) - verticalMargin); final int customNavWidthMode = lp.width != LayoutParams.WRAP_CONTENT ? MeasureSpec.EXACTLY : MeasureSpec.AT_MOST; int customNavWidth = Math.max(0, (lp.width >= 0 ? Math.min(lp.width, availableWidth) : availableWidth) - horizontalMargin); final int hgrav = (ablp != null ? ablp.gravity : DEFAULT_CUSTOM_GRAVITY) & Gravity.HORIZONTAL_GRAVITY_MASK; // Centering a custom view is treated specially; we try to center within the whole // action bar rather than in the available space. if (hgrav == Gravity.CENTER_HORIZONTAL && lp.width == LayoutParams.MATCH_PARENT) { customNavWidth = Math.min(leftOfCenter, rightOfCenter) * 2; } customView.measure( MeasureSpec.makeMeasureSpec(customNavWidth, customNavWidthMode), MeasureSpec.makeMeasureSpec(customNavHeight, customNavHeightMode)); availableWidth -= horizontalMargin + customView.getMeasuredWidth(); } if (mExpandedActionView == null && showTitle) { availableWidth = measureChildView(mTitleLayout, availableWidth, MeasureSpec.makeMeasureSpec(mContentHeight, MeasureSpec.EXACTLY), 0); leftOfCenter = Math.max(0, leftOfCenter - mTitleLayout.getMeasuredWidth()); } if (mContentHeight <= 0) { int measuredHeight = 0; for (int i = 0; i < childCount; i++) { View v = getChildAt(i); int paddedViewHeight = v.getMeasuredHeight() + verticalPadding; if (paddedViewHeight > measuredHeight) { measuredHeight = paddedViewHeight; } } setMeasuredDimension(contentWidth, measuredHeight); } else { setMeasuredDimension(contentWidth, maxHeight); } if (mContextView != null) { mContextView.setContentHeight(getMeasuredHeight()); } if (mProgressView != null && mProgressView.getVisibility() != GONE) { mProgressView.measure(MeasureSpec.makeMeasureSpec( contentWidth - mProgressBarPadding * 2, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(getMeasuredHeight(), MeasureSpec.AT_MOST)); } } @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { int x = getPaddingLeft(); final int y = getPaddingTop(); final int contentHeight = b - t - getPaddingTop() - getPaddingBottom(); if (contentHeight <= 0) { // Nothing to do if we can't see anything. return; } HomeView homeLayout = mExpandedActionView != null ? mExpandedHomeLayout : mHomeLayout; if (homeLayout.getVisibility() != GONE) { final int leftOffset = homeLayout.getLeftOffset(); x += positionChild(homeLayout, x + leftOffset, y, contentHeight) + leftOffset; } if (mExpandedActionView == null) { final boolean showTitle = mTitleLayout != null && mTitleLayout.getVisibility() != GONE && (mDisplayOptions & ActionBar.DISPLAY_SHOW_TITLE) != 0; if (showTitle) { x += positionChild(mTitleLayout, x, y, contentHeight); } switch (mNavigationMode) { case ActionBar.NAVIGATION_MODE_STANDARD: break; case ActionBar.NAVIGATION_MODE_LIST: if (mListNavLayout != null) { if (showTitle) x += mItemPadding; x += positionChild(mListNavLayout, x, y, contentHeight) + mItemPadding; } break; case ActionBar.NAVIGATION_MODE_TABS: if (mTabScrollView != null) { if (showTitle) x += mItemPadding; x += positionChild(mTabScrollView, x, y, contentHeight) + mItemPadding; } break; } } int menuLeft = r - l - getPaddingRight(); if (mMenuView != null && mMenuView.getParent() == this) { positionChildInverse(mMenuView, menuLeft, y, contentHeight); menuLeft -= mMenuView.getMeasuredWidth(); } if (mIndeterminateProgressView != null && mIndeterminateProgressView.getVisibility() != GONE) { positionChildInverse(mIndeterminateProgressView, menuLeft, y, contentHeight); menuLeft -= mIndeterminateProgressView.getMeasuredWidth(); } View customView = null; if (mExpandedActionView != null) { customView = mExpandedActionView; } else if ((mDisplayOptions & ActionBar.DISPLAY_SHOW_CUSTOM) != 0 && mCustomNavView != null) { customView = mCustomNavView; } if (customView != null) { ViewGroup.LayoutParams lp = customView.getLayoutParams(); final ActionBar.LayoutParams ablp = lp instanceof ActionBar.LayoutParams ? (ActionBar.LayoutParams) lp : null; final int gravity = ablp != null ? ablp.gravity : DEFAULT_CUSTOM_GRAVITY; final int navWidth = customView.getMeasuredWidth(); int topMargin = 0; int bottomMargin = 0; if (ablp != null) { x += ablp.leftMargin; menuLeft -= ablp.rightMargin; topMargin = ablp.topMargin; bottomMargin = ablp.bottomMargin; } int hgravity = gravity & Gravity.HORIZONTAL_GRAVITY_MASK; // See if we actually have room to truly center; if not push against left or right. if (hgravity == Gravity.CENTER_HORIZONTAL) { final int centeredLeft = ((getRight() - getLeft()) - navWidth) / 2; if (centeredLeft < x) { hgravity = Gravity.LEFT; } else if (centeredLeft + navWidth > menuLeft) { hgravity = Gravity.RIGHT; } } else if (gravity == -1) { hgravity = Gravity.LEFT; } int xpos = 0; switch (hgravity) { case Gravity.CENTER_HORIZONTAL: xpos = ((getRight() - getLeft()) - navWidth) / 2; break; case Gravity.LEFT: xpos = x; break; case Gravity.RIGHT: xpos = menuLeft - navWidth; break; } int vgravity = gravity & Gravity.VERTICAL_GRAVITY_MASK; if (gravity == -1) { vgravity = Gravity.CENTER_VERTICAL; } int ypos = 0; switch (vgravity) { case Gravity.CENTER_VERTICAL: final int paddedTop = getPaddingTop(); final int paddedBottom = getBottom() - getTop() - getPaddingBottom(); ypos = ((paddedBottom - paddedTop) - customView.getMeasuredHeight()) / 2; break; case Gravity.TOP: ypos = getPaddingTop() + topMargin; break; case Gravity.BOTTOM: ypos = getHeight() - getPaddingBottom() - customView.getMeasuredHeight() - bottomMargin; break; } final int customWidth = customView.getMeasuredWidth(); customView.layout(xpos, ypos, xpos + customWidth, ypos + customView.getMeasuredHeight()); x += customWidth; } if (mProgressView != null) { mProgressView.bringToFront(); final int halfProgressHeight = mProgressView.getMeasuredHeight() / 2; mProgressView.layout(mProgressBarPadding, -halfProgressHeight, mProgressBarPadding + mProgressView.getMeasuredWidth(), halfProgressHeight); } } @Override public ViewGroup.LayoutParams generateLayoutParams(AttributeSet attrs) { return new ActionBar.LayoutParams(getContext(), attrs); } @Override public ViewGroup.LayoutParams generateLayoutParams(ViewGroup.LayoutParams lp) { if (lp == null) { lp = generateDefaultLayoutParams(); } return lp; } @Override public Parcelable onSaveInstanceState() { Parcelable superState = super.onSaveInstanceState(); SavedState state = new SavedState(superState); if (mExpandedMenuPresenter != null && mExpandedMenuPresenter.mCurrentExpandedItem != null) { state.expandedMenuItemId = mExpandedMenuPresenter.mCurrentExpandedItem.getItemId(); } state.isOverflowOpen = isOverflowMenuShowing(); return state; } @Override public void onRestoreInstanceState(Parcelable p) { SavedState state = (SavedState) p; super.onRestoreInstanceState(state.getSuperState()); if (state.expandedMenuItemId != 0 && mExpandedMenuPresenter != null && mOptionsMenu != null) { final MenuItem item = mOptionsMenu.findItem(state.expandedMenuItemId); if (item != null) { item.expandActionView(); } } if (state.isOverflowOpen) { postShowOverflowMenu(); } } static class SavedState extends BaseSavedState { int expandedMenuItemId; boolean isOverflowOpen; SavedState(Parcelable superState) { super(superState); } private SavedState(Parcel in) { super(in); expandedMenuItemId = in.readInt(); isOverflowOpen = in.readInt() != 0; } @Override public void writeToParcel(Parcel out, int flags) { super.writeToParcel(out, flags); out.writeInt(expandedMenuItemId); out.writeInt(isOverflowOpen ? 1 : 0); } public static final Parcelable.Creator<SavedState> CREATOR = new Parcelable.Creator<SavedState>() { public SavedState createFromParcel(Parcel in) { return new SavedState(in); } public SavedState[] newArray(int size) { return new SavedState[size]; } }; } public static class HomeView extends FrameLayout { private View mUpView; private ImageView mIconView; private int mUpWidth; public HomeView(Context context) { this(context, null); } public HomeView(Context context, AttributeSet attrs) { super(context, attrs); } public void setUp(boolean isUp) { mUpView.setVisibility(isUp ? VISIBLE : GONE); } public void setIcon(Drawable icon) { mIconView.setImageDrawable(icon); } @Override public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) { onPopulateAccessibilityEvent(event); return true; } @Override public void onPopulateAccessibilityEvent(AccessibilityEvent event) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) { super.onPopulateAccessibilityEvent(event); } final CharSequence cdesc = getContentDescription(); if (!TextUtils.isEmpty(cdesc)) { event.getText().add(cdesc); } } @Override public boolean dispatchHoverEvent(MotionEvent event) { // Don't allow children to hover; we want this to be treated as a single component. return onHoverEvent(event); } @Override protected void onFinishInflate() { mUpView = findViewById(R.id.abs__up); mIconView = (ImageView) findViewById(R.id.abs__home); } public int getLeftOffset() { return mUpView.getVisibility() == GONE ? mUpWidth : 0; } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { measureChildWithMargins(mUpView, widthMeasureSpec, 0, heightMeasureSpec, 0); final LayoutParams upLp = (LayoutParams) mUpView.getLayoutParams(); mUpWidth = upLp.leftMargin + mUpView.getMeasuredWidth() + upLp.rightMargin; int width = mUpView.getVisibility() == GONE ? 0 : mUpWidth; int height = upLp.topMargin + mUpView.getMeasuredHeight() + upLp.bottomMargin; measureChildWithMargins(mIconView, widthMeasureSpec, width, heightMeasureSpec, 0); final LayoutParams iconLp = (LayoutParams) mIconView.getLayoutParams(); width += iconLp.leftMargin + mIconView.getMeasuredWidth() + iconLp.rightMargin; height = Math.max(height, iconLp.topMargin + mIconView.getMeasuredHeight() + iconLp.bottomMargin); final int widthMode = MeasureSpec.getMode(widthMeasureSpec); final int heightMode = MeasureSpec.getMode(heightMeasureSpec); final int widthSize = MeasureSpec.getSize(widthMeasureSpec); final int heightSize = MeasureSpec.getSize(heightMeasureSpec); switch (widthMode) { case MeasureSpec.AT_MOST: width = Math.min(width, widthSize); break; case MeasureSpec.EXACTLY: width = widthSize; break; case MeasureSpec.UNSPECIFIED: default: break; } switch (heightMode) { case MeasureSpec.AT_MOST: height = Math.min(height, heightSize); break; case MeasureSpec.EXACTLY: height = heightSize; break; case MeasureSpec.UNSPECIFIED: default: break; } setMeasuredDimension(width, height); } @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { final int vCenter = (b - t) / 2; //UNUSED int width = r - l; int upOffset = 0; if (mUpView.getVisibility() != GONE) { final LayoutParams upLp = (LayoutParams) mUpView.getLayoutParams(); final int upHeight = mUpView.getMeasuredHeight(); final int upWidth = mUpView.getMeasuredWidth(); final int upTop = vCenter - upHeight / 2; mUpView.layout(0, upTop, upWidth, upTop + upHeight); upOffset = upLp.leftMargin + upWidth + upLp.rightMargin; //UNUSED width -= upOffset; l += upOffset; } final LayoutParams iconLp = (LayoutParams) mIconView.getLayoutParams(); final int iconHeight = mIconView.getMeasuredHeight(); final int iconWidth = mIconView.getMeasuredWidth(); final int hCenter = (r - l) / 2; final int iconLeft = upOffset + Math.max(iconLp.leftMargin, hCenter - iconWidth / 2); final int iconTop = Math.max(iconLp.topMargin, vCenter - iconHeight / 2); mIconView.layout(iconLeft, iconTop, iconLeft + iconWidth, iconTop + iconHeight); } } private class ExpandedActionViewMenuPresenter implements MenuPresenter { MenuBuilder mMenu; MenuItemImpl mCurrentExpandedItem; @Override public void initForMenu(Context context, MenuBuilder menu) { // Clear the expanded action view when menus change. if (mMenu != null && mCurrentExpandedItem != null) { mMenu.collapseItemActionView(mCurrentExpandedItem); } mMenu = menu; } @Override public MenuView getMenuView(ViewGroup root) { return null; } @Override public void updateMenuView(boolean cleared) { // Make sure the expanded item we have is still there. if (mCurrentExpandedItem != null) { boolean found = false; if (mMenu != null) { final int count = mMenu.size(); for (int i = 0; i < count; i++) { final MenuItem item = mMenu.getItem(i); if (item == mCurrentExpandedItem) { found = true; break; } } } if (!found) { // The item we had expanded disappeared. Collapse. collapseItemActionView(mMenu, mCurrentExpandedItem); } } } @Override public void setCallback(Callback cb) { } @Override public boolean onSubMenuSelected(SubMenuBuilder subMenu) { return false; } @Override public void onCloseMenu(MenuBuilder menu, boolean allMenusAreClosing) { } @Override public boolean flagActionItems() { return false; } @Override public boolean expandItemActionView(MenuBuilder menu, MenuItemImpl item) { mExpandedActionView = item.getActionView(); mExpandedHomeLayout.setIcon(mIcon.getConstantState().newDrawable(/* TODO getResources() */)); mCurrentExpandedItem = item; if (mExpandedActionView.getParent() != ActionBarView.this) { addView(mExpandedActionView); } if (mExpandedHomeLayout.getParent() != ActionBarView.this) { addView(mExpandedHomeLayout); } mHomeLayout.setVisibility(GONE); if (mTitleLayout != null) mTitleLayout.setVisibility(GONE); if (mTabScrollView != null) mTabScrollView.setVisibility(GONE); if (mSpinner != null) mSpinner.setVisibility(GONE); if (mCustomNavView != null) mCustomNavView.setVisibility(GONE); requestLayout(); item.setActionViewExpanded(true); if (mExpandedActionView instanceof CollapsibleActionView) { ((CollapsibleActionView) mExpandedActionView).onActionViewExpanded(); } return true; } @Override public boolean collapseItemActionView(MenuBuilder menu, MenuItemImpl item) { // Do this before detaching the actionview from the hierarchy, in case // it needs to dismiss the soft keyboard, etc. if (mExpandedActionView instanceof CollapsibleActionView) { ((CollapsibleActionView) mExpandedActionView).onActionViewCollapsed(); } removeView(mExpandedActionView); removeView(mExpandedHomeLayout); mExpandedActionView = null; if ((mDisplayOptions & ActionBar.DISPLAY_SHOW_HOME) != 0) { mHomeLayout.setVisibility(VISIBLE); } if ((mDisplayOptions & ActionBar.DISPLAY_SHOW_TITLE) != 0) { if (mTitleLayout == null) { initTitle(); } else { mTitleLayout.setVisibility(VISIBLE); } } if (mTabScrollView != null && mNavigationMode == ActionBar.NAVIGATION_MODE_TABS) { mTabScrollView.setVisibility(VISIBLE); } if (mSpinner != null && mNavigationMode == ActionBar.NAVIGATION_MODE_LIST) { mSpinner.setVisibility(VISIBLE); } if (mCustomNavView != null && (mDisplayOptions & ActionBar.DISPLAY_SHOW_CUSTOM) != 0) { mCustomNavView.setVisibility(VISIBLE); } mExpandedHomeLayout.setIcon(null); mCurrentExpandedItem = null; requestLayout(); item.setActionViewExpanded(false); return true; } @Override public int getId() { return 0; } @Override public Parcelable onSaveInstanceState() { return null; } @Override public void onRestoreInstanceState(Parcelable state) { } } }
Java
/* * Copyright (C) 2010 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.actionbarsherlock.internal.widget; import android.content.Context; import android.content.res.TypedArray; import android.graphics.drawable.Drawable; import android.text.TextUtils; import android.util.AttributeSet; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.accessibility.AccessibilityEvent; import android.view.animation.DecelerateInterpolator; import android.widget.LinearLayout; import android.widget.TextView; import com.actionbarsherlock.R; import com.actionbarsherlock.internal.nineoldandroids.animation.Animator; import com.actionbarsherlock.internal.nineoldandroids.animation.Animator.AnimatorListener; import com.actionbarsherlock.internal.nineoldandroids.animation.AnimatorSet; import com.actionbarsherlock.internal.nineoldandroids.animation.ObjectAnimator; import com.actionbarsherlock.internal.nineoldandroids.view.animation.AnimatorProxy; import com.actionbarsherlock.internal.nineoldandroids.widget.NineLinearLayout; import com.actionbarsherlock.internal.view.menu.ActionMenuPresenter; import com.actionbarsherlock.internal.view.menu.ActionMenuView; import com.actionbarsherlock.internal.view.menu.MenuBuilder; import com.actionbarsherlock.view.ActionMode; /** * @hide */ public class ActionBarContextView extends AbsActionBarView implements AnimatorListener { //UNUSED private static final String TAG = "ActionBarContextView"; private CharSequence mTitle; private CharSequence mSubtitle; private NineLinearLayout mClose; private View mCustomView; private LinearLayout mTitleLayout; private TextView mTitleView; private TextView mSubtitleView; private int mTitleStyleRes; private int mSubtitleStyleRes; private Drawable mSplitBackground; private Animator mCurrentAnimation; private boolean mAnimateInOnLayout; private int mAnimationMode; private static final int ANIMATE_IDLE = 0; private static final int ANIMATE_IN = 1; private static final int ANIMATE_OUT = 2; public ActionBarContextView(Context context) { this(context, null); } public ActionBarContextView(Context context, AttributeSet attrs) { this(context, attrs, R.attr.actionModeStyle); } public ActionBarContextView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.SherlockActionMode, defStyle, 0); setBackgroundDrawable(a.getDrawable( R.styleable.SherlockActionMode_background)); mTitleStyleRes = a.getResourceId( R.styleable.SherlockActionMode_titleTextStyle, 0); mSubtitleStyleRes = a.getResourceId( R.styleable.SherlockActionMode_subtitleTextStyle, 0); mContentHeight = a.getLayoutDimension( R.styleable.SherlockActionMode_height, 0); mSplitBackground = a.getDrawable( R.styleable.SherlockActionMode_backgroundSplit); a.recycle(); } @Override public void onDetachedFromWindow() { super.onDetachedFromWindow(); if (mActionMenuPresenter != null) { mActionMenuPresenter.hideOverflowMenu(); mActionMenuPresenter.hideSubMenus(); } } @Override public void setSplitActionBar(boolean split) { if (mSplitActionBar != split) { if (mActionMenuPresenter != null) { // Mode is already active; move everything over and adjust the menu itself. final LayoutParams layoutParams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT); if (!split) { mMenuView = (ActionMenuView) mActionMenuPresenter.getMenuView(this); mMenuView.setBackgroundDrawable(null); final ViewGroup oldParent = (ViewGroup) mMenuView.getParent(); if (oldParent != null) oldParent.removeView(mMenuView); addView(mMenuView, layoutParams); } else { // Allow full screen width in split mode. mActionMenuPresenter.setWidthLimit( getContext().getResources().getDisplayMetrics().widthPixels, true); // No limit to the item count; use whatever will fit. mActionMenuPresenter.setItemLimit(Integer.MAX_VALUE); // Span the whole width layoutParams.width = LayoutParams.MATCH_PARENT; layoutParams.height = mContentHeight; mMenuView = (ActionMenuView) mActionMenuPresenter.getMenuView(this); mMenuView.setBackgroundDrawable(mSplitBackground); final ViewGroup oldParent = (ViewGroup) mMenuView.getParent(); if (oldParent != null) oldParent.removeView(mMenuView); mSplitView.addView(mMenuView, layoutParams); } } super.setSplitActionBar(split); } } public void setContentHeight(int height) { mContentHeight = height; } public void setCustomView(View view) { if (mCustomView != null) { removeView(mCustomView); } mCustomView = view; if (mTitleLayout != null) { removeView(mTitleLayout); mTitleLayout = null; } if (view != null) { addView(view); } requestLayout(); } public void setTitle(CharSequence title) { mTitle = title; initTitle(); } public void setSubtitle(CharSequence subtitle) { mSubtitle = subtitle; initTitle(); } public CharSequence getTitle() { return mTitle; } public CharSequence getSubtitle() { return mSubtitle; } private void initTitle() { if (mTitleLayout == null) { LayoutInflater inflater = LayoutInflater.from(getContext()); inflater.inflate(R.layout.abs__action_bar_title_item, this); mTitleLayout = (LinearLayout) getChildAt(getChildCount() - 1); mTitleView = (TextView) mTitleLayout.findViewById(R.id.abs__action_bar_title); mSubtitleView = (TextView) mTitleLayout.findViewById(R.id.abs__action_bar_subtitle); if (mTitleStyleRes != 0) { mTitleView.setTextAppearance(mContext, mTitleStyleRes); } if (mSubtitleStyleRes != 0) { mSubtitleView.setTextAppearance(mContext, mSubtitleStyleRes); } } mTitleView.setText(mTitle); mSubtitleView.setText(mSubtitle); final boolean hasTitle = !TextUtils.isEmpty(mTitle); final boolean hasSubtitle = !TextUtils.isEmpty(mSubtitle); mSubtitleView.setVisibility(hasSubtitle ? VISIBLE : GONE); mTitleLayout.setVisibility(hasTitle || hasSubtitle ? VISIBLE : GONE); if (mTitleLayout.getParent() == null) { addView(mTitleLayout); } } public void initForMode(final ActionMode mode) { if (mClose == null) { LayoutInflater inflater = LayoutInflater.from(mContext); mClose = (NineLinearLayout)inflater.inflate(R.layout.abs__action_mode_close_item, this, false); addView(mClose); } else if (mClose.getParent() == null) { addView(mClose); } View closeButton = mClose.findViewById(R.id.abs__action_mode_close_button); closeButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { mode.finish(); } }); final MenuBuilder menu = (MenuBuilder) mode.getMenu(); if (mActionMenuPresenter != null) { mActionMenuPresenter.dismissPopupMenus(); } mActionMenuPresenter = new ActionMenuPresenter(mContext); mActionMenuPresenter.setReserveOverflow(true); final LayoutParams layoutParams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT); if (!mSplitActionBar) { menu.addMenuPresenter(mActionMenuPresenter); mMenuView = (ActionMenuView) mActionMenuPresenter.getMenuView(this); mMenuView.setBackgroundDrawable(null); addView(mMenuView, layoutParams); } else { // Allow full screen width in split mode. mActionMenuPresenter.setWidthLimit( getContext().getResources().getDisplayMetrics().widthPixels, true); // No limit to the item count; use whatever will fit. mActionMenuPresenter.setItemLimit(Integer.MAX_VALUE); // Span the whole width layoutParams.width = LayoutParams.MATCH_PARENT; layoutParams.height = mContentHeight; menu.addMenuPresenter(mActionMenuPresenter); mMenuView = (ActionMenuView) mActionMenuPresenter.getMenuView(this); mMenuView.setBackgroundDrawable(mSplitBackground); mSplitView.addView(mMenuView, layoutParams); } mAnimateInOnLayout = true; } public void closeMode() { if (mAnimationMode == ANIMATE_OUT) { // Called again during close; just finish what we were doing. return; } if (mClose == null) { killMode(); return; } finishAnimation(); mAnimationMode = ANIMATE_OUT; mCurrentAnimation = makeOutAnimation(); mCurrentAnimation.start(); } private void finishAnimation() { final Animator a = mCurrentAnimation; if (a != null) { mCurrentAnimation = null; a.end(); } } public void killMode() { finishAnimation(); removeAllViews(); if (mSplitView != null) { mSplitView.removeView(mMenuView); } mCustomView = null; mMenuView = null; mAnimateInOnLayout = false; } @Override public boolean showOverflowMenu() { if (mActionMenuPresenter != null) { return mActionMenuPresenter.showOverflowMenu(); } return false; } @Override public boolean hideOverflowMenu() { if (mActionMenuPresenter != null) { return mActionMenuPresenter.hideOverflowMenu(); } return false; } @Override public boolean isOverflowMenuShowing() { if (mActionMenuPresenter != null) { return mActionMenuPresenter.isOverflowMenuShowing(); } return false; } @Override protected ViewGroup.LayoutParams generateDefaultLayoutParams() { // Used by custom views if they don't supply layout params. Everything else // added to an ActionBarContextView should have them already. return new MarginLayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT); } @Override public ViewGroup.LayoutParams generateLayoutParams(AttributeSet attrs) { return new MarginLayoutParams(getContext(), attrs); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { final int widthMode = MeasureSpec.getMode(widthMeasureSpec); if (widthMode != MeasureSpec.EXACTLY) { throw new IllegalStateException(getClass().getSimpleName() + " can only be used " + "with android:layout_width=\"match_parent\" (or fill_parent)"); } final int heightMode = MeasureSpec.getMode(heightMeasureSpec); if (heightMode == MeasureSpec.UNSPECIFIED) { throw new IllegalStateException(getClass().getSimpleName() + " can only be used " + "with android:layout_height=\"wrap_content\""); } final int contentWidth = MeasureSpec.getSize(widthMeasureSpec); int maxHeight = mContentHeight > 0 ? mContentHeight : MeasureSpec.getSize(heightMeasureSpec); final int verticalPadding = getPaddingTop() + getPaddingBottom(); int availableWidth = contentWidth - getPaddingLeft() - getPaddingRight(); final int height = maxHeight - verticalPadding; final int childSpecHeight = MeasureSpec.makeMeasureSpec(height, MeasureSpec.AT_MOST); if (mClose != null) { availableWidth = measureChildView(mClose, availableWidth, childSpecHeight, 0); MarginLayoutParams lp = (MarginLayoutParams) mClose.getLayoutParams(); availableWidth -= lp.leftMargin + lp.rightMargin; } if (mMenuView != null && mMenuView.getParent() == this) { availableWidth = measureChildView(mMenuView, availableWidth, childSpecHeight, 0); } if (mTitleLayout != null && mCustomView == null) { availableWidth = measureChildView(mTitleLayout, availableWidth, childSpecHeight, 0); } if (mCustomView != null) { ViewGroup.LayoutParams lp = mCustomView.getLayoutParams(); final int customWidthMode = lp.width != LayoutParams.WRAP_CONTENT ? MeasureSpec.EXACTLY : MeasureSpec.AT_MOST; final int customWidth = lp.width >= 0 ? Math.min(lp.width, availableWidth) : availableWidth; final int customHeightMode = lp.height != LayoutParams.WRAP_CONTENT ? MeasureSpec.EXACTLY : MeasureSpec.AT_MOST; final int customHeight = lp.height >= 0 ? Math.min(lp.height, height) : height; mCustomView.measure(MeasureSpec.makeMeasureSpec(customWidth, customWidthMode), MeasureSpec.makeMeasureSpec(customHeight, customHeightMode)); } if (mContentHeight <= 0) { int measuredHeight = 0; final int count = getChildCount(); for (int i = 0; i < count; i++) { View v = getChildAt(i); int paddedViewHeight = v.getMeasuredHeight() + verticalPadding; if (paddedViewHeight > measuredHeight) { measuredHeight = paddedViewHeight; } } setMeasuredDimension(contentWidth, measuredHeight); } else { setMeasuredDimension(contentWidth, maxHeight); } } private Animator makeInAnimation() { mClose.setTranslationX(-mClose.getWidth() - ((MarginLayoutParams) mClose.getLayoutParams()).leftMargin); ObjectAnimator buttonAnimator = ObjectAnimator.ofFloat(mClose, "translationX", 0); buttonAnimator.setDuration(200); buttonAnimator.addListener(this); buttonAnimator.setInterpolator(new DecelerateInterpolator()); AnimatorSet set = new AnimatorSet(); AnimatorSet.Builder b = set.play(buttonAnimator); if (mMenuView != null) { final int count = mMenuView.getChildCount(); if (count > 0) { for (int i = count - 1, j = 0; i >= 0; i--, j++) { AnimatorProxy child = AnimatorProxy.wrap(mMenuView.getChildAt(i)); child.setScaleY(0); ObjectAnimator a = ObjectAnimator.ofFloat(child, "scaleY", 0, 1); a.setDuration(100); a.setStartDelay(j * 70); b.with(a); } } } return set; } private Animator makeOutAnimation() { ObjectAnimator buttonAnimator = ObjectAnimator.ofFloat(mClose, "translationX", -mClose.getWidth() - ((MarginLayoutParams) mClose.getLayoutParams()).leftMargin); buttonAnimator.setDuration(200); buttonAnimator.addListener(this); buttonAnimator.setInterpolator(new DecelerateInterpolator()); AnimatorSet set = new AnimatorSet(); AnimatorSet.Builder b = set.play(buttonAnimator); if (mMenuView != null) { final int count = mMenuView.getChildCount(); if (count > 0) { for (int i = 0; i < 0; i++) { AnimatorProxy child = AnimatorProxy.wrap(mMenuView.getChildAt(i)); child.setScaleY(0); ObjectAnimator a = ObjectAnimator.ofFloat(child, "scaleY", 0); a.setDuration(100); a.setStartDelay(i * 70); b.with(a); } } } return set; } @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { int x = getPaddingLeft(); final int y = getPaddingTop(); final int contentHeight = b - t - getPaddingTop() - getPaddingBottom(); if (mClose != null && mClose.getVisibility() != GONE) { MarginLayoutParams lp = (MarginLayoutParams) mClose.getLayoutParams(); x += lp.leftMargin; x += positionChild(mClose, x, y, contentHeight); x += lp.rightMargin; if (mAnimateInOnLayout) { mAnimationMode = ANIMATE_IN; mCurrentAnimation = makeInAnimation(); mCurrentAnimation.start(); mAnimateInOnLayout = false; } } if (mTitleLayout != null && mCustomView == null) { x += positionChild(mTitleLayout, x, y, contentHeight); } if (mCustomView != null) { x += positionChild(mCustomView, x, y, contentHeight); } x = r - l - getPaddingRight(); if (mMenuView != null) { x -= positionChildInverse(mMenuView, x, y, contentHeight); } } @Override public void onAnimationStart(Animator animation) { } @Override public void onAnimationEnd(Animator animation) { if (mAnimationMode == ANIMATE_OUT) { killMode(); } mAnimationMode = ANIMATE_IDLE; } @Override public void onAnimationCancel(Animator animation) { } @Override public void onAnimationRepeat(Animator animation) { } @Override public boolean shouldDelayChildPressedState() { return false; } @Override public void onInitializeAccessibilityEvent(AccessibilityEvent event) { if (event.getEventType() == AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED) { // Action mode started //TODO event.setSource(this); event.setClassName(getClass().getName()); event.setPackageName(getContext().getPackageName()); event.setContentDescription(mTitle); } else { //TODO super.onInitializeAccessibilityEvent(event); } } }
Java
/* * Copyright (C) 2006 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.actionbarsherlock.internal.widget; import android.content.Context; import android.database.DataSetObserver; import android.os.Parcelable; import android.os.SystemClock; import android.util.AttributeSet; import android.util.SparseArray; import android.view.ContextMenu; import android.view.SoundEffectConstants; import android.view.View; import android.view.ViewDebug; import android.view.ViewGroup; import android.view.accessibility.AccessibilityEvent; import android.view.accessibility.AccessibilityNodeInfo; import android.widget.Adapter; import android.widget.AdapterView.OnItemClickListener; import android.widget.ListView; /** * An AdapterView is a view whose children are determined by an {@link Adapter}. * * <p> * See {@link ListView}, {@link GridView}, {@link Spinner} and * {@link Gallery} for commonly used subclasses of AdapterView. * * <div class="special reference"> * <h3>Developer Guides</h3> * <p>For more information about using AdapterView, read the * <a href="{@docRoot}guide/topics/ui/binding.html">Binding to Data with AdapterView</a> * developer guide.</p></div> */ public abstract class IcsAdapterView<T extends Adapter> extends ViewGroup { /** * The item view type returned by {@link Adapter#getItemViewType(int)} when * the adapter does not want the item's view recycled. */ public static final int ITEM_VIEW_TYPE_IGNORE = -1; /** * The item view type returned by {@link Adapter#getItemViewType(int)} when * the item is a header or footer. */ public static final int ITEM_VIEW_TYPE_HEADER_OR_FOOTER = -2; /** * The position of the first child displayed */ @ViewDebug.ExportedProperty(category = "scrolling") int mFirstPosition = 0; /** * The offset in pixels from the top of the AdapterView to the top * of the view to select during the next layout. */ int mSpecificTop; /** * Position from which to start looking for mSyncRowId */ int mSyncPosition; /** * Row id to look for when data has changed */ long mSyncRowId = INVALID_ROW_ID; /** * Height of the view when mSyncPosition and mSyncRowId where set */ long mSyncHeight; /** * True if we need to sync to mSyncRowId */ boolean mNeedSync = false; /** * Indicates whether to sync based on the selection or position. Possible * values are {@link #SYNC_SELECTED_POSITION} or * {@link #SYNC_FIRST_POSITION}. */ int mSyncMode; /** * Our height after the last layout */ private int mLayoutHeight; /** * Sync based on the selected child */ static final int SYNC_SELECTED_POSITION = 0; /** * Sync based on the first child displayed */ static final int SYNC_FIRST_POSITION = 1; /** * Maximum amount of time to spend in {@link #findSyncPosition()} */ static final int SYNC_MAX_DURATION_MILLIS = 100; /** * Indicates that this view is currently being laid out. */ boolean mInLayout = false; /** * The listener that receives notifications when an item is selected. */ OnItemSelectedListener mOnItemSelectedListener; /** * The listener that receives notifications when an item is clicked. */ OnItemClickListener mOnItemClickListener; /** * The listener that receives notifications when an item is long clicked. */ OnItemLongClickListener mOnItemLongClickListener; /** * True if the data has changed since the last layout */ boolean mDataChanged; /** * The position within the adapter's data set of the item to select * during the next layout. */ @ViewDebug.ExportedProperty(category = "list") int mNextSelectedPosition = INVALID_POSITION; /** * The item id of the item to select during the next layout. */ long mNextSelectedRowId = INVALID_ROW_ID; /** * The position within the adapter's data set of the currently selected item. */ @ViewDebug.ExportedProperty(category = "list") int mSelectedPosition = INVALID_POSITION; /** * The item id of the currently selected item. */ long mSelectedRowId = INVALID_ROW_ID; /** * View to show if there are no items to show. */ private View mEmptyView; /** * The number of items in the current adapter. */ @ViewDebug.ExportedProperty(category = "list") int mItemCount; /** * The number of items in the adapter before a data changed event occurred. */ int mOldItemCount; /** * Represents an invalid position. All valid positions are in the range 0 to 1 less than the * number of items in the current adapter. */ public static final int INVALID_POSITION = -1; /** * Represents an empty or invalid row id */ public static final long INVALID_ROW_ID = Long.MIN_VALUE; /** * The last selected position we used when notifying */ int mOldSelectedPosition = INVALID_POSITION; /** * The id of the last selected position we used when notifying */ long mOldSelectedRowId = INVALID_ROW_ID; /** * Indicates what focusable state is requested when calling setFocusable(). * In addition to this, this view has other criteria for actually * determining the focusable state (such as whether its empty or the text * filter is shown). * * @see #setFocusable(boolean) * @see #checkFocus() */ private boolean mDesiredFocusableState; private boolean mDesiredFocusableInTouchModeState; private SelectionNotifier mSelectionNotifier; /** * When set to true, calls to requestLayout() will not propagate up the parent hierarchy. * This is used to layout the children during a layout pass. */ boolean mBlockLayoutRequests = false; public IcsAdapterView(Context context) { super(context); } public IcsAdapterView(Context context, AttributeSet attrs) { super(context, attrs); } public IcsAdapterView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } /** * Register a callback to be invoked when an item in this AdapterView has * been clicked. * * @param listener The callback that will be invoked. */ public void setOnItemClickListener(OnItemClickListener listener) { mOnItemClickListener = listener; } /** * @return The callback to be invoked with an item in this AdapterView has * been clicked, or null id no callback has been set. */ public final OnItemClickListener getOnItemClickListener() { return mOnItemClickListener; } /** * Call the OnItemClickListener, if it is defined. * * @param view The view within the AdapterView that was clicked. * @param position The position of the view in the adapter. * @param id The row id of the item that was clicked. * @return True if there was an assigned OnItemClickListener that was * called, false otherwise is returned. */ public boolean performItemClick(View view, int position, long id) { if (mOnItemClickListener != null) { playSoundEffect(SoundEffectConstants.CLICK); if (view != null) { view.sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED); } mOnItemClickListener.onItemClick(/*this*/null, view, position, id); return true; } return false; } /** * Interface definition for a callback to be invoked when an item in this * view has been clicked and held. */ public interface OnItemLongClickListener { /** * Callback method to be invoked when an item in this view has been * clicked and held. * * Implementers can call getItemAtPosition(position) if they need to access * the data associated with the selected item. * * @param parent The AbsListView where the click happened * @param view The view within the AbsListView that was clicked * @param position The position of the view in the list * @param id The row id of the item that was clicked * * @return true if the callback consumed the long click, false otherwise */ boolean onItemLongClick(IcsAdapterView<?> parent, View view, int position, long id); } /** * Register a callback to be invoked when an item in this AdapterView has * been clicked and held * * @param listener The callback that will run */ public void setOnItemLongClickListener(OnItemLongClickListener listener) { if (!isLongClickable()) { setLongClickable(true); } mOnItemLongClickListener = listener; } /** * @return The callback to be invoked with an item in this AdapterView has * been clicked and held, or null id no callback as been set. */ public final OnItemLongClickListener getOnItemLongClickListener() { return mOnItemLongClickListener; } /** * Interface definition for a callback to be invoked when * an item in this view has been selected. */ public interface OnItemSelectedListener { /** * <p>Callback method to be invoked when an item in this view has been * selected. This callback is invoked only when the newly selected * position is different from the previously selected position or if * there was no selected item.</p> * * Impelmenters can call getItemAtPosition(position) if they need to access the * data associated with the selected item. * * @param parent The AdapterView where the selection happened * @param view The view within the AdapterView that was clicked * @param position The position of the view in the adapter * @param id The row id of the item that is selected */ void onItemSelected(IcsAdapterView<?> parent, View view, int position, long id); /** * Callback method to be invoked when the selection disappears from this * view. The selection can disappear for instance when touch is activated * or when the adapter becomes empty. * * @param parent The AdapterView that now contains no selected item. */ void onNothingSelected(IcsAdapterView<?> parent); } /** * Register a callback to be invoked when an item in this AdapterView has * been selected. * * @param listener The callback that will run */ public void setOnItemSelectedListener(OnItemSelectedListener listener) { mOnItemSelectedListener = listener; } public final OnItemSelectedListener getOnItemSelectedListener() { return mOnItemSelectedListener; } /** * Extra menu information provided to the * {@link android.view.View.OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo) } * callback when a context menu is brought up for this AdapterView. * */ public static class AdapterContextMenuInfo implements ContextMenu.ContextMenuInfo { public AdapterContextMenuInfo(View targetView, int position, long id) { this.targetView = targetView; this.position = position; this.id = id; } /** * The child view for which the context menu is being displayed. This * will be one of the children of this AdapterView. */ public View targetView; /** * The position in the adapter for which the context menu is being * displayed. */ public int position; /** * The row id of the item for which the context menu is being displayed. */ public long id; } /** * Returns the adapter currently associated with this widget. * * @return The adapter used to provide this view's content. */ public abstract T getAdapter(); /** * Sets the adapter that provides the data and the views to represent the data * in this widget. * * @param adapter The adapter to use to create this view's content. */ public abstract void setAdapter(T adapter); /** * This method is not supported and throws an UnsupportedOperationException when called. * * @param child Ignored. * * @throws UnsupportedOperationException Every time this method is invoked. */ @Override public void addView(View child) { throw new UnsupportedOperationException("addView(View) is not supported in AdapterView"); } /** * This method is not supported and throws an UnsupportedOperationException when called. * * @param child Ignored. * @param index Ignored. * * @throws UnsupportedOperationException Every time this method is invoked. */ @Override public void addView(View child, int index) { throw new UnsupportedOperationException("addView(View, int) is not supported in AdapterView"); } /** * This method is not supported and throws an UnsupportedOperationException when called. * * @param child Ignored. * @param params Ignored. * * @throws UnsupportedOperationException Every time this method is invoked. */ @Override public void addView(View child, LayoutParams params) { throw new UnsupportedOperationException("addView(View, LayoutParams) " + "is not supported in AdapterView"); } /** * This method is not supported and throws an UnsupportedOperationException when called. * * @param child Ignored. * @param index Ignored. * @param params Ignored. * * @throws UnsupportedOperationException Every time this method is invoked. */ @Override public void addView(View child, int index, LayoutParams params) { throw new UnsupportedOperationException("addView(View, int, LayoutParams) " + "is not supported in AdapterView"); } /** * This method is not supported and throws an UnsupportedOperationException when called. * * @param child Ignored. * * @throws UnsupportedOperationException Every time this method is invoked. */ @Override public void removeView(View child) { throw new UnsupportedOperationException("removeView(View) is not supported in AdapterView"); } /** * This method is not supported and throws an UnsupportedOperationException when called. * * @param index Ignored. * * @throws UnsupportedOperationException Every time this method is invoked. */ @Override public void removeViewAt(int index) { throw new UnsupportedOperationException("removeViewAt(int) is not supported in AdapterView"); } /** * This method is not supported and throws an UnsupportedOperationException when called. * * @throws UnsupportedOperationException Every time this method is invoked. */ @Override public void removeAllViews() { throw new UnsupportedOperationException("removeAllViews() is not supported in AdapterView"); } @Override protected void onLayout(boolean changed, int left, int top, int right, int bottom) { mLayoutHeight = getHeight(); } /** * Return the position of the currently selected item within the adapter's data set * * @return int Position (starting at 0), or {@link #INVALID_POSITION} if there is nothing selected. */ @ViewDebug.CapturedViewProperty public int getSelectedItemPosition() { return mNextSelectedPosition; } /** * @return The id corresponding to the currently selected item, or {@link #INVALID_ROW_ID} * if nothing is selected. */ @ViewDebug.CapturedViewProperty public long getSelectedItemId() { return mNextSelectedRowId; } /** * @return The view corresponding to the currently selected item, or null * if nothing is selected */ public abstract View getSelectedView(); /** * @return The data corresponding to the currently selected item, or * null if there is nothing selected. */ public Object getSelectedItem() { T adapter = getAdapter(); int selection = getSelectedItemPosition(); if (adapter != null && adapter.getCount() > 0 && selection >= 0) { return adapter.getItem(selection); } else { return null; } } /** * @return The number of items owned by the Adapter associated with this * AdapterView. (This is the number of data items, which may be * larger than the number of visible views.) */ @ViewDebug.CapturedViewProperty public int getCount() { return mItemCount; } /** * Get the position within the adapter's data set for the view, where view is a an adapter item * or a descendant of an adapter item. * * @param view an adapter item, or a descendant of an adapter item. This must be visible in this * AdapterView at the time of the call. * @return the position within the adapter's data set of the view, or {@link #INVALID_POSITION} * if the view does not correspond to a list item (or it is not currently visible). */ public int getPositionForView(View view) { View listItem = view; try { View v; while (!(v = (View) listItem.getParent()).equals(this)) { listItem = v; } } catch (ClassCastException e) { // We made it up to the window without find this list view return INVALID_POSITION; } // Search the children for the list item final int childCount = getChildCount(); for (int i = 0; i < childCount; i++) { if (getChildAt(i).equals(listItem)) { return mFirstPosition + i; } } // Child not found! return INVALID_POSITION; } /** * Returns the position within the adapter's data set for the first item * displayed on screen. * * @return The position within the adapter's data set */ public int getFirstVisiblePosition() { return mFirstPosition; } /** * Returns the position within the adapter's data set for the last item * displayed on screen. * * @return The position within the adapter's data set */ public int getLastVisiblePosition() { return mFirstPosition + getChildCount() - 1; } /** * Sets the currently selected item. To support accessibility subclasses that * override this method must invoke the overriden super method first. * * @param position Index (starting at 0) of the data item to be selected. */ public abstract void setSelection(int position); /** * Sets the view to show if the adapter is empty */ public void setEmptyView(View emptyView) { mEmptyView = emptyView; final T adapter = getAdapter(); final boolean empty = ((adapter == null) || adapter.isEmpty()); updateEmptyStatus(empty); } /** * When the current adapter is empty, the AdapterView can display a special view * call the empty view. The empty view is used to provide feedback to the user * that no data is available in this AdapterView. * * @return The view to show if the adapter is empty. */ public View getEmptyView() { return mEmptyView; } /** * Indicates whether this view is in filter mode. Filter mode can for instance * be enabled by a user when typing on the keyboard. * * @return True if the view is in filter mode, false otherwise. */ boolean isInFilterMode() { return false; } @Override public void setFocusable(boolean focusable) { final T adapter = getAdapter(); final boolean empty = adapter == null || adapter.getCount() == 0; mDesiredFocusableState = focusable; if (!focusable) { mDesiredFocusableInTouchModeState = false; } super.setFocusable(focusable && (!empty || isInFilterMode())); } @Override public void setFocusableInTouchMode(boolean focusable) { final T adapter = getAdapter(); final boolean empty = adapter == null || adapter.getCount() == 0; mDesiredFocusableInTouchModeState = focusable; if (focusable) { mDesiredFocusableState = true; } super.setFocusableInTouchMode(focusable && (!empty || isInFilterMode())); } void checkFocus() { final T adapter = getAdapter(); final boolean empty = adapter == null || adapter.getCount() == 0; final boolean focusable = !empty || isInFilterMode(); // The order in which we set focusable in touch mode/focusable may matter // for the client, see View.setFocusableInTouchMode() comments for more // details super.setFocusableInTouchMode(focusable && mDesiredFocusableInTouchModeState); super.setFocusable(focusable && mDesiredFocusableState); if (mEmptyView != null) { updateEmptyStatus((adapter == null) || adapter.isEmpty()); } } /** * Update the status of the list based on the empty parameter. If empty is true and * we have an empty view, display it. In all the other cases, make sure that the listview * is VISIBLE and that the empty view is GONE (if it's not null). */ private void updateEmptyStatus(boolean empty) { if (isInFilterMode()) { empty = false; } if (empty) { if (mEmptyView != null) { mEmptyView.setVisibility(View.VISIBLE); setVisibility(View.GONE); } else { // If the caller just removed our empty view, make sure the list view is visible setVisibility(View.VISIBLE); } // We are now GONE, so pending layouts will not be dispatched. // Force one here to make sure that the state of the list matches // the state of the adapter. if (mDataChanged) { this.onLayout(false, getLeft(), getTop(), getRight(), getBottom()); } } else { if (mEmptyView != null) mEmptyView.setVisibility(View.GONE); setVisibility(View.VISIBLE); } } /** * Gets the data associated with the specified position in the list. * * @param position Which data to get * @return The data associated with the specified position in the list */ public Object getItemAtPosition(int position) { T adapter = getAdapter(); return (adapter == null || position < 0) ? null : adapter.getItem(position); } public long getItemIdAtPosition(int position) { T adapter = getAdapter(); return (adapter == null || position < 0) ? INVALID_ROW_ID : adapter.getItemId(position); } @Override public void setOnClickListener(OnClickListener l) { throw new RuntimeException("Don't call setOnClickListener for an AdapterView. " + "You probably want setOnItemClickListener instead"); } /** * Override to prevent freezing of any views created by the adapter. */ @Override protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) { dispatchFreezeSelfOnly(container); } /** * Override to prevent thawing of any views created by the adapter. */ @Override protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) { dispatchThawSelfOnly(container); } class AdapterDataSetObserver extends DataSetObserver { private Parcelable mInstanceState = null; @Override public void onChanged() { mDataChanged = true; mOldItemCount = mItemCount; mItemCount = getAdapter().getCount(); // Detect the case where a cursor that was previously invalidated has // been repopulated with new data. if (IcsAdapterView.this.getAdapter().hasStableIds() && mInstanceState != null && mOldItemCount == 0 && mItemCount > 0) { IcsAdapterView.this.onRestoreInstanceState(mInstanceState); mInstanceState = null; } else { rememberSyncState(); } checkFocus(); requestLayout(); } @Override public void onInvalidated() { mDataChanged = true; if (IcsAdapterView.this.getAdapter().hasStableIds()) { // Remember the current state for the case where our hosting activity is being // stopped and later restarted mInstanceState = IcsAdapterView.this.onSaveInstanceState(); } // Data is invalid so we should reset our state mOldItemCount = mItemCount; mItemCount = 0; mSelectedPosition = INVALID_POSITION; mSelectedRowId = INVALID_ROW_ID; mNextSelectedPosition = INVALID_POSITION; mNextSelectedRowId = INVALID_ROW_ID; mNeedSync = false; checkFocus(); requestLayout(); } public void clearSavedState() { mInstanceState = null; } } @Override protected void onDetachedFromWindow() { super.onDetachedFromWindow(); removeCallbacks(mSelectionNotifier); } private class SelectionNotifier implements Runnable { public void run() { if (mDataChanged) { // Data has changed between when this SelectionNotifier // was posted and now. We need to wait until the AdapterView // has been synched to the new data. if (getAdapter() != null) { post(this); } } else { fireOnSelected(); } } } void selectionChanged() { if (mOnItemSelectedListener != null) { if (mInLayout || mBlockLayoutRequests) { // If we are in a layout traversal, defer notification // by posting. This ensures that the view tree is // in a consistent state and is able to accomodate // new layout or invalidate requests. if (mSelectionNotifier == null) { mSelectionNotifier = new SelectionNotifier(); } post(mSelectionNotifier); } else { fireOnSelected(); } } // we fire selection events here not in View if (mSelectedPosition != ListView.INVALID_POSITION && isShown() && !isInTouchMode()) { sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SELECTED); } } private void fireOnSelected() { if (mOnItemSelectedListener == null) return; int selection = this.getSelectedItemPosition(); if (selection >= 0) { View v = getSelectedView(); mOnItemSelectedListener.onItemSelected(this, v, selection, getAdapter().getItemId(selection)); } else { mOnItemSelectedListener.onNothingSelected(this); } } @Override public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) { View selectedView = getSelectedView(); if (selectedView != null && selectedView.getVisibility() == VISIBLE && selectedView.dispatchPopulateAccessibilityEvent(event)) { return true; } return false; } @Override public boolean onRequestSendAccessibilityEvent(View child, AccessibilityEvent event) { if (super.onRequestSendAccessibilityEvent(child, event)) { // Add a record for ourselves as well. AccessibilityEvent record = AccessibilityEvent.obtain(); onInitializeAccessibilityEvent(record); // Populate with the text of the requesting child. child.dispatchPopulateAccessibilityEvent(record); event.appendRecord(record); return true; } return false; } @Override public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) { super.onInitializeAccessibilityNodeInfo(info); info.setScrollable(isScrollableForAccessibility()); View selectedView = getSelectedView(); if (selectedView != null) { info.setEnabled(selectedView.isEnabled()); } } @Override public void onInitializeAccessibilityEvent(AccessibilityEvent event) { super.onInitializeAccessibilityEvent(event); event.setScrollable(isScrollableForAccessibility()); View selectedView = getSelectedView(); if (selectedView != null) { event.setEnabled(selectedView.isEnabled()); } event.setCurrentItemIndex(getSelectedItemPosition()); event.setFromIndex(getFirstVisiblePosition()); event.setToIndex(getLastVisiblePosition()); event.setItemCount(getCount()); } private boolean isScrollableForAccessibility() { T adapter = getAdapter(); if (adapter != null) { final int itemCount = adapter.getCount(); return itemCount > 0 && (getFirstVisiblePosition() > 0 || getLastVisiblePosition() < itemCount - 1); } return false; } @Override protected boolean canAnimate() { return super.canAnimate() && mItemCount > 0; } void handleDataChanged() { final int count = mItemCount; boolean found = false; if (count > 0) { int newPos; // Find the row we are supposed to sync to if (mNeedSync) { // Update this first, since setNextSelectedPositionInt inspects // it mNeedSync = false; // See if we can find a position in the new data with the same // id as the old selection newPos = findSyncPosition(); if (newPos >= 0) { // Verify that new selection is selectable int selectablePos = lookForSelectablePosition(newPos, true); if (selectablePos == newPos) { // Same row id is selected setNextSelectedPositionInt(newPos); found = true; } } } if (!found) { // Try to use the same position if we can't find matching data newPos = getSelectedItemPosition(); // Pin position to the available range if (newPos >= count) { newPos = count - 1; } if (newPos < 0) { newPos = 0; } // Make sure we select something selectable -- first look down int selectablePos = lookForSelectablePosition(newPos, true); if (selectablePos < 0) { // Looking down didn't work -- try looking up selectablePos = lookForSelectablePosition(newPos, false); } if (selectablePos >= 0) { setNextSelectedPositionInt(selectablePos); checkSelectionChanged(); found = true; } } } if (!found) { // Nothing is selected mSelectedPosition = INVALID_POSITION; mSelectedRowId = INVALID_ROW_ID; mNextSelectedPosition = INVALID_POSITION; mNextSelectedRowId = INVALID_ROW_ID; mNeedSync = false; checkSelectionChanged(); } } void checkSelectionChanged() { if ((mSelectedPosition != mOldSelectedPosition) || (mSelectedRowId != mOldSelectedRowId)) { selectionChanged(); mOldSelectedPosition = mSelectedPosition; mOldSelectedRowId = mSelectedRowId; } } /** * Searches the adapter for a position matching mSyncRowId. The search starts at mSyncPosition * and then alternates between moving up and moving down until 1) we find the right position, or * 2) we run out of time, or 3) we have looked at every position * * @return Position of the row that matches mSyncRowId, or {@link #INVALID_POSITION} if it can't * be found */ int findSyncPosition() { int count = mItemCount; if (count == 0) { return INVALID_POSITION; } long idToMatch = mSyncRowId; int seed = mSyncPosition; // If there isn't a selection don't hunt for it if (idToMatch == INVALID_ROW_ID) { return INVALID_POSITION; } // Pin seed to reasonable values seed = Math.max(0, seed); seed = Math.min(count - 1, seed); long endTime = SystemClock.uptimeMillis() + SYNC_MAX_DURATION_MILLIS; long rowId; // first position scanned so far int first = seed; // last position scanned so far int last = seed; // True if we should move down on the next iteration boolean next = false; // True when we have looked at the first item in the data boolean hitFirst; // True when we have looked at the last item in the data boolean hitLast; // Get the item ID locally (instead of getItemIdAtPosition), so // we need the adapter T adapter = getAdapter(); if (adapter == null) { return INVALID_POSITION; } while (SystemClock.uptimeMillis() <= endTime) { rowId = adapter.getItemId(seed); if (rowId == idToMatch) { // Found it! return seed; } hitLast = last == count - 1; hitFirst = first == 0; if (hitLast && hitFirst) { // Looked at everything break; } if (hitFirst || (next && !hitLast)) { // Either we hit the top, or we are trying to move down last++; seed = last; // Try going up next time next = false; } else if (hitLast || (!next && !hitFirst)) { // Either we hit the bottom, or we are trying to move up first--; seed = first; // Try going down next time next = true; } } return INVALID_POSITION; } /** * Find a position that can be selected (i.e., is not a separator). * * @param position The starting position to look at. * @param lookDown Whether to look down for other positions. * @return The next selectable position starting at position and then searching either up or * down. Returns {@link #INVALID_POSITION} if nothing can be found. */ int lookForSelectablePosition(int position, boolean lookDown) { return position; } /** * Utility to keep mSelectedPosition and mSelectedRowId in sync * @param position Our current position */ void setSelectedPositionInt(int position) { mSelectedPosition = position; mSelectedRowId = getItemIdAtPosition(position); } /** * Utility to keep mNextSelectedPosition and mNextSelectedRowId in sync * @param position Intended value for mSelectedPosition the next time we go * through layout */ void setNextSelectedPositionInt(int position) { mNextSelectedPosition = position; mNextSelectedRowId = getItemIdAtPosition(position); // If we are trying to sync to the selection, update that too if (mNeedSync && mSyncMode == SYNC_SELECTED_POSITION && position >= 0) { mSyncPosition = position; mSyncRowId = mNextSelectedRowId; } } /** * Remember enough information to restore the screen state when the data has * changed. * */ void rememberSyncState() { if (getChildCount() > 0) { mNeedSync = true; mSyncHeight = mLayoutHeight; if (mSelectedPosition >= 0) { // Sync the selection state View v = getChildAt(mSelectedPosition - mFirstPosition); mSyncRowId = mNextSelectedRowId; mSyncPosition = mNextSelectedPosition; if (v != null) { mSpecificTop = v.getTop(); } mSyncMode = SYNC_SELECTED_POSITION; } else { // Sync the based on the offset of the first view View v = getChildAt(0); T adapter = getAdapter(); if (mFirstPosition >= 0 && mFirstPosition < adapter.getCount()) { mSyncRowId = adapter.getItemId(mFirstPosition); } else { mSyncRowId = NO_ID; } mSyncPosition = mFirstPosition; if (v != null) { mSpecificTop = v.getTop(); } mSyncMode = SYNC_FIRST_POSITION; } } } }
Java
package com.actionbarsherlock.internal.widget; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Canvas; import android.graphics.drawable.Drawable; import android.util.AttributeSet; import android.view.View; import com.actionbarsherlock.internal.nineoldandroids.widget.NineLinearLayout; /** * A simple extension of a regular linear layout that supports the divider API * of Android 4.0+. The dividers are added adjacent to the children by changing * their layout params. If you need to rely on the margins which fall in the * same orientation as the layout you should wrap the child in a simple * {@link android.widget.FrameLayout} so it can receive the margin. */ public class IcsLinearLayout extends NineLinearLayout { private static final int[] LinearLayout = new int[] { /* 0 */ android.R.attr.divider, /* 1 */ android.R.attr.showDividers, /* 2 */ android.R.attr.dividerPadding, }; private static final int LinearLayout_divider = 0; private static final int LinearLayout_showDividers = 1; private static final int LinearLayout_dividerPadding = 2; /** * Don't show any dividers. */ public static final int SHOW_DIVIDER_NONE = 0; /** * Show a divider at the beginning of the group. */ public static final int SHOW_DIVIDER_BEGINNING = 1; /** * Show dividers between each item in the group. */ public static final int SHOW_DIVIDER_MIDDLE = 2; /** * Show a divider at the end of the group. */ public static final int SHOW_DIVIDER_END = 4; private Drawable mDivider; private int mDividerWidth; private int mDividerHeight; private int mShowDividers; private int mDividerPadding; public IcsLinearLayout(Context context, AttributeSet attrs) { super(context, attrs); TypedArray a = context.obtainStyledAttributes(attrs, /*com.android.internal.R.styleable.*/LinearLayout); setDividerDrawable(a.getDrawable(/*com.android.internal.R.styleable.*/LinearLayout_divider)); mShowDividers = a.getInt(/*com.android.internal.R.styleable.*/LinearLayout_showDividers, SHOW_DIVIDER_NONE); mDividerPadding = a.getDimensionPixelSize(/*com.android.internal.R.styleable.*/LinearLayout_dividerPadding, 0); a.recycle(); } /** * Set how dividers should be shown between items in this layout * * @param showDividers One or more of {@link #SHOW_DIVIDER_BEGINNING}, * {@link #SHOW_DIVIDER_MIDDLE}, or {@link #SHOW_DIVIDER_END}, * or {@link #SHOW_DIVIDER_NONE} to show no dividers. */ public void setShowDividers(int showDividers) { if (showDividers != mShowDividers) { requestLayout(); invalidate(); //XXX This is required if you are toggling a divider off } mShowDividers = showDividers; } /** * @return A flag set indicating how dividers should be shown around items. * @see #setShowDividers(int) */ public int getShowDividers() { return mShowDividers; } /** * Set a drawable to be used as a divider between items. * @param divider Drawable that will divide each item. * @see #setShowDividers(int) */ public void setDividerDrawable(Drawable divider) { if (divider == mDivider) { return; } mDivider = divider; if (divider != null) { mDividerWidth = divider.getIntrinsicWidth(); mDividerHeight = divider.getIntrinsicHeight(); } else { mDividerWidth = 0; mDividerHeight = 0; } setWillNotDraw(divider == null); requestLayout(); } /** * Set padding displayed on both ends of dividers. * * @param padding Padding value in pixels that will be applied to each end * * @see #setShowDividers(int) * @see #setDividerDrawable(Drawable) * @see #getDividerPadding() */ public void setDividerPadding(int padding) { mDividerPadding = padding; } /** * Get the padding size used to inset dividers in pixels * * @see #setShowDividers(int) * @see #setDividerDrawable(Drawable) * @see #setDividerPadding(int) */ public int getDividerPadding() { return mDividerPadding; } /** * Get the width of the current divider drawable. * * @hide Used internally by framework. */ public int getDividerWidth() { return mDividerWidth; } @Override protected void measureChildWithMargins(View child, int parentWidthMeasureSpec, int widthUsed, int parentHeightMeasureSpec, int heightUsed) { final int index = indexOfChild(child); final int orientation = getOrientation(); final LayoutParams params = (LayoutParams) child.getLayoutParams(); if (hasDividerBeforeChildAt(index)) { if (orientation == VERTICAL) { //Account for the divider by pushing everything up params.topMargin = mDividerHeight; } else { //Account for the divider by pushing everything left params.leftMargin = mDividerWidth; } } final int count = getChildCount(); if (index == count - 1) { if (hasDividerBeforeChildAt(count)) { if (orientation == VERTICAL) { params.bottomMargin = mDividerHeight; } else { params.rightMargin = mDividerWidth; } } } super.measureChildWithMargins(child, parentWidthMeasureSpec, widthUsed, parentHeightMeasureSpec, heightUsed); } @Override protected void onDraw(Canvas canvas) { if (mDivider != null) { if (getOrientation() == VERTICAL) { drawDividersVertical(canvas); } else { drawDividersHorizontal(canvas); } } super.onDraw(canvas); } void drawDividersVertical(Canvas canvas) { final int count = getChildCount(); for (int i = 0; i < count; i++) { final View child = getChildAt(i); if (child != null && child.getVisibility() != GONE) { if (hasDividerBeforeChildAt(i)) { final LayoutParams lp = (LayoutParams) child.getLayoutParams(); final int top = child.getTop() - lp.topMargin/* - mDividerHeight*/; drawHorizontalDivider(canvas, top); } } } if (hasDividerBeforeChildAt(count)) { final View child = getChildAt(count - 1); int bottom = 0; if (child == null) { bottom = getHeight() - getPaddingBottom() - mDividerHeight; } else { final LayoutParams lp = (LayoutParams) child.getLayoutParams(); bottom = child.getBottom()/* + lp.bottomMargin*/; } drawHorizontalDivider(canvas, bottom); } } void drawDividersHorizontal(Canvas canvas) { final int count = getChildCount(); for (int i = 0; i < count; i++) { final View child = getChildAt(i); if (child != null && child.getVisibility() != GONE) { if (hasDividerBeforeChildAt(i)) { final LayoutParams lp = (LayoutParams) child.getLayoutParams(); final int left = child.getLeft() - lp.leftMargin/* - mDividerWidth*/; drawVerticalDivider(canvas, left); } } } if (hasDividerBeforeChildAt(count)) { final View child = getChildAt(count - 1); int right = 0; if (child == null) { right = getWidth() - getPaddingRight() - mDividerWidth; } else { final LayoutParams lp = (LayoutParams) child.getLayoutParams(); right = child.getRight()/* + lp.rightMargin*/; } drawVerticalDivider(canvas, right); } } void drawHorizontalDivider(Canvas canvas, int top) { mDivider.setBounds(getPaddingLeft() + mDividerPadding, top, getWidth() - getPaddingRight() - mDividerPadding, top + mDividerHeight); mDivider.draw(canvas); } void drawVerticalDivider(Canvas canvas, int left) { mDivider.setBounds(left, getPaddingTop() + mDividerPadding, left + mDividerWidth, getHeight() - getPaddingBottom() - mDividerPadding); mDivider.draw(canvas); } /** * Determines where to position dividers between children. * * @param childIndex Index of child to check for preceding divider * @return true if there should be a divider before the child at childIndex * @hide Pending API consideration. Currently only used internally by the system. */ protected boolean hasDividerBeforeChildAt(int childIndex) { if (childIndex == 0) { return (mShowDividers & SHOW_DIVIDER_BEGINNING) != 0; } else if (childIndex == getChildCount()) { return (mShowDividers & SHOW_DIVIDER_END) != 0; } else if ((mShowDividers & SHOW_DIVIDER_MIDDLE) != 0) { boolean hasVisibleViewBefore = false; for (int i = childIndex - 1; i >= 0; i--) { if (getChildAt(i).getVisibility() != GONE) { hasVisibleViewBefore = true; break; } } return hasVisibleViewBefore; } return false; } }
Java
package com.actionbarsherlock.internal.widget; import java.util.Locale; import android.content.Context; import android.content.res.TypedArray; import android.os.Build; import android.util.AttributeSet; import android.widget.Button; public class CapitalizingButton extends Button { private static final boolean SANS_ICE_CREAM = Build.VERSION.SDK_INT < Build.VERSION_CODES.ICE_CREAM_SANDWICH; private static final boolean IS_GINGERBREAD = Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD; private static final int[] R_styleable_Button = new int[] { android.R.attr.textAllCaps }; private static final int R_styleable_Button_textAllCaps = 0; private boolean mAllCaps; public CapitalizingButton(Context context, AttributeSet attrs) { super(context, attrs); TypedArray a = context.obtainStyledAttributes(attrs, R_styleable_Button); mAllCaps = a.getBoolean(R_styleable_Button_textAllCaps, true); a.recycle(); } public void setTextCompat(CharSequence text) { if (SANS_ICE_CREAM && mAllCaps && text != null) { if (IS_GINGERBREAD) { setText(text.toString().toUpperCase(Locale.ROOT)); } else { setText(text.toString().toUpperCase()); } } else { setText(text); } } }
Java
/* * Copyright (C) 2006 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.actionbarsherlock.internal.widget; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Bitmap; import android.graphics.BitmapShader; import android.graphics.Canvas; import android.graphics.Rect; import android.graphics.Shader; import android.graphics.drawable.Animatable; import android.graphics.drawable.AnimationDrawable; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.ClipDrawable; import android.graphics.drawable.Drawable; import android.graphics.drawable.LayerDrawable; import android.graphics.drawable.ShapeDrawable; import android.graphics.drawable.shapes.RoundRectShape; import android.graphics.drawable.shapes.Shape; import android.os.Build; import android.os.Parcel; import android.os.Parcelable; import android.os.SystemClock; import android.util.AttributeSet; import android.view.Gravity; import android.view.View; import android.view.ViewDebug; import android.view.accessibility.AccessibilityEvent; import android.view.accessibility.AccessibilityManager; import android.view.animation.AlphaAnimation; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.view.animation.Interpolator; import android.view.animation.LinearInterpolator; import android.view.animation.Transformation; import android.widget.RemoteViews.RemoteView; /** * <p> * Visual indicator of progress in some operation. Displays a bar to the user * representing how far the operation has progressed; the application can * change the amount of progress (modifying the length of the bar) as it moves * forward. There is also a secondary progress displayable on a progress bar * which is useful for displaying intermediate progress, such as the buffer * level during a streaming playback progress bar. * </p> * * <p> * A progress bar can also be made indeterminate. In indeterminate mode, the * progress bar shows a cyclic animation without an indication of progress. This mode is used by * applications when the length of the task is unknown. The indeterminate progress bar can be either * a spinning wheel or a horizontal bar. * </p> * * <p>The following code example shows how a progress bar can be used from * a worker thread to update the user interface to notify the user of progress: * </p> * * <pre> * public class MyActivity extends Activity { * private static final int PROGRESS = 0x1; * * private ProgressBar mProgress; * private int mProgressStatus = 0; * * private Handler mHandler = new Handler(); * * protected void onCreate(Bundle icicle) { * super.onCreate(icicle); * * setContentView(R.layout.progressbar_activity); * * mProgress = (ProgressBar) findViewById(R.id.progress_bar); * * // Start lengthy operation in a background thread * new Thread(new Runnable() { * public void run() { * while (mProgressStatus &lt; 100) { * mProgressStatus = doWork(); * * // Update the progress bar * mHandler.post(new Runnable() { * public void run() { * mProgress.setProgress(mProgressStatus); * } * }); * } * } * }).start(); * } * }</pre> * * <p>To add a progress bar to a layout file, you can use the {@code &lt;ProgressBar&gt;} element. * By default, the progress bar is a spinning wheel (an indeterminate indicator). To change to a * horizontal progress bar, apply the {@link android.R.style#Widget_ProgressBar_Horizontal * Widget.ProgressBar.Horizontal} style, like so:</p> * * <pre> * &lt;ProgressBar * style="@android:style/Widget.ProgressBar.Horizontal" * ... /&gt;</pre> * * <p>If you will use the progress bar to show real progress, you must use the horizontal bar. You * can then increment the progress with {@link #incrementProgressBy incrementProgressBy()} or * {@link #setProgress setProgress()}. By default, the progress bar is full when it reaches 100. If * necessary, you can adjust the maximum value (the value for a full bar) using the {@link * android.R.styleable#ProgressBar_max android:max} attribute. Other attributes available are listed * below.</p> * * <p>Another common style to apply to the progress bar is {@link * android.R.style#Widget_ProgressBar_Small Widget.ProgressBar.Small}, which shows a smaller * version of the spinning wheel&mdash;useful when waiting for content to load. * For example, you can insert this kind of progress bar into your default layout for * a view that will be populated by some content fetched from the Internet&mdash;the spinning wheel * appears immediately and when your application receives the content, it replaces the progress bar * with the loaded content. For example:</p> * * <pre> * &lt;LinearLayout * android:orientation="horizontal" * ... &gt; * &lt;ProgressBar * android:layout_width="wrap_content" * android:layout_height="wrap_content" * style="@android:style/Widget.ProgressBar.Small" * android:layout_marginRight="5dp" /&gt; * &lt;TextView * android:layout_width="wrap_content" * android:layout_height="wrap_content" * android:text="@string/loading" /&gt; * &lt;/LinearLayout&gt;</pre> * * <p>Other progress bar styles provided by the system include:</p> * <ul> * <li>{@link android.R.style#Widget_ProgressBar_Horizontal Widget.ProgressBar.Horizontal}</li> * <li>{@link android.R.style#Widget_ProgressBar_Small Widget.ProgressBar.Small}</li> * <li>{@link android.R.style#Widget_ProgressBar_Large Widget.ProgressBar.Large}</li> * <li>{@link android.R.style#Widget_ProgressBar_Inverse Widget.ProgressBar.Inverse}</li> * <li>{@link android.R.style#Widget_ProgressBar_Small_Inverse * Widget.ProgressBar.Small.Inverse}</li> * <li>{@link android.R.style#Widget_ProgressBar_Large_Inverse * Widget.ProgressBar.Large.Inverse}</li> * </ul> * <p>The "inverse" styles provide an inverse color scheme for the spinner, which may be necessary * if your application uses a light colored theme (a white background).</p> * * <p><strong>XML attributes</b></strong> * <p> * See {@link android.R.styleable#ProgressBar ProgressBar Attributes}, * {@link android.R.styleable#View View Attributes} * </p> * * @attr ref android.R.styleable#ProgressBar_animationResolution * @attr ref android.R.styleable#ProgressBar_indeterminate * @attr ref android.R.styleable#ProgressBar_indeterminateBehavior * @attr ref android.R.styleable#ProgressBar_indeterminateDrawable * @attr ref android.R.styleable#ProgressBar_indeterminateDuration * @attr ref android.R.styleable#ProgressBar_indeterminateOnly * @attr ref android.R.styleable#ProgressBar_interpolator * @attr ref android.R.styleable#ProgressBar_max * @attr ref android.R.styleable#ProgressBar_maxHeight * @attr ref android.R.styleable#ProgressBar_maxWidth * @attr ref android.R.styleable#ProgressBar_minHeight * @attr ref android.R.styleable#ProgressBar_minWidth * @attr ref android.R.styleable#ProgressBar_progress * @attr ref android.R.styleable#ProgressBar_progressDrawable * @attr ref android.R.styleable#ProgressBar_secondaryProgress */ @RemoteView public class IcsProgressBar extends View { private static final boolean IS_HONEYCOMB = Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB; private static final int MAX_LEVEL = 10000; private static final int ANIMATION_RESOLUTION = 200; private static final int TIMEOUT_SEND_ACCESSIBILITY_EVENT = 200; private static final int[] ProgressBar = new int[] { android.R.attr.maxWidth, android.R.attr.maxHeight, android.R.attr.max, android.R.attr.progress, android.R.attr.secondaryProgress, android.R.attr.indeterminate, android.R.attr.indeterminateOnly, android.R.attr.indeterminateDrawable, android.R.attr.progressDrawable, android.R.attr.indeterminateDuration, android.R.attr.indeterminateBehavior, android.R.attr.minWidth, android.R.attr.minHeight, android.R.attr.interpolator, android.R.attr.animationResolution, }; private static final int ProgressBar_maxWidth = 0; private static final int ProgressBar_maxHeight = 1; private static final int ProgressBar_max = 2; private static final int ProgressBar_progress = 3; private static final int ProgressBar_secondaryProgress = 4; private static final int ProgressBar_indeterminate = 5; private static final int ProgressBar_indeterminateOnly = 6; private static final int ProgressBar_indeterminateDrawable = 7; private static final int ProgressBar_progressDrawable = 8; private static final int ProgressBar_indeterminateDuration = 9; private static final int ProgressBar_indeterminateBehavior = 10; private static final int ProgressBar_minWidth = 11; private static final int ProgressBar_minHeight = 12; private static final int ProgressBar_interpolator = 13; private static final int ProgressBar_animationResolution = 14; int mMinWidth; int mMaxWidth; int mMinHeight; int mMaxHeight; private int mProgress; private int mSecondaryProgress; private int mMax; private int mBehavior; private int mDuration; private boolean mIndeterminate; private boolean mOnlyIndeterminate; private Transformation mTransformation; private AlphaAnimation mAnimation; private Drawable mIndeterminateDrawable; private int mIndeterminateRealLeft; private int mIndeterminateRealTop; private Drawable mProgressDrawable; private Drawable mCurrentDrawable; Bitmap mSampleTile; private boolean mNoInvalidate; private Interpolator mInterpolator; private RefreshProgressRunnable mRefreshProgressRunnable; private long mUiThreadId; private boolean mShouldStartAnimationDrawable; private long mLastDrawTime; private boolean mInDrawing; private int mAnimationResolution; private AccessibilityManager mAccessibilityManager; private AccessibilityEventSender mAccessibilityEventSender; /** * Create a new progress bar with range 0...100 and initial progress of 0. * @param context the application environment */ public IcsProgressBar(Context context) { this(context, null); } public IcsProgressBar(Context context, AttributeSet attrs) { this(context, attrs, android.R.attr.progressBarStyle); } public IcsProgressBar(Context context, AttributeSet attrs, int defStyle) { this(context, attrs, defStyle, 0); } /** * @hide */ public IcsProgressBar(Context context, AttributeSet attrs, int defStyle, int styleRes) { super(context, attrs, defStyle); mUiThreadId = Thread.currentThread().getId(); initProgressBar(); TypedArray a = context.obtainStyledAttributes(attrs, /*R.styleable.*/ProgressBar, defStyle, styleRes); mNoInvalidate = true; Drawable drawable = a.getDrawable(/*R.styleable.*/ProgressBar_progressDrawable); if (drawable != null) { drawable = tileify(drawable, false); // Calling this method can set mMaxHeight, make sure the corresponding // XML attribute for mMaxHeight is read after calling this method setProgressDrawable(drawable); } mDuration = a.getInt(/*R.styleable.*/ProgressBar_indeterminateDuration, mDuration); mMinWidth = a.getDimensionPixelSize(/*R.styleable.*/ProgressBar_minWidth, mMinWidth); mMaxWidth = a.getDimensionPixelSize(/*R.styleable.*/ProgressBar_maxWidth, mMaxWidth); mMinHeight = a.getDimensionPixelSize(/*R.styleable.*/ProgressBar_minHeight, mMinHeight); mMaxHeight = a.getDimensionPixelSize(/*R.styleable.*/ProgressBar_maxHeight, mMaxHeight); mBehavior = a.getInt(/*R.styleable.*/ProgressBar_indeterminateBehavior, mBehavior); final int resID = a.getResourceId( /*com.android.internal.R.styleable.*/ProgressBar_interpolator, android.R.anim.linear_interpolator); // default to linear interpolator if (resID > 0) { setInterpolator(context, resID); } setMax(a.getInt(/*R.styleable.*/ProgressBar_max, mMax)); setProgress(a.getInt(/*R.styleable.*/ProgressBar_progress, mProgress)); setSecondaryProgress( a.getInt(/*R.styleable.*/ProgressBar_secondaryProgress, mSecondaryProgress)); drawable = a.getDrawable(/*R.styleable.*/ProgressBar_indeterminateDrawable); if (drawable != null) { drawable = tileifyIndeterminate(drawable); setIndeterminateDrawable(drawable); } mOnlyIndeterminate = a.getBoolean( /*R.styleable.*/ProgressBar_indeterminateOnly, mOnlyIndeterminate); mNoInvalidate = false; setIndeterminate(mOnlyIndeterminate || a.getBoolean( /*R.styleable.*/ProgressBar_indeterminate, mIndeterminate)); mAnimationResolution = a.getInteger(/*R.styleable.*/ProgressBar_animationResolution, ANIMATION_RESOLUTION); a.recycle(); mAccessibilityManager = (AccessibilityManager)context.getSystemService(Context.ACCESSIBILITY_SERVICE); } /** * Converts a drawable to a tiled version of itself. It will recursively * traverse layer and state list drawables. */ private Drawable tileify(Drawable drawable, boolean clip) { if (drawable instanceof LayerDrawable) { LayerDrawable background = (LayerDrawable) drawable; final int N = background.getNumberOfLayers(); Drawable[] outDrawables = new Drawable[N]; for (int i = 0; i < N; i++) { int id = background.getId(i); outDrawables[i] = tileify(background.getDrawable(i), (id == android.R.id.progress || id == android.R.id.secondaryProgress)); } LayerDrawable newBg = new LayerDrawable(outDrawables); for (int i = 0; i < N; i++) { newBg.setId(i, background.getId(i)); } return newBg; }/* else if (drawable instanceof StateListDrawable) { StateListDrawable in = (StateListDrawable) drawable; StateListDrawable out = new StateListDrawable(); int numStates = in.getStateCount(); for (int i = 0; i < numStates; i++) { out.addState(in.getStateSet(i), tileify(in.getStateDrawable(i), clip)); } return out; }*/ else if (drawable instanceof BitmapDrawable) { final Bitmap tileBitmap = ((BitmapDrawable) drawable).getBitmap(); if (mSampleTile == null) { mSampleTile = tileBitmap; } final ShapeDrawable shapeDrawable = new ShapeDrawable(getDrawableShape()); final BitmapShader bitmapShader = new BitmapShader(tileBitmap, Shader.TileMode.REPEAT, Shader.TileMode.CLAMP); shapeDrawable.getPaint().setShader(bitmapShader); return (clip) ? new ClipDrawable(shapeDrawable, Gravity.LEFT, ClipDrawable.HORIZONTAL) : shapeDrawable; } return drawable; } Shape getDrawableShape() { final float[] roundedCorners = new float[] { 5, 5, 5, 5, 5, 5, 5, 5 }; return new RoundRectShape(roundedCorners, null, null); } /** * Convert a AnimationDrawable for use as a barberpole animation. * Each frame of the animation is wrapped in a ClipDrawable and * given a tiling BitmapShader. */ private Drawable tileifyIndeterminate(Drawable drawable) { if (drawable instanceof AnimationDrawable) { AnimationDrawable background = (AnimationDrawable) drawable; final int N = background.getNumberOfFrames(); AnimationDrawable newBg = new AnimationDrawable(); newBg.setOneShot(background.isOneShot()); for (int i = 0; i < N; i++) { Drawable frame = tileify(background.getFrame(i), true); frame.setLevel(10000); newBg.addFrame(frame, background.getDuration(i)); } newBg.setLevel(10000); drawable = newBg; } return drawable; } /** * <p> * Initialize the progress bar's default values: * </p> * <ul> * <li>progress = 0</li> * <li>max = 100</li> * <li>animation duration = 4000 ms</li> * <li>indeterminate = false</li> * <li>behavior = repeat</li> * </ul> */ private void initProgressBar() { mMax = 100; mProgress = 0; mSecondaryProgress = 0; mIndeterminate = false; mOnlyIndeterminate = false; mDuration = 4000; mBehavior = AlphaAnimation.RESTART; mMinWidth = 24; mMaxWidth = 48; mMinHeight = 24; mMaxHeight = 48; } /** * <p>Indicate whether this progress bar is in indeterminate mode.</p> * * @return true if the progress bar is in indeterminate mode */ @ViewDebug.ExportedProperty(category = "progress") public synchronized boolean isIndeterminate() { return mIndeterminate; } /** * <p>Change the indeterminate mode for this progress bar. In indeterminate * mode, the progress is ignored and the progress bar shows an infinite * animation instead.</p> * * If this progress bar's style only supports indeterminate mode (such as the circular * progress bars), then this will be ignored. * * @param indeterminate true to enable the indeterminate mode */ public synchronized void setIndeterminate(boolean indeterminate) { if ((!mOnlyIndeterminate || !mIndeterminate) && indeterminate != mIndeterminate) { mIndeterminate = indeterminate; if (indeterminate) { // swap between indeterminate and regular backgrounds mCurrentDrawable = mIndeterminateDrawable; startAnimation(); } else { mCurrentDrawable = mProgressDrawable; stopAnimation(); } } } /** * <p>Get the drawable used to draw the progress bar in * indeterminate mode.</p> * * @return a {@link android.graphics.drawable.Drawable} instance * * @see #setIndeterminateDrawable(android.graphics.drawable.Drawable) * @see #setIndeterminate(boolean) */ public Drawable getIndeterminateDrawable() { return mIndeterminateDrawable; } /** * <p>Define the drawable used to draw the progress bar in * indeterminate mode.</p> * * @param d the new drawable * * @see #getIndeterminateDrawable() * @see #setIndeterminate(boolean) */ public void setIndeterminateDrawable(Drawable d) { if (d != null) { d.setCallback(this); } mIndeterminateDrawable = d; if (mIndeterminate) { mCurrentDrawable = d; postInvalidate(); } } /** * <p>Get the drawable used to draw the progress bar in * progress mode.</p> * * @return a {@link android.graphics.drawable.Drawable} instance * * @see #setProgressDrawable(android.graphics.drawable.Drawable) * @see #setIndeterminate(boolean) */ public Drawable getProgressDrawable() { return mProgressDrawable; } /** * <p>Define the drawable used to draw the progress bar in * progress mode.</p> * * @param d the new drawable * * @see #getProgressDrawable() * @see #setIndeterminate(boolean) */ public void setProgressDrawable(Drawable d) { boolean needUpdate; if (mProgressDrawable != null && d != mProgressDrawable) { mProgressDrawable.setCallback(null); needUpdate = true; } else { needUpdate = false; } if (d != null) { d.setCallback(this); // Make sure the ProgressBar is always tall enough int drawableHeight = d.getMinimumHeight(); if (mMaxHeight < drawableHeight) { mMaxHeight = drawableHeight; requestLayout(); } } mProgressDrawable = d; if (!mIndeterminate) { mCurrentDrawable = d; postInvalidate(); } if (needUpdate) { updateDrawableBounds(getWidth(), getHeight()); updateDrawableState(); doRefreshProgress(android.R.id.progress, mProgress, false, false); doRefreshProgress(android.R.id.secondaryProgress, mSecondaryProgress, false, false); } } /** * @return The drawable currently used to draw the progress bar */ Drawable getCurrentDrawable() { return mCurrentDrawable; } @Override protected boolean verifyDrawable(Drawable who) { return who == mProgressDrawable || who == mIndeterminateDrawable || super.verifyDrawable(who); } @Override public void jumpDrawablesToCurrentState() { super.jumpDrawablesToCurrentState(); if (mProgressDrawable != null) mProgressDrawable.jumpToCurrentState(); if (mIndeterminateDrawable != null) mIndeterminateDrawable.jumpToCurrentState(); } @Override public void postInvalidate() { if (!mNoInvalidate) { super.postInvalidate(); } } private class RefreshProgressRunnable implements Runnable { private int mId; private int mProgress; private boolean mFromUser; RefreshProgressRunnable(int id, int progress, boolean fromUser) { mId = id; mProgress = progress; mFromUser = fromUser; } public void run() { doRefreshProgress(mId, mProgress, mFromUser, true); // Put ourselves back in the cache when we are done mRefreshProgressRunnable = this; } public void setup(int id, int progress, boolean fromUser) { mId = id; mProgress = progress; mFromUser = fromUser; } } private synchronized void doRefreshProgress(int id, int progress, boolean fromUser, boolean callBackToApp) { float scale = mMax > 0 ? (float) progress / (float) mMax : 0; final Drawable d = mCurrentDrawable; if (d != null) { Drawable progressDrawable = null; if (d instanceof LayerDrawable) { progressDrawable = ((LayerDrawable) d).findDrawableByLayerId(id); } final int level = (int) (scale * MAX_LEVEL); (progressDrawable != null ? progressDrawable : d).setLevel(level); } else { invalidate(); } if (callBackToApp && id == android.R.id.progress) { onProgressRefresh(scale, fromUser); } } void onProgressRefresh(float scale, boolean fromUser) { if (mAccessibilityManager.isEnabled()) { scheduleAccessibilityEventSender(); } } private synchronized void refreshProgress(int id, int progress, boolean fromUser) { if (mUiThreadId == Thread.currentThread().getId()) { doRefreshProgress(id, progress, fromUser, true); } else { RefreshProgressRunnable r; if (mRefreshProgressRunnable != null) { // Use cached RefreshProgressRunnable if available r = mRefreshProgressRunnable; // Uncache it mRefreshProgressRunnable = null; r.setup(id, progress, fromUser); } else { // Make a new one r = new RefreshProgressRunnable(id, progress, fromUser); } post(r); } } /** * <p>Set the current progress to the specified value. Does not do anything * if the progress bar is in indeterminate mode.</p> * * @param progress the new progress, between 0 and {@link #getMax()} * * @see #setIndeterminate(boolean) * @see #isIndeterminate() * @see #getProgress() * @see #incrementProgressBy(int) */ public synchronized void setProgress(int progress) { setProgress(progress, false); } synchronized void setProgress(int progress, boolean fromUser) { if (mIndeterminate) { return; } if (progress < 0) { progress = 0; } if (progress > mMax) { progress = mMax; } if (progress != mProgress) { mProgress = progress; refreshProgress(android.R.id.progress, mProgress, fromUser); } } /** * <p> * Set the current secondary progress to the specified value. Does not do * anything if the progress bar is in indeterminate mode. * </p> * * @param secondaryProgress the new secondary progress, between 0 and {@link #getMax()} * @see #setIndeterminate(boolean) * @see #isIndeterminate() * @see #getSecondaryProgress() * @see #incrementSecondaryProgressBy(int) */ public synchronized void setSecondaryProgress(int secondaryProgress) { if (mIndeterminate) { return; } if (secondaryProgress < 0) { secondaryProgress = 0; } if (secondaryProgress > mMax) { secondaryProgress = mMax; } if (secondaryProgress != mSecondaryProgress) { mSecondaryProgress = secondaryProgress; refreshProgress(android.R.id.secondaryProgress, mSecondaryProgress, false); } } /** * <p>Get the progress bar's current level of progress. Return 0 when the * progress bar is in indeterminate mode.</p> * * @return the current progress, between 0 and {@link #getMax()} * * @see #setIndeterminate(boolean) * @see #isIndeterminate() * @see #setProgress(int) * @see #setMax(int) * @see #getMax() */ @ViewDebug.ExportedProperty(category = "progress") public synchronized int getProgress() { return mIndeterminate ? 0 : mProgress; } /** * <p>Get the progress bar's current level of secondary progress. Return 0 when the * progress bar is in indeterminate mode.</p> * * @return the current secondary progress, between 0 and {@link #getMax()} * * @see #setIndeterminate(boolean) * @see #isIndeterminate() * @see #setSecondaryProgress(int) * @see #setMax(int) * @see #getMax() */ @ViewDebug.ExportedProperty(category = "progress") public synchronized int getSecondaryProgress() { return mIndeterminate ? 0 : mSecondaryProgress; } /** * <p>Return the upper limit of this progress bar's range.</p> * * @return a positive integer * * @see #setMax(int) * @see #getProgress() * @see #getSecondaryProgress() */ @ViewDebug.ExportedProperty(category = "progress") public synchronized int getMax() { return mMax; } /** * <p>Set the range of the progress bar to 0...<tt>max</tt>.</p> * * @param max the upper range of this progress bar * * @see #getMax() * @see #setProgress(int) * @see #setSecondaryProgress(int) */ public synchronized void setMax(int max) { if (max < 0) { max = 0; } if (max != mMax) { mMax = max; postInvalidate(); if (mProgress > max) { mProgress = max; } refreshProgress(android.R.id.progress, mProgress, false); } } /** * <p>Increase the progress bar's progress by the specified amount.</p> * * @param diff the amount by which the progress must be increased * * @see #setProgress(int) */ public synchronized final void incrementProgressBy(int diff) { setProgress(mProgress + diff); } /** * <p>Increase the progress bar's secondary progress by the specified amount.</p> * * @param diff the amount by which the secondary progress must be increased * * @see #setSecondaryProgress(int) */ public synchronized final void incrementSecondaryProgressBy(int diff) { setSecondaryProgress(mSecondaryProgress + diff); } /** * <p>Start the indeterminate progress animation.</p> */ void startAnimation() { if (getVisibility() != VISIBLE) { return; } if (mIndeterminateDrawable instanceof Animatable) { mShouldStartAnimationDrawable = true; mAnimation = null; } else { if (mInterpolator == null) { mInterpolator = new LinearInterpolator(); } mTransformation = new Transformation(); mAnimation = new AlphaAnimation(0.0f, 1.0f); mAnimation.setRepeatMode(mBehavior); mAnimation.setRepeatCount(Animation.INFINITE); mAnimation.setDuration(mDuration); mAnimation.setInterpolator(mInterpolator); mAnimation.setStartTime(Animation.START_ON_FIRST_FRAME); } postInvalidate(); } /** * <p>Stop the indeterminate progress animation.</p> */ void stopAnimation() { mAnimation = null; mTransformation = null; if (mIndeterminateDrawable instanceof Animatable) { ((Animatable) mIndeterminateDrawable).stop(); mShouldStartAnimationDrawable = false; } postInvalidate(); } /** * Sets the acceleration curve for the indeterminate animation. * The interpolator is loaded as a resource from the specified context. * * @param context The application environment * @param resID The resource identifier of the interpolator to load */ public void setInterpolator(Context context, int resID) { setInterpolator(AnimationUtils.loadInterpolator(context, resID)); } /** * Sets the acceleration curve for the indeterminate animation. * Defaults to a linear interpolation. * * @param interpolator The interpolator which defines the acceleration curve */ public void setInterpolator(Interpolator interpolator) { mInterpolator = interpolator; } /** * Gets the acceleration curve type for the indeterminate animation. * * @return the {@link Interpolator} associated to this animation */ public Interpolator getInterpolator() { return mInterpolator; } @Override public void setVisibility(int v) { if (getVisibility() != v) { super.setVisibility(v); if (mIndeterminate) { // let's be nice with the UI thread if (v == GONE || v == INVISIBLE) { stopAnimation(); } else { startAnimation(); } } } } @Override protected void onVisibilityChanged(View changedView, int visibility) { super.onVisibilityChanged(changedView, visibility); if (mIndeterminate) { // let's be nice with the UI thread if (visibility == GONE || visibility == INVISIBLE) { stopAnimation(); } else { startAnimation(); } } } @Override public void invalidateDrawable(Drawable dr) { if (!mInDrawing) { if (verifyDrawable(dr)) { final Rect dirty = dr.getBounds(); final int scrollX = getScrollX() + getPaddingLeft(); final int scrollY = getScrollY() + getPaddingTop(); invalidate(dirty.left + scrollX, dirty.top + scrollY, dirty.right + scrollX, dirty.bottom + scrollY); } else { super.invalidateDrawable(dr); } } } /** * @hide * @Override public int getResolvedLayoutDirection(Drawable who) { return (who == mProgressDrawable || who == mIndeterminateDrawable) ? getResolvedLayoutDirection() : super.getResolvedLayoutDirection(who); } */ @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { updateDrawableBounds(w, h); } private void updateDrawableBounds(int w, int h) { // onDraw will translate the canvas so we draw starting at 0,0 int right = w - getPaddingRight() - getPaddingLeft(); int bottom = h - getPaddingBottom() - getPaddingTop(); int top = 0; int left = 0; if (mIndeterminateDrawable != null) { // Aspect ratio logic does not apply to AnimationDrawables if (mOnlyIndeterminate && !(mIndeterminateDrawable instanceof AnimationDrawable)) { // Maintain aspect ratio. Certain kinds of animated drawables // get very confused otherwise. final int intrinsicWidth = mIndeterminateDrawable.getIntrinsicWidth(); final int intrinsicHeight = mIndeterminateDrawable.getIntrinsicHeight(); final float intrinsicAspect = (float) intrinsicWidth / intrinsicHeight; final float boundAspect = (float) w / h; if (intrinsicAspect != boundAspect) { if (boundAspect > intrinsicAspect) { // New width is larger. Make it smaller to match height. final int width = (int) (h * intrinsicAspect); left = (w - width) / 2; right = left + width; } else { // New height is larger. Make it smaller to match width. final int height = (int) (w * (1 / intrinsicAspect)); top = (h - height) / 2; bottom = top + height; } } } mIndeterminateDrawable.setBounds(0, 0, right - left, bottom - top); mIndeterminateRealLeft = left; mIndeterminateRealTop = top; } if (mProgressDrawable != null) { mProgressDrawable.setBounds(0, 0, right, bottom); } } @Override protected synchronized void onDraw(Canvas canvas) { super.onDraw(canvas); Drawable d = mCurrentDrawable; if (d != null) { // Translate canvas so a indeterminate circular progress bar with padding // rotates properly in its animation canvas.save(); canvas.translate(getPaddingLeft() + mIndeterminateRealLeft, getPaddingTop() + mIndeterminateRealTop); long time = getDrawingTime(); if (mAnimation != null) { mAnimation.getTransformation(time, mTransformation); float scale = mTransformation.getAlpha(); try { mInDrawing = true; d.setLevel((int) (scale * MAX_LEVEL)); } finally { mInDrawing = false; } if (SystemClock.uptimeMillis() - mLastDrawTime >= mAnimationResolution) { mLastDrawTime = SystemClock.uptimeMillis(); postInvalidateDelayed(mAnimationResolution); } } d.draw(canvas); canvas.restore(); if (mShouldStartAnimationDrawable && d instanceof Animatable) { ((Animatable) d).start(); mShouldStartAnimationDrawable = false; } } } @Override protected synchronized void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { Drawable d = mCurrentDrawable; int dw = 0; int dh = 0; if (d != null) { dw = Math.max(mMinWidth, Math.min(mMaxWidth, d.getIntrinsicWidth())); dh = Math.max(mMinHeight, Math.min(mMaxHeight, d.getIntrinsicHeight())); } updateDrawableState(); dw += getPaddingLeft() + getPaddingRight(); dh += getPaddingTop() + getPaddingBottom(); if (IS_HONEYCOMB) { setMeasuredDimension(View.resolveSizeAndState(dw, widthMeasureSpec, 0), View.resolveSizeAndState(dh, heightMeasureSpec, 0)); } else { setMeasuredDimension(View.resolveSize(dw, widthMeasureSpec), View.resolveSize(dh, heightMeasureSpec)); } } @Override protected void drawableStateChanged() { super.drawableStateChanged(); updateDrawableState(); } private void updateDrawableState() { int[] state = getDrawableState(); if (mProgressDrawable != null && mProgressDrawable.isStateful()) { mProgressDrawable.setState(state); } if (mIndeterminateDrawable != null && mIndeterminateDrawable.isStateful()) { mIndeterminateDrawable.setState(state); } } static class SavedState extends BaseSavedState { int progress; int secondaryProgress; /** * Constructor called from {@link IcsProgressBar#onSaveInstanceState()} */ SavedState(Parcelable superState) { super(superState); } /** * Constructor called from {@link #CREATOR} */ private SavedState(Parcel in) { super(in); progress = in.readInt(); secondaryProgress = in.readInt(); } @Override public void writeToParcel(Parcel out, int flags) { super.writeToParcel(out, flags); out.writeInt(progress); out.writeInt(secondaryProgress); } public static final Parcelable.Creator<SavedState> CREATOR = new Parcelable.Creator<SavedState>() { public SavedState createFromParcel(Parcel in) { return new SavedState(in); } public SavedState[] newArray(int size) { return new SavedState[size]; } }; } @Override public Parcelable onSaveInstanceState() { // Force our ancestor class to save its state Parcelable superState = super.onSaveInstanceState(); SavedState ss = new SavedState(superState); ss.progress = mProgress; ss.secondaryProgress = mSecondaryProgress; return ss; } @Override public void onRestoreInstanceState(Parcelable state) { SavedState ss = (SavedState) state; super.onRestoreInstanceState(ss.getSuperState()); setProgress(ss.progress); setSecondaryProgress(ss.secondaryProgress); } @Override protected void onAttachedToWindow() { super.onAttachedToWindow(); if (mIndeterminate) { startAnimation(); } } @Override protected void onDetachedFromWindow() { if (mIndeterminate) { stopAnimation(); } if(mRefreshProgressRunnable != null) { removeCallbacks(mRefreshProgressRunnable); } if (mAccessibilityEventSender != null) { removeCallbacks(mAccessibilityEventSender); } // This should come after stopAnimation(), otherwise an invalidate message remains in the // queue, which can prevent the entire view hierarchy from being GC'ed during a rotation super.onDetachedFromWindow(); } @Override public void onInitializeAccessibilityEvent(AccessibilityEvent event) { super.onInitializeAccessibilityEvent(event); event.setItemCount(mMax); event.setCurrentItemIndex(mProgress); } /** * Schedule a command for sending an accessibility event. * </br> * Note: A command is used to ensure that accessibility events * are sent at most one in a given time frame to save * system resources while the progress changes quickly. */ private void scheduleAccessibilityEventSender() { if (mAccessibilityEventSender == null) { mAccessibilityEventSender = new AccessibilityEventSender(); } else { removeCallbacks(mAccessibilityEventSender); } postDelayed(mAccessibilityEventSender, TIMEOUT_SEND_ACCESSIBILITY_EVENT); } /** * Command for sending an accessibility event. */ private class AccessibilityEventSender implements Runnable { public void run() { sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SELECTED); } } }
Java
package com.actionbarsherlock.internal.widget; import static android.view.View.MeasureSpec.EXACTLY; import android.content.Context; import android.content.res.TypedArray; import android.util.AttributeSet; import android.util.DisplayMetrics; import android.util.TypedValue; import android.widget.LinearLayout; import com.actionbarsherlock.R; public class FakeDialogPhoneWindow extends LinearLayout { final TypedValue mMinWidthMajor = new TypedValue(); final TypedValue mMinWidthMinor = new TypedValue(); public FakeDialogPhoneWindow(Context context, AttributeSet attrs) { super(context, attrs); TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.SherlockTheme); a.getValue(R.styleable.SherlockTheme_windowMinWidthMajor, mMinWidthMajor); a.getValue(R.styleable.SherlockTheme_windowMinWidthMinor, mMinWidthMinor); a.recycle(); } /* Stolen from PhoneWindow */ @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { final DisplayMetrics metrics = getContext().getResources().getDisplayMetrics(); final boolean isPortrait = metrics.widthPixels < metrics.heightPixels; super.onMeasure(widthMeasureSpec, heightMeasureSpec); int width = getMeasuredWidth(); boolean measure = false; widthMeasureSpec = MeasureSpec.makeMeasureSpec(width, EXACTLY); final TypedValue tv = isPortrait ? mMinWidthMinor : mMinWidthMajor; if (tv.type != TypedValue.TYPE_NULL) { final int min; if (tv.type == TypedValue.TYPE_DIMENSION) { min = (int)tv.getDimension(metrics); } else if (tv.type == TypedValue.TYPE_FRACTION) { min = (int)tv.getFraction(metrics.widthPixels, metrics.widthPixels); } else { min = 0; } if (width < min) { widthMeasureSpec = MeasureSpec.makeMeasureSpec(min, EXACTLY); measure = true; } } // TODO: Support height? if (measure) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); } } }
Java
/* * Copyright (C) 2010 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.actionbarsherlock.internal.widget; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Canvas; import android.graphics.drawable.Drawable; import android.util.AttributeSet; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import com.actionbarsherlock.R; import com.actionbarsherlock.app.ActionBar; import com.actionbarsherlock.internal.nineoldandroids.widget.NineFrameLayout; /** * This class acts as a container for the action bar view and action mode context views. * It applies special styles as needed to help handle animated transitions between them. * @hide */ public class ActionBarContainer extends NineFrameLayout { private boolean mIsTransitioning; private View mTabContainer; private ActionBarView mActionBarView; private Drawable mBackground; private Drawable mStackedBackground; private Drawable mSplitBackground; private boolean mIsSplit; private boolean mIsStacked; public ActionBarContainer(Context context) { this(context, null); } public ActionBarContainer(Context context, AttributeSet attrs) { super(context, attrs); setBackgroundDrawable(null); TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.SherlockActionBar); mBackground = a.getDrawable(R.styleable.SherlockActionBar_background); mStackedBackground = a.getDrawable( R.styleable.SherlockActionBar_backgroundStacked); if (getId() == R.id.abs__split_action_bar) { mIsSplit = true; mSplitBackground = a.getDrawable( R.styleable.SherlockActionBar_backgroundSplit); } a.recycle(); setWillNotDraw(mIsSplit ? mSplitBackground == null : mBackground == null && mStackedBackground == null); } @Override public void onFinishInflate() { super.onFinishInflate(); mActionBarView = (ActionBarView) findViewById(R.id.abs__action_bar); } public void setPrimaryBackground(Drawable bg) { mBackground = bg; invalidate(); } public void setStackedBackground(Drawable bg) { mStackedBackground = bg; invalidate(); } public void setSplitBackground(Drawable bg) { mSplitBackground = bg; invalidate(); } /** * Set the action bar into a "transitioning" state. While transitioning * the bar will block focus and touch from all of its descendants. This * prevents the user from interacting with the bar while it is animating * in or out. * * @param isTransitioning true if the bar is currently transitioning, false otherwise. */ public void setTransitioning(boolean isTransitioning) { mIsTransitioning = isTransitioning; setDescendantFocusability(isTransitioning ? FOCUS_BLOCK_DESCENDANTS : FOCUS_AFTER_DESCENDANTS); } @Override public boolean onInterceptTouchEvent(MotionEvent ev) { return mIsTransitioning || super.onInterceptTouchEvent(ev); } @Override public boolean onTouchEvent(MotionEvent ev) { super.onTouchEvent(ev); // An action bar always eats touch events. return true; } @Override public boolean onHoverEvent(MotionEvent ev) { super.onHoverEvent(ev); // An action bar always eats hover events. return true; } public void setTabContainer(ScrollingTabContainerView tabView) { if (mTabContainer != null) { removeView(mTabContainer); } mTabContainer = tabView; if (tabView != null) { addView(tabView); final ViewGroup.LayoutParams lp = tabView.getLayoutParams(); lp.width = LayoutParams.MATCH_PARENT; lp.height = LayoutParams.WRAP_CONTENT; tabView.setAllowCollapse(false); } } public View getTabContainer() { return mTabContainer; } @Override public void onDraw(Canvas canvas) { if (getWidth() == 0 || getHeight() == 0) { return; } if (mIsSplit) { if (mSplitBackground != null) mSplitBackground.draw(canvas); } else { if (mBackground != null) { mBackground.draw(canvas); } if (mStackedBackground != null && mIsStacked) { mStackedBackground.draw(canvas); } } } //This causes the animation reflection to fail on pre-HC platforms //@Override //public android.view.ActionMode startActionModeForChild(View child, android.view.ActionMode.Callback callback) { // // No starting an action mode for an action bar child! (Where would it go?) // return null; //} @Override public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); if (mActionBarView == null) return; final LayoutParams lp = (LayoutParams) mActionBarView.getLayoutParams(); final int actionBarViewHeight = mActionBarView.isCollapsed() ? 0 : mActionBarView.getMeasuredHeight() + lp.topMargin + lp.bottomMargin; if (mTabContainer != null && mTabContainer.getVisibility() != GONE) { final int mode = MeasureSpec.getMode(heightMeasureSpec); if (mode == MeasureSpec.AT_MOST) { final int maxHeight = MeasureSpec.getSize(heightMeasureSpec); setMeasuredDimension(getMeasuredWidth(), Math.min(actionBarViewHeight + mTabContainer.getMeasuredHeight(), maxHeight)); } } } @Override public void onLayout(boolean changed, int l, int t, int r, int b) { super.onLayout(changed, l, t, r, b); final boolean hasTabs = mTabContainer != null && mTabContainer.getVisibility() != GONE; if (mTabContainer != null && mTabContainer.getVisibility() != GONE) { final int containerHeight = getMeasuredHeight(); final int tabHeight = mTabContainer.getMeasuredHeight(); if ((mActionBarView.getDisplayOptions() & ActionBar.DISPLAY_SHOW_HOME) == 0) { // Not showing home, put tabs on top. final int count = getChildCount(); for (int i = 0; i < count; i++) { final View child = getChildAt(i); if (child == mTabContainer) continue; if (!mActionBarView.isCollapsed()) { child.offsetTopAndBottom(tabHeight); } } mTabContainer.layout(l, 0, r, tabHeight); } else { mTabContainer.layout(l, containerHeight - tabHeight, r, containerHeight); } } boolean needsInvalidate = false; if (mIsSplit) { if (mSplitBackground != null) { mSplitBackground.setBounds(0, 0, getMeasuredWidth(), getMeasuredHeight()); needsInvalidate = true; } } else { if (mBackground != null) { mBackground.setBounds(mActionBarView.getLeft(), mActionBarView.getTop(), mActionBarView.getRight(), mActionBarView.getBottom()); needsInvalidate = true; } if ((mIsStacked = hasTabs && mStackedBackground != null)) { mStackedBackground.setBounds(mTabContainer.getLeft(), mTabContainer.getTop(), mTabContainer.getRight(), mTabContainer.getBottom()); needsInvalidate = true; } } if (needsInvalidate) { invalidate(); } } }
Java
package com.actionbarsherlock.app; import android.content.res.Configuration; import android.os.Bundle; import android.preference.PreferenceActivity; import android.view.KeyEvent; import android.view.View; import android.view.ViewGroup.LayoutParams; import android.view.Window; import com.actionbarsherlock.ActionBarSherlock; import com.actionbarsherlock.ActionBarSherlock.OnActionModeFinishedListener; import com.actionbarsherlock.ActionBarSherlock.OnActionModeStartedListener; import com.actionbarsherlock.ActionBarSherlock.OnCreatePanelMenuListener; import com.actionbarsherlock.ActionBarSherlock.OnMenuItemSelectedListener; import com.actionbarsherlock.ActionBarSherlock.OnPreparePanelListener; import com.actionbarsherlock.view.ActionMode; import com.actionbarsherlock.view.Menu; import com.actionbarsherlock.view.MenuInflater; import com.actionbarsherlock.view.MenuItem; public abstract class SherlockPreferenceActivity extends PreferenceActivity implements OnCreatePanelMenuListener, OnPreparePanelListener, OnMenuItemSelectedListener, OnActionModeStartedListener, OnActionModeFinishedListener { private ActionBarSherlock mSherlock; protected final ActionBarSherlock getSherlock() { if (mSherlock == null) { mSherlock = ActionBarSherlock.wrap(this, ActionBarSherlock.FLAG_DELEGATE); } return mSherlock; } /////////////////////////////////////////////////////////////////////////// // Action bar and mode /////////////////////////////////////////////////////////////////////////// public ActionBar getSupportActionBar() { return getSherlock().getActionBar(); } public ActionMode startActionMode(ActionMode.Callback callback) { return getSherlock().startActionMode(callback); } @Override public void onActionModeStarted(ActionMode mode) {} @Override public void onActionModeFinished(ActionMode mode) {} /////////////////////////////////////////////////////////////////////////// // General lifecycle/callback dispatching /////////////////////////////////////////////////////////////////////////// @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); getSherlock().dispatchConfigurationChanged(newConfig); } @Override protected void onPostResume() { super.onPostResume(); getSherlock().dispatchPostResume(); } @Override protected void onPause() { getSherlock().dispatchPause(); super.onPause(); } @Override protected void onStop() { getSherlock().dispatchStop(); super.onStop(); } @Override protected void onDestroy() { getSherlock().dispatchDestroy(); super.onDestroy(); } @Override protected void onPostCreate(Bundle savedInstanceState) { getSherlock().dispatchPostCreate(savedInstanceState); super.onPostCreate(savedInstanceState); } @Override protected void onTitleChanged(CharSequence title, int color) { getSherlock().dispatchTitleChanged(title, color); super.onTitleChanged(title, color); } @Override public final boolean onMenuOpened(int featureId, android.view.Menu menu) { if (getSherlock().dispatchMenuOpened(featureId, menu)) { return true; } return super.onMenuOpened(featureId, menu); } @Override public void onPanelClosed(int featureId, android.view.Menu menu) { getSherlock().dispatchPanelClosed(featureId, menu); super.onPanelClosed(featureId, menu); } @Override public boolean dispatchKeyEvent(KeyEvent event) { if (getSherlock().dispatchKeyEvent(event)) { return true; } return super.dispatchKeyEvent(event); } /////////////////////////////////////////////////////////////////////////// // Native menu handling /////////////////////////////////////////////////////////////////////////// public MenuInflater getSupportMenuInflater() { return getSherlock().getMenuInflater(); } public void invalidateOptionsMenu() { getSherlock().dispatchInvalidateOptionsMenu(); } public void supportInvalidateOptionsMenu() { invalidateOptionsMenu(); } @Override public final boolean onCreateOptionsMenu(android.view.Menu menu) { return getSherlock().dispatchCreateOptionsMenu(menu); } @Override public final boolean onPrepareOptionsMenu(android.view.Menu menu) { return getSherlock().dispatchPrepareOptionsMenu(menu); } @Override public final boolean onOptionsItemSelected(android.view.MenuItem item) { return getSherlock().dispatchOptionsItemSelected(item); } @Override public void openOptionsMenu() { if (!getSherlock().dispatchOpenOptionsMenu()) { super.openOptionsMenu(); } } @Override public void closeOptionsMenu() { if (!getSherlock().dispatchCloseOptionsMenu()) { super.closeOptionsMenu(); } } /////////////////////////////////////////////////////////////////////////// // Sherlock menu handling /////////////////////////////////////////////////////////////////////////// @Override public boolean onCreatePanelMenu(int featureId, Menu menu) { if (featureId == Window.FEATURE_OPTIONS_PANEL) { return onCreateOptionsMenu(menu); } return false; } public boolean onCreateOptionsMenu(Menu menu) { return true; } @Override public boolean onPreparePanel(int featureId, View view, Menu menu) { if (featureId == Window.FEATURE_OPTIONS_PANEL) { return onPrepareOptionsMenu(menu); } return false; } public boolean onPrepareOptionsMenu(Menu menu) { return true; } @Override public boolean onMenuItemSelected(int featureId, MenuItem item) { if (featureId == Window.FEATURE_OPTIONS_PANEL) { return onOptionsItemSelected(item); } return false; } public boolean onOptionsItemSelected(MenuItem item) { return false; } /////////////////////////////////////////////////////////////////////////// // Content /////////////////////////////////////////////////////////////////////////// @Override public void addContentView(View view, LayoutParams params) { getSherlock().addContentView(view, params); } @Override public void setContentView(int layoutResId) { getSherlock().setContentView(layoutResId); } @Override public void setContentView(View view, LayoutParams params) { getSherlock().setContentView(view, params); } @Override public void setContentView(View view) { getSherlock().setContentView(view); } public void requestWindowFeature(long featureId) { getSherlock().requestFeature((int)featureId); } /////////////////////////////////////////////////////////////////////////// // Progress Indication /////////////////////////////////////////////////////////////////////////// public void setSupportProgress(int progress) { getSherlock().setProgress(progress); } public void setSupportProgressBarIndeterminate(boolean indeterminate) { getSherlock().setProgressBarIndeterminate(indeterminate); } public void setSupportProgressBarIndeterminateVisibility(boolean visible) { getSherlock().setProgressBarIndeterminateVisibility(visible); } public void setSupportProgressBarVisibility(boolean visible) { getSherlock().setProgressBarVisibility(visible); } public void setSupportSecondaryProgress(int secondaryProgress) { getSherlock().setSecondaryProgress(secondaryProgress); } }
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.app; import android.content.Context; import android.graphics.drawable.Drawable; import android.support.v4.app.FragmentTransaction; import android.util.AttributeSet; import android.view.Gravity; import android.view.View; import android.view.ViewDebug; import android.view.ViewGroup; import android.view.ViewGroup.MarginLayoutParams; import android.widget.SpinnerAdapter; /** * A window feature at the top of the activity that may display the activity title, navigation * modes, and other interactive items. * <p>Beginning with Android 3.0 (API level 11), the action bar appears at the top of an * activity's window when the activity uses the system's {@link * android.R.style#Theme_Holo Holo} theme (or one of its descendant themes), which is the default. * You may otherwise add the action bar by calling {@link * android.view.Window#requestFeature requestFeature(FEATURE_ACTION_BAR)} or by declaring it in a * custom theme with the {@link android.R.styleable#Theme_windowActionBar windowActionBar} property. * <p>By default, the action bar shows the application icon on * the left, followed by the activity title. If your activity has an options menu, you can make * select items accessible directly from the action bar as "action items". You can also * modify various characteristics of the action bar or remove it completely.</p> * <p>From your activity, you can retrieve an instance of {@link ActionBar} by calling {@link * android.app.Activity#getActionBar getActionBar()}.</p> * <p>In some cases, the action bar may be overlayed by another bar that enables contextual actions, * using an {@link android.view.ActionMode}. For example, when the user selects one or more items in * your activity, you can enable an action mode that offers actions specific to the selected * items, with a UI that temporarily replaces the action bar. Although the UI may occupy the * same space, the {@link android.view.ActionMode} APIs are distinct and independent from those for * {@link ActionBar}. * <div class="special reference"> * <h3>Developer Guides</h3> * <p>For information about how to use the action bar, including how to add action items, navigation * modes and more, read the <a href="{@docRoot}guide/topics/ui/actionbar.html">Action * Bar</a> developer guide.</p> * </div> */ public abstract class ActionBar { /** * Standard navigation mode. Consists of either a logo or icon * and title text with an optional subtitle. Clicking any of these elements * will dispatch onOptionsItemSelected to the host Activity with * a MenuItem with item ID android.R.id.home. */ public static final int NAVIGATION_MODE_STANDARD = android.app.ActionBar.NAVIGATION_MODE_STANDARD; /** * List navigation mode. Instead of static title text this mode * presents a list menu for navigation within the activity. * e.g. this might be presented to the user as a dropdown list. */ public static final int NAVIGATION_MODE_LIST = android.app.ActionBar.NAVIGATION_MODE_LIST; /** * Tab navigation mode. Instead of static title text this mode * presents a series of tabs for navigation within the activity. */ public static final int NAVIGATION_MODE_TABS = android.app.ActionBar.NAVIGATION_MODE_TABS; /** * Use logo instead of icon if available. This flag will cause appropriate * navigation modes to use a wider logo in place of the standard icon. * * @see #setDisplayOptions(int) * @see #setDisplayOptions(int, int) */ public static final int DISPLAY_USE_LOGO = android.app.ActionBar.DISPLAY_USE_LOGO; /** * Show 'home' elements in this action bar, leaving more space for other * navigation elements. This includes logo and icon. * * @see #setDisplayOptions(int) * @see #setDisplayOptions(int, int) */ public static final int DISPLAY_SHOW_HOME = android.app.ActionBar.DISPLAY_SHOW_HOME; /** * Display the 'home' element such that it appears as an 'up' affordance. * e.g. show an arrow to the left indicating the action that will be taken. * * Set this flag if selecting the 'home' button in the action bar to return * up by a single level in your UI rather than back to the top level or front page. * * <p>Setting this option will implicitly enable interaction with the home/up * button. See {@link #setHomeButtonEnabled(boolean)}. * * @see #setDisplayOptions(int) * @see #setDisplayOptions(int, int) */ public static final int DISPLAY_HOME_AS_UP = android.app.ActionBar.DISPLAY_HOME_AS_UP; /** * Show the activity title and subtitle, if present. * * @see #setTitle(CharSequence) * @see #setTitle(int) * @see #setSubtitle(CharSequence) * @see #setSubtitle(int) * @see #setDisplayOptions(int) * @see #setDisplayOptions(int, int) */ public static final int DISPLAY_SHOW_TITLE = android.app.ActionBar.DISPLAY_SHOW_TITLE; /** * Show the custom view if one has been set. * @see #setCustomView(View) * @see #setDisplayOptions(int) * @see #setDisplayOptions(int, int) */ public static final int DISPLAY_SHOW_CUSTOM = android.app.ActionBar.DISPLAY_SHOW_CUSTOM; /** * Set the action bar into custom navigation mode, supplying a view * for custom navigation. * * Custom navigation views appear between the application icon and * any action buttons and may use any space available there. Common * use cases for custom navigation views might include an auto-suggesting * address bar for a browser or other navigation mechanisms that do not * translate well to provided navigation modes. * * @param view Custom navigation view to place in the ActionBar. */ public abstract void setCustomView(View view); /** * Set the action bar into custom navigation mode, supplying a view * for custom navigation. * * <p>Custom navigation views appear between the application icon and * any action buttons and may use any space available there. Common * use cases for custom navigation views might include an auto-suggesting * address bar for a browser or other navigation mechanisms that do not * translate well to provided navigation modes.</p> * * <p>The display option {@link #DISPLAY_SHOW_CUSTOM} must be set for * the custom view to be displayed.</p> * * @param view Custom navigation view to place in the ActionBar. * @param layoutParams How this custom view should layout in the bar. * * @see #setDisplayOptions(int, int) */ public abstract void setCustomView(View view, LayoutParams layoutParams); /** * Set the action bar into custom navigation mode, supplying a view * for custom navigation. * * <p>Custom navigation views appear between the application icon and * any action buttons and may use any space available there. Common * use cases for custom navigation views might include an auto-suggesting * address bar for a browser or other navigation mechanisms that do not * translate well to provided navigation modes.</p> * * <p>The display option {@link #DISPLAY_SHOW_CUSTOM} must be set for * the custom view to be displayed.</p> * * @param resId Resource ID of a layout to inflate into the ActionBar. * * @see #setDisplayOptions(int, int) */ public abstract void setCustomView(int resId); /** * Set the icon to display in the 'home' section of the action bar. * The action bar will use an icon specified by its style or the * activity icon by default. * * Whether the home section shows an icon or logo is controlled * by the display option {@link #DISPLAY_USE_LOGO}. * * @param resId Resource ID of a drawable to show as an icon. * * @see #setDisplayUseLogoEnabled(boolean) * @see #setDisplayShowHomeEnabled(boolean) */ public abstract void setIcon(int resId); /** * Set the icon to display in the 'home' section of the action bar. * The action bar will use an icon specified by its style or the * activity icon by default. * * Whether the home section shows an icon or logo is controlled * by the display option {@link #DISPLAY_USE_LOGO}. * * @param icon Drawable to show as an icon. * * @see #setDisplayUseLogoEnabled(boolean) * @see #setDisplayShowHomeEnabled(boolean) */ public abstract void setIcon(Drawable icon); /** * Set the logo to display in the 'home' section of the action bar. * The action bar will use a logo specified by its style or the * activity logo by default. * * Whether the home section shows an icon or logo is controlled * by the display option {@link #DISPLAY_USE_LOGO}. * * @param resId Resource ID of a drawable to show as a logo. * * @see #setDisplayUseLogoEnabled(boolean) * @see #setDisplayShowHomeEnabled(boolean) */ public abstract void setLogo(int resId); /** * Set the logo to display in the 'home' section of the action bar. * The action bar will use a logo specified by its style or the * activity logo by default. * * Whether the home section shows an icon or logo is controlled * by the display option {@link #DISPLAY_USE_LOGO}. * * @param logo Drawable to show as a logo. * * @see #setDisplayUseLogoEnabled(boolean) * @see #setDisplayShowHomeEnabled(boolean) */ public abstract void setLogo(Drawable logo); /** * Set the adapter and navigation callback for list navigation mode. * * The supplied adapter will provide views for the expanded list as well as * the currently selected item. (These may be displayed differently.) * * The supplied OnNavigationListener will alert the application when the user * changes the current list selection. * * @param adapter An adapter that will provide views both to display * the current navigation selection and populate views * within the dropdown navigation menu. * @param callback An OnNavigationListener that will receive events when the user * selects a navigation item. */ public abstract void setListNavigationCallbacks(SpinnerAdapter adapter, OnNavigationListener callback); /** * Set the selected navigation item in list or tabbed navigation modes. * * @param position Position of the item to select. */ public abstract void setSelectedNavigationItem(int position); /** * Get the position of the selected navigation item in list or tabbed navigation modes. * * @return Position of the selected item. */ public abstract int getSelectedNavigationIndex(); /** * Get the number of navigation items present in the current navigation mode. * * @return Number of navigation items. */ public abstract int getNavigationItemCount(); /** * Set the action bar's title. This will only be displayed if * {@link #DISPLAY_SHOW_TITLE} is set. * * @param title Title to set * * @see #setTitle(int) * @see #setDisplayOptions(int, int) */ public abstract void setTitle(CharSequence title); /** * Set the action bar's title. This will only be displayed if * {@link #DISPLAY_SHOW_TITLE} is set. * * @param resId Resource ID of title string to set * * @see #setTitle(CharSequence) * @see #setDisplayOptions(int, int) */ public abstract void setTitle(int resId); /** * Set the action bar's subtitle. This will only be displayed if * {@link #DISPLAY_SHOW_TITLE} is set. Set to null to disable the * subtitle entirely. * * @param subtitle Subtitle to set * * @see #setSubtitle(int) * @see #setDisplayOptions(int, int) */ public abstract void setSubtitle(CharSequence subtitle); /** * Set the action bar's subtitle. This will only be displayed if * {@link #DISPLAY_SHOW_TITLE} is set. * * @param resId Resource ID of subtitle string to set * * @see #setSubtitle(CharSequence) * @see #setDisplayOptions(int, int) */ public abstract void setSubtitle(int resId); /** * Set display options. This changes all display option bits at once. To change * a limited subset of display options, see {@link #setDisplayOptions(int, int)}. * * @param options A combination of the bits defined by the DISPLAY_ constants * defined in ActionBar. */ public abstract void setDisplayOptions(int options); /** * Set selected display options. Only the options specified by mask will be changed. * To change all display option bits at once, see {@link #setDisplayOptions(int)}. * * <p>Example: setDisplayOptions(0, DISPLAY_SHOW_HOME) will disable the * {@link #DISPLAY_SHOW_HOME} option. * setDisplayOptions(DISPLAY_SHOW_HOME, DISPLAY_SHOW_HOME | DISPLAY_USE_LOGO) * will enable {@link #DISPLAY_SHOW_HOME} and disable {@link #DISPLAY_USE_LOGO}. * * @param options A combination of the bits defined by the DISPLAY_ constants * defined in ActionBar. * @param mask A bit mask declaring which display options should be changed. */ public abstract void setDisplayOptions(int options, int mask); /** * Set whether to display the activity logo rather than the activity icon. * A logo is often a wider, more detailed image. * * <p>To set several display options at once, see the setDisplayOptions methods. * * @param useLogo true to use the activity logo, false to use the activity icon. * * @see #setDisplayOptions(int) * @see #setDisplayOptions(int, int) */ public abstract void setDisplayUseLogoEnabled(boolean useLogo); /** * Set whether to include the application home affordance in the action bar. * Home is presented as either an activity icon or logo. * * <p>To set several display options at once, see the setDisplayOptions methods. * * @param showHome true to show home, false otherwise. * * @see #setDisplayOptions(int) * @see #setDisplayOptions(int, int) */ public abstract void setDisplayShowHomeEnabled(boolean showHome); /** * Set whether home should be displayed as an "up" affordance. * Set this to true if selecting "home" returns up by a single level in your UI * rather than back to the top level or front page. * * <p>To set several display options at once, see the setDisplayOptions methods. * * @param showHomeAsUp true to show the user that selecting home will return one * level up rather than to the top level of the app. * * @see #setDisplayOptions(int) * @see #setDisplayOptions(int, int) */ public abstract void setDisplayHomeAsUpEnabled(boolean showHomeAsUp); /** * Set whether an activity title/subtitle should be displayed. * * <p>To set several display options at once, see the setDisplayOptions methods. * * @param showTitle true to display a title/subtitle if present. * * @see #setDisplayOptions(int) * @see #setDisplayOptions(int, int) */ public abstract void setDisplayShowTitleEnabled(boolean showTitle); /** * Set whether a custom view should be displayed, if set. * * <p>To set several display options at once, see the setDisplayOptions methods. * * @param showCustom true if the currently set custom view should be displayed, false otherwise. * * @see #setDisplayOptions(int) * @see #setDisplayOptions(int, int) */ public abstract void setDisplayShowCustomEnabled(boolean showCustom); /** * Set the ActionBar's background. This will be used for the primary * action bar. * * @param d Background drawable * @see #setStackedBackgroundDrawable(Drawable) * @see #setSplitBackgroundDrawable(Drawable) */ public abstract void setBackgroundDrawable(Drawable d); /** * Set the ActionBar's stacked background. This will appear * in the second row/stacked bar on some devices and configurations. * * @param d Background drawable for the stacked row */ public void setStackedBackgroundDrawable(Drawable d) { } /** * Set the ActionBar's split background. This will appear in * the split action bar containing menu-provided action buttons * on some devices and configurations. * <p>You can enable split action bar with {@link android.R.attr#uiOptions} * * @param d Background drawable for the split bar */ public void setSplitBackgroundDrawable(Drawable d) { } /** * @return The current custom view. */ public abstract View getCustomView(); /** * Returns the current ActionBar title in standard mode. * Returns null if {@link #getNavigationMode()} would not return * {@link #NAVIGATION_MODE_STANDARD}. * * @return The current ActionBar title or null. */ public abstract CharSequence getTitle(); /** * Returns the current ActionBar subtitle in standard mode. * Returns null if {@link #getNavigationMode()} would not return * {@link #NAVIGATION_MODE_STANDARD}. * * @return The current ActionBar subtitle or null. */ public abstract CharSequence getSubtitle(); /** * Returns the current navigation mode. The result will be one of: * <ul> * <li>{@link #NAVIGATION_MODE_STANDARD}</li> * <li>{@link #NAVIGATION_MODE_LIST}</li> * <li>{@link #NAVIGATION_MODE_TABS}</li> * </ul> * * @return The current navigation mode. */ public abstract int getNavigationMode(); /** * Set the current navigation mode. * * @param mode The new mode to set. * @see #NAVIGATION_MODE_STANDARD * @see #NAVIGATION_MODE_LIST * @see #NAVIGATION_MODE_TABS */ public abstract void setNavigationMode(int mode); /** * @return The current set of display options. */ public abstract int getDisplayOptions(); /** * Create and return a new {@link Tab}. * This tab will not be included in the action bar until it is added. * * <p>Very often tabs will be used to switch between {@link Fragment} * objects. Here is a typical implementation of such tabs:</p> * * {@sample development/samples/ApiDemos/src/com/example/android/apis/app/FragmentTabs.java * complete} * * @return A new Tab * * @see #addTab(Tab) */ public abstract Tab newTab(); /** * Add a tab for use in tabbed navigation mode. The tab will be added at the end of the list. * If this is the first tab to be added it will become the selected tab. * * @param tab Tab to add */ public abstract void addTab(Tab tab); /** * Add a tab for use in tabbed navigation mode. The tab will be added at the end of the list. * * @param tab Tab to add * @param setSelected True if the added tab should become the selected tab. */ public abstract void addTab(Tab tab, boolean setSelected); /** * Add a tab for use in tabbed navigation mode. The tab will be inserted at * <code>position</code>. If this is the first tab to be added it will become * the selected tab. * * @param tab The tab to add * @param position The new position of the tab */ public abstract void addTab(Tab tab, int position); /** * Add a tab for use in tabbed navigation mode. The tab will be insterted at * <code>position</code>. * * @param tab The tab to add * @param position The new position of the tab * @param setSelected True if the added tab should become the selected tab. */ public abstract void addTab(Tab tab, int position, boolean setSelected); /** * Remove a tab from the action bar. If the removed tab was selected it will be deselected * and another tab will be selected if present. * * @param tab The tab to remove */ public abstract void removeTab(Tab tab); /** * Remove a tab from the action bar. If the removed tab was selected it will be deselected * and another tab will be selected if present. * * @param position Position of the tab to remove */ public abstract void removeTabAt(int position); /** * Remove all tabs from the action bar and deselect the current tab. */ public abstract void removeAllTabs(); /** * Select the specified tab. If it is not a child of this action bar it will be added. * * <p>Note: If you want to select by index, use {@link #setSelectedNavigationItem(int)}.</p> * * @param tab Tab to select */ public abstract void selectTab(Tab tab); /** * Returns the currently selected tab if in tabbed navigation mode and there is at least * one tab present. * * @return The currently selected tab or null */ public abstract Tab getSelectedTab(); /** * Returns the tab at the specified index. * * @param index Index value in the range 0-get * @return */ public abstract Tab getTabAt(int index); /** * Returns the number of tabs currently registered with the action bar. * @return Tab count */ public abstract int getTabCount(); /** * Retrieve the current height of the ActionBar. * * @return The ActionBar's height */ public abstract int getHeight(); /** * Show the ActionBar if it is not currently showing. * If the window hosting the ActionBar does not have the feature * {@link Window#FEATURE_ACTION_BAR_OVERLAY} it will resize application * content to fit the new space available. */ public abstract void show(); /** * Hide the ActionBar if it is currently showing. * If the window hosting the ActionBar does not have the feature * {@link Window#FEATURE_ACTION_BAR_OVERLAY} it will resize application * content to fit the new space available. */ public abstract void hide(); /** * @return <code>true</code> if the ActionBar is showing, <code>false</code> otherwise. */ public abstract boolean isShowing(); /** * Add a listener that will respond to menu visibility change events. * * @param listener The new listener to add */ public abstract void addOnMenuVisibilityListener(OnMenuVisibilityListener listener); /** * Remove a menu visibility listener. This listener will no longer receive menu * visibility change events. * * @param listener A listener to remove that was previously added */ public abstract void removeOnMenuVisibilityListener(OnMenuVisibilityListener listener); /** * Enable or disable the "home" button in the corner of the action bar. (Note that this * is the application home/up affordance on the action bar, not the systemwide home * button.) * * <p>This defaults to true for packages targeting &lt; API 14. For packages targeting * API 14 or greater, the application should call this method to enable interaction * with the home/up affordance. * * <p>Setting the {@link #DISPLAY_HOME_AS_UP} display option will automatically enable * the home button. * * @param enabled true to enable the home button, false to disable the home button. */ public void setHomeButtonEnabled(boolean enabled) { } /** * Returns a {@link Context} with an appropriate theme for creating views that * will appear in the action bar. If you are inflating or instantiating custom views * that will appear in an action bar, you should use the Context returned by this method. * (This includes adapters used for list navigation mode.) * This will ensure that views contrast properly against the action bar. * * @return A themed Context for creating views */ public Context getThemedContext() { return null; } /** * Listener interface for ActionBar navigation events. */ public interface OnNavigationListener { /** * This method is called whenever a navigation item in your action bar * is selected. * * @param itemPosition Position of the item clicked. * @param itemId ID of the item clicked. * @return True if the event was handled, false otherwise. */ public boolean onNavigationItemSelected(int itemPosition, long itemId); } /** * Listener for receiving events when action bar menus are shown or hidden. */ public interface OnMenuVisibilityListener { /** * Called when an action bar menu is shown or hidden. Applications may want to use * this to tune auto-hiding behavior for the action bar or pause/resume video playback, * gameplay, or other activity within the main content area. * * @param isVisible True if an action bar menu is now visible, false if no action bar * menus are visible. */ public void onMenuVisibilityChanged(boolean isVisible); } /** * A tab in the action bar. * * <p>Tabs manage the hiding and showing of {@link Fragment}s. */ public static abstract class Tab { /** * An invalid position for a tab. * * @see #getPosition() */ public static final int INVALID_POSITION = -1; /** * Return the current position of this tab in the action bar. * * @return Current position, or {@link #INVALID_POSITION} if this tab is not currently in * the action bar. */ public abstract int getPosition(); /** * Return the icon associated with this tab. * * @return The tab's icon */ public abstract Drawable getIcon(); /** * Return the text of this tab. * * @return The tab's text */ public abstract CharSequence getText(); /** * Set the icon displayed on this tab. * * @param icon The drawable to use as an icon * @return The current instance for call chaining */ public abstract Tab setIcon(Drawable icon); /** * Set the icon displayed on this tab. * * @param resId Resource ID referring to the drawable to use as an icon * @return The current instance for call chaining */ public abstract Tab setIcon(int resId); /** * Set the text displayed on this tab. Text may be truncated if there is not * room to display the entire string. * * @param text The text to display * @return The current instance for call chaining */ public abstract Tab setText(CharSequence text); /** * Set the text displayed on this tab. Text may be truncated if there is not * room to display the entire string. * * @param resId A resource ID referring to the text that should be displayed * @return The current instance for call chaining */ public abstract Tab setText(int resId); /** * Set a custom view to be used for this tab. This overrides values set by * {@link #setText(CharSequence)} and {@link #setIcon(Drawable)}. * * @param view Custom view to be used as a tab. * @return The current instance for call chaining */ public abstract Tab setCustomView(View view); /** * Set a custom view to be used for this tab. This overrides values set by * {@link #setText(CharSequence)} and {@link #setIcon(Drawable)}. * * @param layoutResId A layout resource to inflate and use as a custom tab view * @return The current instance for call chaining */ public abstract Tab setCustomView(int layoutResId); /** * Retrieve a previously set custom view for this tab. * * @return The custom view set by {@link #setCustomView(View)}. */ public abstract View getCustomView(); /** * Give this Tab an arbitrary object to hold for later use. * * @param obj Object to store * @return The current instance for call chaining */ public abstract Tab setTag(Object obj); /** * @return This Tab's tag object. */ public abstract Object getTag(); /** * Set the {@link TabListener} that will handle switching to and from this tab. * All tabs must have a TabListener set before being added to the ActionBar. * * @param listener Listener to handle tab selection events * @return The current instance for call chaining */ public abstract Tab setTabListener(TabListener listener); /** * Select this tab. Only valid if the tab has been added to the action bar. */ public abstract void select(); /** * Set a description of this tab's content for use in accessibility support. * If no content description is provided the title will be used. * * @param resId A resource ID referring to the description text * @return The current instance for call chaining * @see #setContentDescription(CharSequence) * @see #getContentDescription() */ public abstract Tab setContentDescription(int resId); /** * Set a description of this tab's content for use in accessibility support. * If no content description is provided the title will be used. * * @param contentDesc Description of this tab's content * @return The current instance for call chaining * @see #setContentDescription(int) * @see #getContentDescription() */ public abstract Tab setContentDescription(CharSequence contentDesc); /** * Gets a brief description of this tab's content for use in accessibility support. * * @return Description of this tab's content * @see #setContentDescription(CharSequence) * @see #setContentDescription(int) */ public abstract CharSequence getContentDescription(); } /** * Callback interface invoked when a tab is focused, unfocused, added, or removed. */ public interface TabListener { /** * Called when a tab enters the selected state. * * @param tab The tab that was selected * @param ft A {@link FragmentTransaction} for queuing fragment operations to execute * during a tab switch. The previous tab's unselect and this tab's select will be * executed in a single transaction. This FragmentTransaction does not support * being added to the back stack. */ public void onTabSelected(Tab tab, FragmentTransaction ft); /** * Called when a tab exits the selected state. * * @param tab The tab that was unselected * @param ft A {@link FragmentTransaction} for queuing fragment operations to execute * during a tab switch. This tab's unselect and the newly selected tab's select * will be executed in a single transaction. This FragmentTransaction does not * support being added to the back stack. */ public void onTabUnselected(Tab tab, FragmentTransaction ft); /** * Called when a tab that is already selected is chosen again by the user. * Some applications may use this action to return to the top level of a category. * * @param tab The tab that was reselected. * @param ft A {@link FragmentTransaction} for queuing fragment operations to execute * once this method returns. This FragmentTransaction does not support * being added to the back stack. */ public void onTabReselected(Tab tab, FragmentTransaction ft); } /** * Per-child layout information associated with action bar custom views. * * @attr ref android.R.styleable#ActionBar_LayoutParams_layout_gravity */ public static class LayoutParams extends MarginLayoutParams { /** * Gravity for the view associated with these LayoutParams. * * @see android.view.Gravity */ @ViewDebug.ExportedProperty(mapping = { @ViewDebug.IntToString(from = -1, to = "NONE"), @ViewDebug.IntToString(from = Gravity.NO_GRAVITY, to = "NONE"), @ViewDebug.IntToString(from = Gravity.TOP, to = "TOP"), @ViewDebug.IntToString(from = Gravity.BOTTOM, to = "BOTTOM"), @ViewDebug.IntToString(from = Gravity.LEFT, to = "LEFT"), @ViewDebug.IntToString(from = Gravity.RIGHT, to = "RIGHT"), @ViewDebug.IntToString(from = Gravity.CENTER_VERTICAL, to = "CENTER_VERTICAL"), @ViewDebug.IntToString(from = Gravity.FILL_VERTICAL, to = "FILL_VERTICAL"), @ViewDebug.IntToString(from = Gravity.CENTER_HORIZONTAL, to = "CENTER_HORIZONTAL"), @ViewDebug.IntToString(from = Gravity.FILL_HORIZONTAL, to = "FILL_HORIZONTAL"), @ViewDebug.IntToString(from = Gravity.CENTER, to = "CENTER"), @ViewDebug.IntToString(from = Gravity.FILL, to = "FILL") }) public int gravity = -1; public LayoutParams(Context c, AttributeSet attrs) { super(c, attrs); } public LayoutParams(int width, int height) { super(width, height); this.gravity = Gravity.CENTER_VERTICAL | Gravity.LEFT; } public LayoutParams(int width, int height, int gravity) { super(width, height); this.gravity = gravity; } public LayoutParams(int gravity) { this(WRAP_CONTENT, FILL_PARENT, gravity); } public LayoutParams(LayoutParams source) { super(source); this.gravity = source.gravity; } public LayoutParams(ViewGroup.LayoutParams source) { super(source); } } }
Java
package com.actionbarsherlock.app; import android.content.res.Configuration; import android.os.Bundle; import android.support.v4.app._ActionBarSherlockTrojanHorse; import android.util.Log; import android.view.KeyEvent; import android.view.View; import android.view.ViewGroup.LayoutParams; import android.view.Window; import com.actionbarsherlock.ActionBarSherlock; import com.actionbarsherlock.view.ActionMode; import com.actionbarsherlock.view.Menu; import com.actionbarsherlock.view.MenuInflater; import com.actionbarsherlock.view.MenuItem; import static com.actionbarsherlock.ActionBarSherlock.OnActionModeFinishedListener; import static com.actionbarsherlock.ActionBarSherlock.OnActionModeStartedListener; /** @see {@link _ActionBarSherlockTrojanHorse} */ public class SherlockFragmentActivity extends _ActionBarSherlockTrojanHorse implements OnActionModeStartedListener, OnActionModeFinishedListener { private static final boolean DEBUG = false; private static final String TAG = "SherlockFragmentActivity"; private ActionBarSherlock mSherlock; private boolean mIgnoreNativeCreate = false; private boolean mIgnoreNativePrepare = false; private boolean mIgnoreNativeSelected = false; protected final ActionBarSherlock getSherlock() { if (mSherlock == null) { mSherlock = ActionBarSherlock.wrap(this, ActionBarSherlock.FLAG_DELEGATE); } return mSherlock; } /////////////////////////////////////////////////////////////////////////// // Action bar and mode /////////////////////////////////////////////////////////////////////////// public ActionBar getSupportActionBar() { return getSherlock().getActionBar(); } public ActionMode startActionMode(ActionMode.Callback callback) { return getSherlock().startActionMode(callback); } @Override public void onActionModeStarted(ActionMode mode) {} @Override public void onActionModeFinished(ActionMode mode) {} /////////////////////////////////////////////////////////////////////////// // General lifecycle/callback dispatching /////////////////////////////////////////////////////////////////////////// @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); getSherlock().dispatchConfigurationChanged(newConfig); } @Override protected void onPostResume() { super.onPostResume(); getSherlock().dispatchPostResume(); } @Override protected void onPause() { getSherlock().dispatchPause(); super.onPause(); } @Override protected void onStop() { getSherlock().dispatchStop(); super.onStop(); } @Override protected void onDestroy() { getSherlock().dispatchDestroy(); super.onDestroy(); } @Override protected void onPostCreate(Bundle savedInstanceState) { getSherlock().dispatchPostCreate(savedInstanceState); super.onPostCreate(savedInstanceState); } @Override protected void onTitleChanged(CharSequence title, int color) { getSherlock().dispatchTitleChanged(title, color); super.onTitleChanged(title, color); } @Override public final boolean onMenuOpened(int featureId, android.view.Menu menu) { if (getSherlock().dispatchMenuOpened(featureId, menu)) { return true; } return super.onMenuOpened(featureId, menu); } @Override public void onPanelClosed(int featureId, android.view.Menu menu) { getSherlock().dispatchPanelClosed(featureId, menu); super.onPanelClosed(featureId, menu); } @Override public boolean dispatchKeyEvent(KeyEvent event) { if (getSherlock().dispatchKeyEvent(event)) { return true; } return super.dispatchKeyEvent(event); } /////////////////////////////////////////////////////////////////////////// // Native menu handling /////////////////////////////////////////////////////////////////////////// public MenuInflater getSupportMenuInflater() { if (DEBUG) Log.d(TAG, "[getSupportMenuInflater]"); return getSherlock().getMenuInflater(); } public void invalidateOptionsMenu() { if (DEBUG) Log.d(TAG, "[invalidateOptionsMenu]"); getSherlock().dispatchInvalidateOptionsMenu(); } public void supportInvalidateOptionsMenu() { if (DEBUG) Log.d(TAG, "[supportInvalidateOptionsMenu]"); invalidateOptionsMenu(); } @Override public final boolean onCreatePanelMenu(int featureId, android.view.Menu menu) { if (DEBUG) Log.d(TAG, "[onCreatePanelMenu] featureId: " + featureId + ", menu: " + menu); if (featureId == Window.FEATURE_OPTIONS_PANEL && !mIgnoreNativeCreate) { mIgnoreNativeCreate = true; boolean result = getSherlock().dispatchCreateOptionsMenu(menu); mIgnoreNativeCreate = false; if (DEBUG) Log.d(TAG, "[onCreatePanelMenu] returning " + result); return result; } return super.onCreatePanelMenu(featureId, menu); } @Override public final boolean onCreateOptionsMenu(android.view.Menu menu) { return true; } @Override public final boolean onPreparePanel(int featureId, View view, android.view.Menu menu) { if (DEBUG) Log.d(TAG, "[onPreparePanel] featureId: " + featureId + ", view: " + view + ", menu: " + menu); if (featureId == Window.FEATURE_OPTIONS_PANEL && !mIgnoreNativePrepare) { mIgnoreNativePrepare = true; boolean result = getSherlock().dispatchPrepareOptionsMenu(menu); mIgnoreNativePrepare = false; if (DEBUG) Log.d(TAG, "[onPreparePanel] returning " + result); return result; } return super.onPreparePanel(featureId, view, menu); } @Override public final boolean onPrepareOptionsMenu(android.view.Menu menu) { return true; } @Override public final boolean onMenuItemSelected(int featureId, android.view.MenuItem item) { if (DEBUG) Log.d(TAG, "[onMenuItemSelected] featureId: " + featureId + ", item: " + item); if (featureId == Window.FEATURE_OPTIONS_PANEL && !mIgnoreNativeSelected) { mIgnoreNativeSelected = true; boolean result = getSherlock().dispatchOptionsItemSelected(item); mIgnoreNativeSelected = false; if (DEBUG) Log.d(TAG, "[onMenuItemSelected] returning " + result); return result; } return super.onMenuItemSelected(featureId, item); } @Override public final boolean onOptionsItemSelected(android.view.MenuItem item) { return false; } @Override public void openOptionsMenu() { if (!getSherlock().dispatchOpenOptionsMenu()) { super.openOptionsMenu(); } } @Override public void closeOptionsMenu() { if (!getSherlock().dispatchCloseOptionsMenu()) { super.closeOptionsMenu(); } } /////////////////////////////////////////////////////////////////////////// // Sherlock menu handling /////////////////////////////////////////////////////////////////////////// public boolean onCreateOptionsMenu(Menu menu) { return true; } public boolean onPrepareOptionsMenu(Menu menu) { return true; } public boolean onOptionsItemSelected(MenuItem item) { return false; } /////////////////////////////////////////////////////////////////////////// // Content /////////////////////////////////////////////////////////////////////////// @Override public void addContentView(View view, LayoutParams params) { getSherlock().addContentView(view, params); } @Override public void setContentView(int layoutResId) { getSherlock().setContentView(layoutResId); } @Override public void setContentView(View view, LayoutParams params) { getSherlock().setContentView(view, params); } @Override public void setContentView(View view) { getSherlock().setContentView(view); } public void requestWindowFeature(long featureId) { getSherlock().requestFeature((int)featureId); } /////////////////////////////////////////////////////////////////////////// // Progress Indication /////////////////////////////////////////////////////////////////////////// public void setSupportProgress(int progress) { getSherlock().setProgress(progress); } public void setSupportProgressBarIndeterminate(boolean indeterminate) { getSherlock().setProgressBarIndeterminate(indeterminate); } public void setSupportProgressBarIndeterminateVisibility(boolean visible) { getSherlock().setProgressBarIndeterminateVisibility(visible); } public void setSupportProgressBarVisibility(boolean visible) { getSherlock().setProgressBarVisibility(visible); } public void setSupportSecondaryProgress(int secondaryProgress) { getSherlock().setSecondaryProgress(secondaryProgress); } }
Java
package com.actionbarsherlock.app; import android.app.Activity; import android.support.v4.app.ListFragment; import com.actionbarsherlock.internal.view.menu.MenuItemWrapper; import com.actionbarsherlock.internal.view.menu.MenuWrapper; import com.actionbarsherlock.view.Menu; import com.actionbarsherlock.view.MenuInflater; import com.actionbarsherlock.view.MenuItem; import static com.actionbarsherlock.app.SherlockFragmentActivity.OnCreateOptionsMenuListener; import static com.actionbarsherlock.app.SherlockFragmentActivity.OnOptionsItemSelectedListener; import static com.actionbarsherlock.app.SherlockFragmentActivity.OnPrepareOptionsMenuListener; public class SherlockListFragment extends ListFragment implements OnCreateOptionsMenuListener, OnPrepareOptionsMenuListener, OnOptionsItemSelectedListener { private SherlockFragmentActivity mActivity; public SherlockFragmentActivity getSherlockActivity() { return mActivity; } @Override public void onAttach(Activity activity) { if (!(activity instanceof SherlockFragmentActivity)) { throw new IllegalStateException(getClass().getSimpleName() + " must be attached to a SherlockFragmentActivity."); } mActivity = (SherlockFragmentActivity)activity; super.onAttach(activity); } @Override public void onDetach() { mActivity = null; super.onDetach(); } @Override public final void onCreateOptionsMenu(android.view.Menu menu, android.view.MenuInflater inflater) { onCreateOptionsMenu(new MenuWrapper(menu), mActivity.getSupportMenuInflater()); } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { //Nothing to see here. } @Override public final void onPrepareOptionsMenu(android.view.Menu menu) { onPrepareOptionsMenu(new MenuWrapper(menu)); } @Override public void onPrepareOptionsMenu(Menu menu) { //Nothing to see here. } @Override public final boolean onOptionsItemSelected(android.view.MenuItem item) { return onOptionsItemSelected(new MenuItemWrapper(item)); } @Override public boolean onOptionsItemSelected(MenuItem item) { //Nothing to see here. return false; } }
Java
package com.actionbarsherlock.app; import android.app.Activity; import android.support.v4.app.DialogFragment; import com.actionbarsherlock.internal.view.menu.MenuItemWrapper; import com.actionbarsherlock.internal.view.menu.MenuWrapper; import com.actionbarsherlock.view.Menu; import com.actionbarsherlock.view.MenuInflater; import com.actionbarsherlock.view.MenuItem; import static com.actionbarsherlock.app.SherlockFragmentActivity.OnCreateOptionsMenuListener; import static com.actionbarsherlock.app.SherlockFragmentActivity.OnOptionsItemSelectedListener; import static com.actionbarsherlock.app.SherlockFragmentActivity.OnPrepareOptionsMenuListener; public class SherlockDialogFragment extends DialogFragment implements OnCreateOptionsMenuListener, OnPrepareOptionsMenuListener, OnOptionsItemSelectedListener { private SherlockFragmentActivity mActivity; public SherlockFragmentActivity getSherlockActivity() { return mActivity; } @Override public void onAttach(Activity activity) { if (!(activity instanceof SherlockFragmentActivity)) { throw new IllegalStateException(getClass().getSimpleName() + " must be attached to a SherlockFragmentActivity."); } mActivity = (SherlockFragmentActivity)activity; super.onAttach(activity); } @Override public void onDetach() { mActivity = null; super.onDetach(); } @Override public final void onCreateOptionsMenu(android.view.Menu menu, android.view.MenuInflater inflater) { onCreateOptionsMenu(new MenuWrapper(menu), mActivity.getSupportMenuInflater()); } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { //Nothing to see here. } @Override public final void onPrepareOptionsMenu(android.view.Menu menu) { onPrepareOptionsMenu(new MenuWrapper(menu)); } @Override public void onPrepareOptionsMenu(Menu menu) { //Nothing to see here. } @Override public final boolean onOptionsItemSelected(android.view.MenuItem item) { return onOptionsItemSelected(new MenuItemWrapper(item)); } @Override public boolean onOptionsItemSelected(MenuItem item) { //Nothing to see here. return false; } }
Java
package com.actionbarsherlock.app; import android.app.ExpandableListActivity; import android.content.res.Configuration; import android.os.Bundle; import android.view.KeyEvent; import android.view.View; import android.view.ViewGroup.LayoutParams; import android.view.Window; import com.actionbarsherlock.ActionBarSherlock; import com.actionbarsherlock.ActionBarSherlock.OnActionModeFinishedListener; import com.actionbarsherlock.ActionBarSherlock.OnActionModeStartedListener; import com.actionbarsherlock.ActionBarSherlock.OnCreatePanelMenuListener; import com.actionbarsherlock.ActionBarSherlock.OnMenuItemSelectedListener; import com.actionbarsherlock.ActionBarSherlock.OnPreparePanelListener; import com.actionbarsherlock.view.ActionMode; import com.actionbarsherlock.view.Menu; import com.actionbarsherlock.view.MenuInflater; import com.actionbarsherlock.view.MenuItem; public abstract class SherlockExpandableListActivity extends ExpandableListActivity implements OnCreatePanelMenuListener, OnPreparePanelListener, OnMenuItemSelectedListener, OnActionModeStartedListener, OnActionModeFinishedListener { private ActionBarSherlock mSherlock; protected final ActionBarSherlock getSherlock() { if (mSherlock == null) { mSherlock = ActionBarSherlock.wrap(this, ActionBarSherlock.FLAG_DELEGATE); } return mSherlock; } /////////////////////////////////////////////////////////////////////////// // Action bar and mode /////////////////////////////////////////////////////////////////////////// public ActionBar getSupportActionBar() { return getSherlock().getActionBar(); } public ActionMode startActionMode(ActionMode.Callback callback) { return getSherlock().startActionMode(callback); } @Override public void onActionModeStarted(ActionMode mode) {} @Override public void onActionModeFinished(ActionMode mode) {} /////////////////////////////////////////////////////////////////////////// // General lifecycle/callback dispatching /////////////////////////////////////////////////////////////////////////// @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); getSherlock().dispatchConfigurationChanged(newConfig); } @Override protected void onPostResume() { super.onPostResume(); getSherlock().dispatchPostResume(); } @Override protected void onPause() { getSherlock().dispatchPause(); super.onPause(); } @Override protected void onStop() { getSherlock().dispatchStop(); super.onStop(); } @Override protected void onDestroy() { getSherlock().dispatchDestroy(); super.onDestroy(); } @Override protected void onPostCreate(Bundle savedInstanceState) { getSherlock().dispatchPostCreate(savedInstanceState); super.onPostCreate(savedInstanceState); } @Override protected void onTitleChanged(CharSequence title, int color) { getSherlock().dispatchTitleChanged(title, color); super.onTitleChanged(title, color); } @Override public final boolean onMenuOpened(int featureId, android.view.Menu menu) { if (getSherlock().dispatchMenuOpened(featureId, menu)) { return true; } return super.onMenuOpened(featureId, menu); } @Override public void onPanelClosed(int featureId, android.view.Menu menu) { getSherlock().dispatchPanelClosed(featureId, menu); super.onPanelClosed(featureId, menu); } @Override public boolean dispatchKeyEvent(KeyEvent event) { if (getSherlock().dispatchKeyEvent(event)) { return true; } return super.dispatchKeyEvent(event); } /////////////////////////////////////////////////////////////////////////// // Native menu handling /////////////////////////////////////////////////////////////////////////// public MenuInflater getSupportMenuInflater() { return getSherlock().getMenuInflater(); } public void invalidateOptionsMenu() { getSherlock().dispatchInvalidateOptionsMenu(); } public void supportInvalidateOptionsMenu() { invalidateOptionsMenu(); } @Override public final boolean onCreateOptionsMenu(android.view.Menu menu) { return getSherlock().dispatchCreateOptionsMenu(menu); } @Override public final boolean onPrepareOptionsMenu(android.view.Menu menu) { return getSherlock().dispatchPrepareOptionsMenu(menu); } @Override public final boolean onOptionsItemSelected(android.view.MenuItem item) { return getSherlock().dispatchOptionsItemSelected(item); } @Override public void openOptionsMenu() { if (!getSherlock().dispatchOpenOptionsMenu()) { super.openOptionsMenu(); } } @Override public void closeOptionsMenu() { if (!getSherlock().dispatchCloseOptionsMenu()) { super.closeOptionsMenu(); } } /////////////////////////////////////////////////////////////////////////// // Sherlock menu handling /////////////////////////////////////////////////////////////////////////// @Override public boolean onCreatePanelMenu(int featureId, Menu menu) { if (featureId == Window.FEATURE_OPTIONS_PANEL) { return onCreateOptionsMenu(menu); } return false; } public boolean onCreateOptionsMenu(Menu menu) { return true; } @Override public boolean onPreparePanel(int featureId, View view, Menu menu) { if (featureId == Window.FEATURE_OPTIONS_PANEL) { return onPrepareOptionsMenu(menu); } return false; } public boolean onPrepareOptionsMenu(Menu menu) { return true; } @Override public boolean onMenuItemSelected(int featureId, MenuItem item) { if (featureId == Window.FEATURE_OPTIONS_PANEL) { return onOptionsItemSelected(item); } return false; } public boolean onOptionsItemSelected(MenuItem item) { return false; } /////////////////////////////////////////////////////////////////////////// // Content /////////////////////////////////////////////////////////////////////////// @Override public void addContentView(View view, LayoutParams params) { getSherlock().addContentView(view, params); } @Override public void setContentView(int layoutResId) { getSherlock().setContentView(layoutResId); } @Override public void setContentView(View view, LayoutParams params) { getSherlock().setContentView(view, params); } @Override public void setContentView(View view) { getSherlock().setContentView(view); } public void requestWindowFeature(long featureId) { getSherlock().requestFeature((int)featureId); } /////////////////////////////////////////////////////////////////////////// // Progress Indication /////////////////////////////////////////////////////////////////////////// public void setSupportProgress(int progress) { getSherlock().setProgress(progress); } public void setSupportProgressBarIndeterminate(boolean indeterminate) { getSherlock().setProgressBarIndeterminate(indeterminate); } public void setSupportProgressBarIndeterminateVisibility(boolean visible) { getSherlock().setProgressBarIndeterminateVisibility(visible); } public void setSupportProgressBarVisibility(boolean visible) { getSherlock().setProgressBarVisibility(visible); } public void setSupportSecondaryProgress(int secondaryProgress) { getSherlock().setSecondaryProgress(secondaryProgress); } }
Java
package com.actionbarsherlock.app; import android.app.ListActivity; import android.content.res.Configuration; import android.os.Bundle; import android.view.KeyEvent; import android.view.View; import android.view.Window; import android.view.ViewGroup.LayoutParams; import com.actionbarsherlock.ActionBarSherlock; import com.actionbarsherlock.ActionBarSherlock.OnActionModeFinishedListener; import com.actionbarsherlock.ActionBarSherlock.OnActionModeStartedListener; import com.actionbarsherlock.ActionBarSherlock.OnCreatePanelMenuListener; import com.actionbarsherlock.ActionBarSherlock.OnMenuItemSelectedListener; import com.actionbarsherlock.ActionBarSherlock.OnPreparePanelListener; import com.actionbarsherlock.view.ActionMode; import com.actionbarsherlock.view.Menu; import com.actionbarsherlock.view.MenuInflater; import com.actionbarsherlock.view.MenuItem; public abstract class SherlockListActivity extends ListActivity implements OnCreatePanelMenuListener, OnPreparePanelListener, OnMenuItemSelectedListener, OnActionModeStartedListener, OnActionModeFinishedListener { private ActionBarSherlock mSherlock; protected final ActionBarSherlock getSherlock() { if (mSherlock == null) { mSherlock = ActionBarSherlock.wrap(this, ActionBarSherlock.FLAG_DELEGATE); } return mSherlock; } /////////////////////////////////////////////////////////////////////////// // Action bar and mode /////////////////////////////////////////////////////////////////////////// public ActionBar getSupportActionBar() { return getSherlock().getActionBar(); } public ActionMode startActionMode(ActionMode.Callback callback) { return getSherlock().startActionMode(callback); } @Override public void onActionModeStarted(ActionMode mode) {} @Override public void onActionModeFinished(ActionMode mode) {} /////////////////////////////////////////////////////////////////////////// // General lifecycle/callback dispatching /////////////////////////////////////////////////////////////////////////// @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); getSherlock().dispatchConfigurationChanged(newConfig); } @Override protected void onPostResume() { super.onPostResume(); getSherlock().dispatchPostResume(); } @Override protected void onPause() { getSherlock().dispatchPause(); super.onPause(); } @Override protected void onStop() { getSherlock().dispatchStop(); super.onStop(); } @Override protected void onDestroy() { getSherlock().dispatchDestroy(); super.onDestroy(); } @Override protected void onPostCreate(Bundle savedInstanceState) { getSherlock().dispatchPostCreate(savedInstanceState); super.onPostCreate(savedInstanceState); } @Override protected void onTitleChanged(CharSequence title, int color) { getSherlock().dispatchTitleChanged(title, color); super.onTitleChanged(title, color); } @Override public final boolean onMenuOpened(int featureId, android.view.Menu menu) { if (getSherlock().dispatchMenuOpened(featureId, menu)) { return true; } return super.onMenuOpened(featureId, menu); } @Override public void onPanelClosed(int featureId, android.view.Menu menu) { getSherlock().dispatchPanelClosed(featureId, menu); super.onPanelClosed(featureId, menu); } @Override public boolean dispatchKeyEvent(KeyEvent event) { if (getSherlock().dispatchKeyEvent(event)) { return true; } return super.dispatchKeyEvent(event); } /////////////////////////////////////////////////////////////////////////// // Native menu handling /////////////////////////////////////////////////////////////////////////// public MenuInflater getSupportMenuInflater() { return getSherlock().getMenuInflater(); } public void invalidateOptionsMenu() { getSherlock().dispatchInvalidateOptionsMenu(); } public void supportInvalidateOptionsMenu() { invalidateOptionsMenu(); } @Override public final boolean onCreateOptionsMenu(android.view.Menu menu) { return getSherlock().dispatchCreateOptionsMenu(menu); } @Override public final boolean onPrepareOptionsMenu(android.view.Menu menu) { return getSherlock().dispatchPrepareOptionsMenu(menu); } @Override public final boolean onOptionsItemSelected(android.view.MenuItem item) { return getSherlock().dispatchOptionsItemSelected(item); } @Override public void openOptionsMenu() { if (!getSherlock().dispatchOpenOptionsMenu()) { super.openOptionsMenu(); } } @Override public void closeOptionsMenu() { if (!getSherlock().dispatchCloseOptionsMenu()) { super.closeOptionsMenu(); } } /////////////////////////////////////////////////////////////////////////// // Sherlock menu handling /////////////////////////////////////////////////////////////////////////// @Override public boolean onCreatePanelMenu(int featureId, Menu menu) { if (featureId == Window.FEATURE_OPTIONS_PANEL) { return onCreateOptionsMenu(menu); } return false; } public boolean onCreateOptionsMenu(Menu menu) { return true; } @Override public boolean onPreparePanel(int featureId, View view, Menu menu) { if (featureId == Window.FEATURE_OPTIONS_PANEL) { return onPrepareOptionsMenu(menu); } return false; } public boolean onPrepareOptionsMenu(Menu menu) { return true; } @Override public boolean onMenuItemSelected(int featureId, MenuItem item) { if (featureId == Window.FEATURE_OPTIONS_PANEL) { return onOptionsItemSelected(item); } return false; } public boolean onOptionsItemSelected(MenuItem item) { return false; } /////////////////////////////////////////////////////////////////////////// // Content /////////////////////////////////////////////////////////////////////////// @Override public void addContentView(View view, LayoutParams params) { getSherlock().addContentView(view, params); } @Override public void setContentView(int layoutResId) { getSherlock().setContentView(layoutResId); } @Override public void setContentView(View view, LayoutParams params) { getSherlock().setContentView(view, params); } @Override public void setContentView(View view) { getSherlock().setContentView(view); } public void requestWindowFeature(long featureId) { getSherlock().requestFeature((int)featureId); } /////////////////////////////////////////////////////////////////////////// // Progress Indication /////////////////////////////////////////////////////////////////////////// public void setSupportProgress(int progress) { getSherlock().setProgress(progress); } public void setSupportProgressBarIndeterminate(boolean indeterminate) { getSherlock().setProgressBarIndeterminate(indeterminate); } public void setSupportProgressBarIndeterminateVisibility(boolean visible) { getSherlock().setProgressBarIndeterminateVisibility(visible); } public void setSupportProgressBarVisibility(boolean visible) { getSherlock().setProgressBarVisibility(visible); } public void setSupportSecondaryProgress(int secondaryProgress) { getSherlock().setSecondaryProgress(secondaryProgress); } }
Java
package com.actionbarsherlock.app; import android.app.Activity; import android.support.v4.app.Fragment; import com.actionbarsherlock.internal.view.menu.MenuItemWrapper; import com.actionbarsherlock.internal.view.menu.MenuWrapper; import com.actionbarsherlock.view.Menu; import com.actionbarsherlock.view.MenuInflater; import com.actionbarsherlock.view.MenuItem; import static com.actionbarsherlock.app.SherlockFragmentActivity.OnCreateOptionsMenuListener; import static com.actionbarsherlock.app.SherlockFragmentActivity.OnOptionsItemSelectedListener; import static com.actionbarsherlock.app.SherlockFragmentActivity.OnPrepareOptionsMenuListener; public class SherlockFragment extends Fragment implements OnCreateOptionsMenuListener, OnPrepareOptionsMenuListener, OnOptionsItemSelectedListener { private SherlockFragmentActivity mActivity; public SherlockFragmentActivity getSherlockActivity() { return mActivity; } @Override public void onAttach(Activity activity) { if (!(activity instanceof SherlockFragmentActivity)) { throw new IllegalStateException(getClass().getSimpleName() + " must be attached to a SherlockFragmentActivity."); } mActivity = (SherlockFragmentActivity)activity; super.onAttach(activity); } @Override public void onDetach() { mActivity = null; super.onDetach(); } @Override public final void onCreateOptionsMenu(android.view.Menu menu, android.view.MenuInflater inflater) { onCreateOptionsMenu(new MenuWrapper(menu), mActivity.getSupportMenuInflater()); } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { //Nothing to see here. } @Override public final void onPrepareOptionsMenu(android.view.Menu menu) { onPrepareOptionsMenu(new MenuWrapper(menu)); } @Override public void onPrepareOptionsMenu(Menu menu) { //Nothing to see here. } @Override public final boolean onOptionsItemSelected(android.view.MenuItem item) { return onOptionsItemSelected(new MenuItemWrapper(item)); } @Override public boolean onOptionsItemSelected(MenuItem item) { //Nothing to see here. return false; } }
Java
package com.actionbarsherlock.app; import android.app.Activity; import android.content.res.Configuration; import android.os.Bundle; import android.view.KeyEvent; import android.view.View; import android.view.Window; import android.view.ViewGroup.LayoutParams; import com.actionbarsherlock.ActionBarSherlock; import com.actionbarsherlock.ActionBarSherlock.OnActionModeFinishedListener; import com.actionbarsherlock.ActionBarSherlock.OnActionModeStartedListener; import com.actionbarsherlock.ActionBarSherlock.OnCreatePanelMenuListener; import com.actionbarsherlock.ActionBarSherlock.OnMenuItemSelectedListener; import com.actionbarsherlock.ActionBarSherlock.OnPreparePanelListener; import com.actionbarsherlock.view.ActionMode; import com.actionbarsherlock.view.Menu; import com.actionbarsherlock.view.MenuInflater; import com.actionbarsherlock.view.MenuItem; public abstract class SherlockActivity extends Activity implements OnCreatePanelMenuListener, OnPreparePanelListener, OnMenuItemSelectedListener, OnActionModeStartedListener, OnActionModeFinishedListener { private ActionBarSherlock mSherlock; protected final ActionBarSherlock getSherlock() { if (mSherlock == null) { mSherlock = ActionBarSherlock.wrap(this, ActionBarSherlock.FLAG_DELEGATE); } return mSherlock; } /////////////////////////////////////////////////////////////////////////// // Action bar and mode /////////////////////////////////////////////////////////////////////////// public ActionBar getSupportActionBar() { return getSherlock().getActionBar(); } public ActionMode startActionMode(ActionMode.Callback callback) { return getSherlock().startActionMode(callback); } @Override public void onActionModeStarted(ActionMode mode) {} @Override public void onActionModeFinished(ActionMode mode) {} /////////////////////////////////////////////////////////////////////////// // General lifecycle/callback dispatching /////////////////////////////////////////////////////////////////////////// @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); getSherlock().dispatchConfigurationChanged(newConfig); } @Override protected void onPostResume() { super.onPostResume(); getSherlock().dispatchPostResume(); } @Override protected void onPause() { getSherlock().dispatchPause(); super.onPause(); } @Override protected void onStop() { getSherlock().dispatchStop(); super.onStop(); } @Override protected void onDestroy() { getSherlock().dispatchDestroy(); super.onDestroy(); } @Override protected void onPostCreate(Bundle savedInstanceState) { getSherlock().dispatchPostCreate(savedInstanceState); super.onPostCreate(savedInstanceState); } @Override protected void onTitleChanged(CharSequence title, int color) { getSherlock().dispatchTitleChanged(title, color); super.onTitleChanged(title, color); } @Override public final boolean onMenuOpened(int featureId, android.view.Menu menu) { if (getSherlock().dispatchMenuOpened(featureId, menu)) { return true; } return super.onMenuOpened(featureId, menu); } @Override public void onPanelClosed(int featureId, android.view.Menu menu) { getSherlock().dispatchPanelClosed(featureId, menu); super.onPanelClosed(featureId, menu); } @Override public boolean dispatchKeyEvent(KeyEvent event) { if (getSherlock().dispatchKeyEvent(event)) { return true; } return super.dispatchKeyEvent(event); } /////////////////////////////////////////////////////////////////////////// // Native menu handling /////////////////////////////////////////////////////////////////////////// public MenuInflater getSupportMenuInflater() { return getSherlock().getMenuInflater(); } public void invalidateOptionsMenu() { getSherlock().dispatchInvalidateOptionsMenu(); } public void supportInvalidateOptionsMenu() { invalidateOptionsMenu(); } @Override public final boolean onCreateOptionsMenu(android.view.Menu menu) { return getSherlock().dispatchCreateOptionsMenu(menu); } @Override public final boolean onPrepareOptionsMenu(android.view.Menu menu) { return getSherlock().dispatchPrepareOptionsMenu(menu); } @Override public final boolean onOptionsItemSelected(android.view.MenuItem item) { return getSherlock().dispatchOptionsItemSelected(item); } @Override public void openOptionsMenu() { if (!getSherlock().dispatchOpenOptionsMenu()) { super.openOptionsMenu(); } } @Override public void closeOptionsMenu() { if (!getSherlock().dispatchCloseOptionsMenu()) { super.closeOptionsMenu(); } } /////////////////////////////////////////////////////////////////////////// // Sherlock menu handling /////////////////////////////////////////////////////////////////////////// @Override public boolean onCreatePanelMenu(int featureId, Menu menu) { if (featureId == Window.FEATURE_OPTIONS_PANEL) { return onCreateOptionsMenu(menu); } return false; } public boolean onCreateOptionsMenu(Menu menu) { return true; } @Override public boolean onPreparePanel(int featureId, View view, Menu menu) { if (featureId == Window.FEATURE_OPTIONS_PANEL) { return onPrepareOptionsMenu(menu); } return false; } public boolean onPrepareOptionsMenu(Menu menu) { return true; } @Override public boolean onMenuItemSelected(int featureId, MenuItem item) { if (featureId == Window.FEATURE_OPTIONS_PANEL) { return onOptionsItemSelected(item); } return false; } public boolean onOptionsItemSelected(MenuItem item) { return false; } /////////////////////////////////////////////////////////////////////////// // Content /////////////////////////////////////////////////////////////////////////// @Override public void addContentView(View view, LayoutParams params) { getSherlock().addContentView(view, params); } @Override public void setContentView(int layoutResId) { getSherlock().setContentView(layoutResId); } @Override public void setContentView(View view, LayoutParams params) { getSherlock().setContentView(view, params); } @Override public void setContentView(View view) { getSherlock().setContentView(view); } public void requestWindowFeature(long featureId) { getSherlock().requestFeature((int)featureId); } /////////////////////////////////////////////////////////////////////////// // Progress Indication /////////////////////////////////////////////////////////////////////////// public void setSupportProgress(int progress) { getSherlock().setProgress(progress); } public void setSupportProgressBarIndeterminate(boolean indeterminate) { getSherlock().setProgressBarIndeterminate(indeterminate); } public void setSupportProgressBarIndeterminateVisibility(boolean visible) { getSherlock().setProgressBarIndeterminateVisibility(visible); } public void setSupportProgressBarVisibility(boolean visible) { getSherlock().setProgressBarVisibility(visible); } public void setSupportSecondaryProgress(int secondaryProgress) { getSherlock().setSecondaryProgress(secondaryProgress); } }
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
/* * 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
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package prbd; /** * * @author DANIEL */ public class PrBD { /** * @param args the command line arguments */ public static void main(String[] args) { // TODO code application logic here } }
Java
import java.util.Arrays; import java.util.Collections; /** * Created by mauricio on 9/17/14. */ public class Triangle { private int length; public String symbol = "*"; public Triangle(int length) { this.length = length; } public String getOne() { return symbol; } public String getHorizontalLine() { return this.getHorizontalLine(this.length); } public String getHorizontalLine(int length) { StringBuilder asterisks = new StringBuilder(); for(int i = 0; i < length; i++) asterisks.append(getOne()); return String.valueOf(asterisks); } public String getVerticalLine(int length) { StringBuilder asterisks = null; for(int i = 0; i < length; i++) asterisks.append(getOne() + "\n"); return String.valueOf(asterisks).replaceFirst("\\s+$", ""); } public String getRightTriangle(int length) { StringBuilder asterisks = new StringBuilder(); for(int i = 1; i <= length; i++) asterisks.append(this.getHorizontalLine(i) + "\n"); return String.valueOf(asterisks).replaceFirst("\\s+$", ""); } public String getRightTriangle() { return this.getRightTriangle(this.length); } public String getIsosceles() { StringBuilder asterisks = new StringBuilder(); for(int i = 1; i <= length; i++) { asterisks.append(this.with(" ").getHorizontalLine(length - i) + this.getHorizontalLine((i*2) -1) + "\n"); } return String.valueOf(asterisks).replaceFirst("\\s+$", ""); } public String getDiamond() { StringBuilder asterisks = new StringBuilder(); asterisks.append(getIsosceles() + "\n" + reverse(getIsosceles(), 1) ); return String.valueOf(asterisks).replaceFirst("\\s+$", ""); } public String getDiamondWithName( String name) { String d = getDiamond(); return d.replace(getHorizontalLine((this.length * 2) -1), name); } public static String reverse(String triangle, int start) { String[] reversed = triangle.split("\n"); StringBuilder asterisks = new StringBuilder(); for(int i = reversed.length -(1+start); i > -1 ; i--) { asterisks.append(reversed[i] + "\n"); } return String.valueOf(asterisks).replaceFirst("\\s+$", ""); } public static void draw(String triangle) { System.out.println(triangle); } public Triangle with(String symbol) { Triangle t = new Triangle(length); t.symbol = symbol; return t; } public static void main(String[] args) throws CloneNotSupportedException { Triangle triangle = new Triangle(3); draw(triangle.getOne()); draw(triangle.getHorizontalLine()); draw(triangle.getRightTriangle()); //draw(reverse(triangle.getIsosceles())); draw(triangle.getIsosceles()); draw(triangle.getDiamond()); draw(triangle.getDiamondWithName("Bill")); } }
Java
import java.util.ArrayList; import java.util.Collection; import java.util.List; /** * Created by mauricio on 9/18/14. */ public class PrimeFactors { private static List list = new ArrayList(); private static void addFactor(int factor) { if(!list.contains(factor)) { list.add(factor); } } public static List generate(int num) { int quotient = 0; for (int factor = 2; factor <= num ; factor++) { if (num%factor == 0) { addFactor(factor); quotient = num / factor; if(quotient != 1) { return generate(quotient); } else break; } } return list; } public static void main(String[] args) { System.out.println(PrimeFactors.generate(191)); } }
Java
/** * Created by mauricio on 9/18/14. */ public class FizzBuzz { public static void fizzBuzz(int limit) { String result; for(int num = 1; num <= limit; num++) { result = ""; if(num % 3 == 0) result += "Fizz"; else if(num % 5 == 0) result += "Buzz"; else if(result.isEmpty()) result = Integer.toString(num); System.out.println(result); } } public static void main(String[] args) { fizzBuzz(100); } }
Java
/* * Copyright (C) 2009 University of Washington * * 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 org.odk.collect.android.activities; import java.util.ArrayList; import org.odk.collect.android.R; import org.odk.collect.android.application.Collect; import org.odk.collect.android.listeners.DeleteInstancesListener; import org.odk.collect.android.provider.InstanceProviderAPI.InstanceColumns; import org.odk.collect.android.tasks.DeleteInstancesTask; import android.app.AlertDialog; import android.app.ListActivity; import android.content.DialogInterface; import android.database.Cursor; import android.os.AsyncTask; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.ListView; import android.widget.SimpleCursorAdapter; import android.widget.Toast; /** * Responsible for displaying and deleting all the valid forms in the forms * directory. * * @author Carl Hartung (carlhartung@gmail.com) * @author Yaw Anokwa (yanokwa@gmail.com) */ public class DataManagerList extends ListActivity implements DeleteInstancesListener { private static final String t = "DataManagerList"; private AlertDialog mAlertDialog; private Button mDeleteButton; private Button mToggleButton; private SimpleCursorAdapter mInstances; private ArrayList<Long> mSelected = new ArrayList<Long>(); DeleteInstancesTask mDeleteInstancesTask = null; private static final String SELECTED = "selected"; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.data_manage_list); mDeleteButton = (Button) findViewById(R.id.delete_button); mDeleteButton.setText(getString(R.string.delete_file)); mDeleteButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Collect.getInstance().getActivityLogger().logAction(this, "deleteButton", Integer.toString(mSelected.size())); if (mSelected.size() > 0) { createDeleteInstancesDialog(); } else { Toast.makeText(getApplicationContext(), R.string.noselect_error, Toast.LENGTH_SHORT).show(); } } }); mToggleButton = (Button) findViewById(R.id.toggle_button); mToggleButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { boolean checkAll = false; // if everything is checked, uncheck if (mSelected.size() == mInstances.getCount()) { checkAll = false; mSelected.clear(); mDeleteButton.setEnabled(false); } else { // otherwise check everything checkAll = true; for (int pos = 0; pos < DataManagerList.this.getListView().getCount(); pos++) { Long id = getListAdapter().getItemId(pos); if (!mSelected.contains(id)) { mSelected.add(id); } } mDeleteButton.setEnabled(true); } for (int pos = 0; pos < DataManagerList.this.getListView().getCount(); pos++) { DataManagerList.this.getListView().setItemChecked(pos, checkAll); } } }); Cursor c = managedQuery(InstanceColumns.CONTENT_URI, null, null, null, InstanceColumns.DISPLAY_NAME + " ASC"); String[] data = new String[] { InstanceColumns.DISPLAY_NAME, InstanceColumns.DISPLAY_SUBTEXT }; int[] view = new int[] { R.id.text1, R.id.text2 }; mInstances = new SimpleCursorAdapter(this, R.layout.two_item_multiple_choice, c, data, view); setListAdapter(mInstances); getListView().setChoiceMode(ListView.CHOICE_MODE_MULTIPLE); getListView().setItemsCanFocus(false); mDeleteButton.setEnabled(false); mDeleteInstancesTask = (DeleteInstancesTask) getLastNonConfigurationInstance(); } @Override protected void onStart() { super.onStart(); Collect.getInstance().getActivityLogger().logOnStart(this); } @Override protected void onStop() { Collect.getInstance().getActivityLogger().logOnStop(this); super.onStop(); } @Override public Object onRetainNonConfigurationInstance() { // pass the tasks on orientation-change restart return mDeleteInstancesTask; } @Override protected void onRestoreInstanceState(Bundle savedInstanceState) { super.onRestoreInstanceState(savedInstanceState); long[] selectedArray = savedInstanceState.getLongArray(SELECTED); for (int i = 0; i < selectedArray.length; i++) { mSelected.add(selectedArray[i]); } mDeleteButton.setEnabled(selectedArray.length > 0); } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); long[] selectedArray = new long[mSelected.size()]; for (int i = 0; i < mSelected.size(); i++) { selectedArray[i] = mSelected.get(i); } outState.putLongArray(SELECTED, selectedArray); } @Override protected void onResume() { // hook up to receive completion events if (mDeleteInstancesTask != null) { mDeleteInstancesTask.setDeleteListener(this); } super.onResume(); // async task may have completed while we were reorienting... if (mDeleteInstancesTask != null && mDeleteInstancesTask.getStatus() == AsyncTask.Status.FINISHED) { deleteComplete(mDeleteInstancesTask.getDeleteCount()); } } @Override protected void onPause() { if (mDeleteInstancesTask != null ) { mDeleteInstancesTask.setDeleteListener(null); } if (mAlertDialog != null && mAlertDialog.isShowing()) { mAlertDialog.dismiss(); } super.onPause(); } /** * Create the instance delete dialog */ private void createDeleteInstancesDialog() { Collect.getInstance().getActivityLogger().logAction(this, "createDeleteInstancesDialog", "show"); mAlertDialog = new AlertDialog.Builder(this).create(); mAlertDialog.setTitle(getString(R.string.delete_file)); mAlertDialog.setMessage(getString(R.string.delete_confirm, mSelected.size())); DialogInterface.OnClickListener dialogYesNoListener = new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int i) { switch (i) { case DialogInterface.BUTTON_POSITIVE: // delete Collect.getInstance().getActivityLogger().logAction(this, "createDeleteInstancesDialog", "delete"); deleteSelectedInstances(); break; case DialogInterface. BUTTON_NEGATIVE: // do nothing Collect.getInstance().getActivityLogger().logAction(this, "createDeleteInstancesDialog", "cancel"); break; } } }; mAlertDialog.setCancelable(false); mAlertDialog.setButton(getString(R.string.delete_yes), dialogYesNoListener); mAlertDialog.setButton2(getString(R.string.delete_no), dialogYesNoListener); mAlertDialog.show(); } /** * Deletes the selected files. Content provider handles removing the files * from the filesystem. */ private void deleteSelectedInstances() { if (mDeleteInstancesTask == null) { mDeleteInstancesTask = new DeleteInstancesTask(); mDeleteInstancesTask.setContentResolver(getContentResolver()); mDeleteInstancesTask.setDeleteListener(this); mDeleteInstancesTask.execute(mSelected.toArray(new Long[mSelected .size()])); } else { Toast.makeText(this, getString(R.string.file_delete_in_progress), Toast.LENGTH_LONG).show(); } } @Override protected void onListItemClick(ListView l, View v, int position, long id) { super.onListItemClick(l, v, position, id); // get row id from db Cursor c = (Cursor) getListAdapter().getItem(position); long k = c.getLong(c.getColumnIndex(InstanceColumns._ID)); // add/remove from selected list if (mSelected.contains(k)) mSelected.remove(k); else mSelected.add(k); Collect.getInstance().getActivityLogger().logAction(this, "onListItemClick", Long.toString(k)); mDeleteButton.setEnabled(!(mSelected.size() == 0)); } @Override public void deleteComplete(int deletedInstances) { Log.i(t, "Delete instances complete"); Collect.getInstance().getActivityLogger().logAction(this, "deleteComplete", Integer.toString(deletedInstances)); if (deletedInstances == mSelected.size()) { // all deletes were successful Toast.makeText(this, getString(R.string.file_deleted_ok, deletedInstances), Toast.LENGTH_SHORT).show(); } else { // had some failures Log.e(t, "Failed to delete " + (mSelected.size() - deletedInstances) + " instances"); Toast.makeText( this, getString(R.string.file_deleted_error, mSelected.size() - deletedInstances, mSelected.size()), Toast.LENGTH_LONG).show(); } mDeleteInstancesTask = null; mSelected.clear(); getListView().clearChoices(); // doesn't unset the checkboxes for ( int i = 0 ; i < getListView().getCount() ; ++i ) { getListView().setItemChecked(i, false); } mDeleteButton.setEnabled(false); } }
Java
/* * Copyright (C) 2009 University of Washington * * 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 org.odk.collect.android.activities; import java.util.ArrayList; import org.odk.collect.android.R; import org.odk.collect.android.application.Collect; import org.odk.collect.android.listeners.DeleteFormsListener; import org.odk.collect.android.listeners.DiskSyncListener; import org.odk.collect.android.provider.FormsProviderAPI.FormsColumns; import org.odk.collect.android.tasks.DeleteFormsTask; import org.odk.collect.android.tasks.DiskSyncTask; import org.odk.collect.android.utilities.VersionHidingCursorAdapter; import android.app.AlertDialog; import android.app.ListActivity; import android.content.DialogInterface; import android.database.Cursor; import android.os.AsyncTask; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.ListView; import android.widget.SimpleCursorAdapter; import android.widget.TextView; import android.widget.Toast; /** * Responsible for displaying and deleting all the valid forms in the forms * directory. * * @author Carl Hartung (carlhartung@gmail.com) * @author Yaw Anokwa (yanokwa@gmail.com) */ public class FormManagerList extends ListActivity implements DiskSyncListener, DeleteFormsListener { private static String t = "FormManagerList"; private static final String SELECTED = "selected"; private static final String syncMsgKey = "syncmsgkey"; private AlertDialog mAlertDialog; private Button mDeleteButton; private Button mToggleButton; private SimpleCursorAdapter mInstances; private ArrayList<Long> mSelected = new ArrayList<Long>(); static class BackgroundTasks { DiskSyncTask mDiskSyncTask = null; DeleteFormsTask mDeleteFormsTask = null; BackgroundTasks() { }; } BackgroundTasks mBackgroundTasks; // handed across orientation changes @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.form_manage_list); mDeleteButton = (Button) findViewById(R.id.delete_button); mDeleteButton.setText(getString(R.string.delete_file)); mDeleteButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Collect.getInstance().getActivityLogger().logAction(this, "deleteButton", Integer.toString(mSelected.size())); if (mSelected.size() > 0) { createDeleteFormsDialog(); } else { Toast.makeText(getApplicationContext(), R.string.noselect_error, Toast.LENGTH_SHORT).show(); } } }); mToggleButton = (Button) findViewById(R.id.toggle_button); mToggleButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { boolean checkAll = false; // if everything is checked, uncheck if (mSelected.size() == mInstances.getCount()) { checkAll = false; mSelected.clear(); mDeleteButton.setEnabled(false); } else { // otherwise check everything checkAll = true; for (int pos = 0; pos < FormManagerList.this.getListView().getCount(); pos++) { Long id = getListAdapter().getItemId(pos); if (!mSelected.contains(id)) { mSelected.add(id); } } mDeleteButton.setEnabled(true); } for (int pos = 0; pos < FormManagerList.this.getListView().getCount(); pos++) { FormManagerList.this.getListView().setItemChecked(pos, checkAll); } } }); String sortOrder = FormsColumns.DISPLAY_NAME + " ASC, " + FormsColumns.JR_VERSION + " DESC"; Cursor c = managedQuery(FormsColumns.CONTENT_URI, null, null, null, sortOrder); String[] data = new String[] { FormsColumns.DISPLAY_NAME, FormsColumns.DISPLAY_SUBTEXT, FormsColumns.JR_VERSION }; int[] view = new int[] { R.id.text1, R.id.text2, R.id.text3 }; // render total instance view mInstances = new VersionHidingCursorAdapter(FormsColumns.JR_VERSION, this, R.layout.two_item_multiple_choice, c, data, view); setListAdapter(mInstances); getListView().setChoiceMode(ListView.CHOICE_MODE_MULTIPLE); getListView().setItemsCanFocus(false); mDeleteButton.setEnabled(!(mSelected.size() == 0)); if (savedInstanceState != null && savedInstanceState.containsKey(syncMsgKey)) { TextView tv = (TextView) findViewById(R.id.status_text); tv.setText(savedInstanceState.getString(syncMsgKey)); } mBackgroundTasks = (BackgroundTasks) getLastNonConfigurationInstance(); if (mBackgroundTasks == null) { mBackgroundTasks = new BackgroundTasks(); mBackgroundTasks.mDiskSyncTask = new DiskSyncTask(); mBackgroundTasks.mDiskSyncTask.setDiskSyncListener(this); mBackgroundTasks.mDiskSyncTask.execute((Void[]) null); } } @Override protected void onStart() { super.onStart(); Collect.getInstance().getActivityLogger().logOnStart(this); } @Override protected void onStop() { Collect.getInstance().getActivityLogger().logOnStop(this); super.onStop(); } @Override public Object onRetainNonConfigurationInstance() { // pass the tasks on restart return mBackgroundTasks; } @Override protected void onRestoreInstanceState(Bundle savedInstanceState) { super.onRestoreInstanceState(savedInstanceState); long[] selectedArray = savedInstanceState.getLongArray(SELECTED); for (int i = 0; i < selectedArray.length; i++) { mSelected.add(selectedArray[i]); } mDeleteButton.setEnabled(selectedArray.length > 0); } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); long[] selectedArray = new long[mSelected.size()]; for (int i = 0; i < mSelected.size(); i++) { selectedArray[i] = mSelected.get(i); } outState.putLongArray(SELECTED, selectedArray); TextView tv = (TextView) findViewById(R.id.status_text); outState.putString(syncMsgKey, tv.getText().toString()); } @Override protected void onResume() { // hook up to receive completion events mBackgroundTasks.mDiskSyncTask.setDiskSyncListener(this); if (mBackgroundTasks.mDeleteFormsTask != null) { mBackgroundTasks.mDeleteFormsTask.setDeleteListener(this); } super.onResume(); // async task may have completed while we were reorienting... if (mBackgroundTasks.mDiskSyncTask.getStatus() == AsyncTask.Status.FINISHED) { SyncComplete(mBackgroundTasks.mDiskSyncTask.getStatusMessage()); } if (mBackgroundTasks.mDeleteFormsTask != null && mBackgroundTasks.mDeleteFormsTask.getStatus() == AsyncTask.Status.FINISHED) { deleteComplete(mBackgroundTasks.mDeleteFormsTask.getDeleteCount()); } } @Override protected void onPause() { mBackgroundTasks.mDiskSyncTask.setDiskSyncListener(null); if (mBackgroundTasks.mDeleteFormsTask != null ) { mBackgroundTasks.mDeleteFormsTask.setDeleteListener(null); } if (mAlertDialog != null && mAlertDialog.isShowing()) { mAlertDialog.dismiss(); } super.onPause(); } /** * Create the form delete dialog */ private void createDeleteFormsDialog() { Collect.getInstance().getActivityLogger().logAction(this, "createDeleteFormsDialog", "show"); mAlertDialog = new AlertDialog.Builder(this).create(); mAlertDialog.setTitle(getString(R.string.delete_file)); mAlertDialog.setMessage(getString(R.string.delete_confirm, mSelected.size())); DialogInterface.OnClickListener dialogYesNoListener = new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int i) { switch (i) { case DialogInterface.BUTTON_POSITIVE: // delete Collect.getInstance().getActivityLogger().logAction(this, "createDeleteFormsDialog", "delete"); deleteSelectedForms(); break; case DialogInterface. BUTTON_NEGATIVE: // do nothing Collect.getInstance().getActivityLogger().logAction(this, "createDeleteFormsDialog", "cancel"); break; } } }; mAlertDialog.setCancelable(false); mAlertDialog.setButton(getString(R.string.delete_yes), dialogYesNoListener); mAlertDialog.setButton2(getString(R.string.delete_no), dialogYesNoListener); mAlertDialog.show(); } /** * Deletes the selected files.First from the database then from the file * system */ private void deleteSelectedForms() { // only start if no other task is running if (mBackgroundTasks.mDeleteFormsTask == null) { mBackgroundTasks.mDeleteFormsTask = new DeleteFormsTask(); mBackgroundTasks.mDeleteFormsTask .setContentResolver(getContentResolver()); mBackgroundTasks.mDeleteFormsTask.setDeleteListener(this); mBackgroundTasks.mDeleteFormsTask.execute(mSelected .toArray(new Long[mSelected.size()])); } else { Toast.makeText(this, getString(R.string.file_delete_in_progress), Toast.LENGTH_LONG).show(); } } @Override protected void onListItemClick(ListView l, View v, int position, long id) { super.onListItemClick(l, v, position, id); // get row id from db Cursor c = (Cursor) getListAdapter().getItem(position); long k = c.getLong(c.getColumnIndex(FormsColumns._ID)); // add/remove from selected list if (mSelected.contains(k)) mSelected.remove(k); else mSelected.add(k); Collect.getInstance().getActivityLogger().logAction(this, "onListItemClick", Long.toString(k)); mDeleteButton.setEnabled(!(mSelected.size() == 0)); } @Override public void SyncComplete(String result) { Log.i(t, "Disk scan complete"); TextView tv = (TextView) findViewById(R.id.status_text); tv.setText(result); } @Override public void deleteComplete(int deletedForms) { Log.i(t, "Delete forms complete"); Collect.getInstance().getActivityLogger().logAction(this, "deleteComplete", Integer.toString(deletedForms)); if (deletedForms == mSelected.size()) { // all deletes were successful Toast.makeText(getApplicationContext(), getString(R.string.file_deleted_ok, deletedForms), Toast.LENGTH_SHORT).show(); } else { // had some failures Log.e(t, "Failed to delete " + (mSelected.size() - deletedForms) + " forms"); Toast.makeText( getApplicationContext(), getString(R.string.file_deleted_error, mSelected.size() - deletedForms, mSelected.size()), Toast.LENGTH_LONG).show(); } mBackgroundTasks.mDeleteFormsTask = null; mSelected.clear(); getListView().clearChoices(); // doesn't unset the checkboxes for ( int i = 0 ; i < getListView().getCount() ; ++i ) { getListView().setItemChecked(i, false); } mDeleteButton.setEnabled(false); } }
Java
/* * Copyright (C) 2014 Nafundi * * 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. */ /** * Activity to upload completed forms to gme. * * @author Carl Hartung (chartung@nafundi.com) */ package org.odk.collect.android.activities; import java.io.IOException; import java.util.HashMap; import java.util.Iterator; import java.util.Set; import org.odk.collect.android.R; import org.odk.collect.android.application.Collect; import org.odk.collect.android.listeners.InstanceUploaderListener; import org.odk.collect.android.preferences.PreferencesActivity; import org.odk.collect.android.provider.InstanceProviderAPI.InstanceColumns; import org.odk.collect.android.tasks.GoogleMapsEngineAbstractUploader; import org.odk.collect.android.tasks.GoogleMapsEngineTask; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.app.ProgressDialog; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.preference.PreferenceManager; import android.util.Log; import com.google.android.gms.auth.GoogleAuthException; import com.google.android.gms.auth.GooglePlayServicesAvailabilityException; import com.google.android.gms.auth.UserRecoverableAuthException; import com.google.android.gms.common.GooglePlayServicesUtil; public class GoogleMapsEngineUploaderActivity extends Activity implements InstanceUploaderListener { private final static String tag = "GoogleMapsEngineUploaderActivity"; private final static int PROGRESS_DIALOG = 1; private final static int GOOGLE_USER_DIALOG = 3; private static final String ALERT_MSG = "alertmsg"; private static final String ALERT_SHOWING = "alertshowing"; private ProgressDialog mProgressDialog; private AlertDialog mAlertDialog; private String mAlertMsg; private boolean mAlertShowing; private Long[] mInstancesToSend; private GoogleMapsEngineInstanceUploaderTask mUlTask; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Log.i(tag, "onCreate: " + ((savedInstanceState == null) ? "creating" : "re-initializing")); // if we start this activity, the following must be true: // 1) Google Maps Engine is selected in preferences // 2) A google user is selected // default initializers mAlertMsg = getString(R.string.please_wait); mAlertShowing = false; setTitle(getString(R.string.app_name) + " > " + getString(R.string.send_data)); // get any simple saved // state... // resets alert message and showing dialog if the screen is rotated if (savedInstanceState != null) { if (savedInstanceState.containsKey(ALERT_MSG)) { mAlertMsg = savedInstanceState.getString(ALERT_MSG); } if (savedInstanceState.containsKey(ALERT_SHOWING)) { mAlertShowing = savedInstanceState.getBoolean(ALERT_SHOWING, false); } } long[] selectedInstanceIDs = null; Intent intent = getIntent(); selectedInstanceIDs = intent .getLongArrayExtra(FormEntryActivity.KEY_INSTANCES); mInstancesToSend = new Long[(selectedInstanceIDs == null) ? 0 : selectedInstanceIDs.length]; if (selectedInstanceIDs != null) { for (int i = 0; i < selectedInstanceIDs.length; ++i) { mInstancesToSend[i] = selectedInstanceIDs[i]; } } // at this point, // we don't expect this to be empty... if (mInstancesToSend.length == 0) { Log.e(tag, "onCreate: No instances to upload!"); // drop through -- // everything will process through OK } else { Log.i(tag, "onCreate: Beginning upload of " + mInstancesToSend.length + " instances!"); } runTask(); } private void runTask() { mUlTask = (GoogleMapsEngineInstanceUploaderTask) getLastNonConfigurationInstance(); if (mUlTask == null) { mUlTask = new GoogleMapsEngineInstanceUploaderTask(); // ensure we have a google account selected SharedPreferences prefs = PreferenceManager .getDefaultSharedPreferences(this); String googleUsername = prefs.getString( PreferencesActivity.KEY_SELECTED_GOOGLE_ACCOUNT, null); if (googleUsername == null || googleUsername.equals("")) { showDialog(GOOGLE_USER_DIALOG); return; } // setup dialog and upload task showDialog(PROGRESS_DIALOG); mUlTask.setUserName(googleUsername); mUlTask.setUploaderListener(this); mUlTask.execute(mInstancesToSend); } else { // it's not null, so we have a task running // progress dialog is handled by the system } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == GoogleMapsEngineTask.PLAYSTORE_REQUEST_CODE && resultCode == RESULT_OK) { // the user got sent to the playstore // it returns to this activity, but we'd rather they manually retry // so we finish finish(); } else if (requestCode == GoogleMapsEngineTask.USER_RECOVERABLE_REQUEST_CODE && resultCode == RESULT_OK) { // authorization granted, try again runTask(); } else if (requestCode == GoogleMapsEngineTask.USER_RECOVERABLE_REQUEST_CODE && resultCode == RESULT_CANCELED) { // the user backed out finish(); } else { Log.e(tag, "unknown request: " + requestCode + " :: result: " + resultCode); } } @Override protected void onStart() { super.onStart(); Collect.getInstance().getActivityLogger().logOnStart(this); } @Override protected void onResume() { if (mUlTask != null) { mUlTask.setUploaderListener(this); } if (mAlertShowing) { createAlertDialog(mAlertMsg); } super.onResume(); } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putString(ALERT_MSG, mAlertMsg); outState.putBoolean(ALERT_SHOWING, mAlertShowing); } @Override public Object onRetainNonConfigurationInstance() { return mUlTask; } @Override protected void onPause() { super.onPause(); if (mAlertDialog != null && mAlertDialog.isShowing()) { mAlertDialog.dismiss(); } } @Override protected void onStop() { Collect.getInstance().getActivityLogger().logOnStop(this); super.onStop(); } @Override protected void onDestroy() { if (mUlTask != null) { mUlTask.setUploaderListener(null); } super.onDestroy(); } @Override public void uploadingComplete(HashMap<String, String> result) { try { dismissDialog(PROGRESS_DIALOG); } catch (Exception e) { // tried to close a dialog not open. don't care. } if (result == null) { // probably got an auth request, so ignore return; } Log.i(tag, "uploadingComplete: Processing results (" + result.size() + ") from upload of " + mInstancesToSend.length + " instances!"); StringBuilder selection = new StringBuilder(); Set<String> keys = result.keySet(); StringBuilder message = new StringBuilder(); if (keys.size() == 0) { message.append(getString(R.string.no_forms_uploaded)); } else { Iterator<String> it = keys.iterator(); String[] selectionArgs = new String[keys.size()]; int i = 0; while (it.hasNext()) { String id = it.next(); selection.append(InstanceColumns._ID + "=?"); selectionArgs[i++] = id; if (i != keys.size()) { selection.append(" or "); } } Cursor results = null; try { results = getContentResolver().query( InstanceColumns.CONTENT_URI, null, selection.toString(), selectionArgs, null); if (results.getCount() > 0) { results.moveToPosition(-1); while (results.moveToNext()) { String name = results.getString(results .getColumnIndex(InstanceColumns.DISPLAY_NAME)); String id = results.getString(results .getColumnIndex(InstanceColumns._ID)); message.append(name + " - " + result.get(id) + "\n\n"); } } else { message.append(getString(R.string.no_forms_uploaded)); } } finally { if (results != null) { results.close(); } } } createAlertDialog(message.toString().trim()); } @Override public void progressUpdate(int progress, int total) { mAlertMsg = getString(R.string.sending_items, progress, total); mProgressDialog.setMessage(mAlertMsg); } @Override protected Dialog onCreateDialog(int id) { switch (id) { case PROGRESS_DIALOG: Collect.getInstance().getActivityLogger() .logAction(this, "onCreateDialog.PROGRESS_DIALOG", "show"); mProgressDialog = new ProgressDialog(this); DialogInterface.OnClickListener loadingButtonListener = new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Collect.getInstance() .getActivityLogger() .logAction(this, "onCreateDialog.PROGRESS_DIALOG", "cancel"); dialog.dismiss(); mUlTask.cancel(true); mUlTask.setUploaderListener(null); finish(); } }; mProgressDialog.setTitle(getString(R.string.uploading_data)); mProgressDialog.setMessage(mAlertMsg); mProgressDialog.setIndeterminate(true); mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER); mProgressDialog.setCancelable(false); mProgressDialog.setButton(getString(R.string.cancel), loadingButtonListener); return mProgressDialog; case GOOGLE_USER_DIALOG: AlertDialog.Builder gudBuilder = new AlertDialog.Builder(this); gudBuilder.setTitle(getString(R.string.no_google_account)); gudBuilder.setMessage(getString(R.string.gme_set_account)); gudBuilder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { finish(); } }); gudBuilder.setCancelable(false); return gudBuilder.create(); } return null; } private void createAlertDialog(String message) { Collect.getInstance().getActivityLogger() .logAction(this, "createAlertDialog", "show"); mAlertDialog = new AlertDialog.Builder(this).create(); mAlertDialog.setTitle(getString(R.string.upload_results)); mAlertDialog.setMessage(message); DialogInterface.OnClickListener quitListener = new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int i) { switch (i) { case DialogInterface.BUTTON1: // ok Collect.getInstance().getActivityLogger() .logAction(this, "createAlertDialog", "OK"); // always exit this activity since it has no interface mAlertShowing = false; finish(); break; } } }; mAlertDialog.setCancelable(false); mAlertDialog.setButton(getString(R.string.ok), quitListener); mAlertDialog.setIcon(android.R.drawable.ic_dialog_info); mAlertShowing = true; mAlertMsg = message; mAlertDialog.show(); } public class GoogleMapsEngineInstanceUploaderTask extends GoogleMapsEngineAbstractUploader<Long, Integer, HashMap<String, String>> { @Override protected HashMap<String, String> doInBackground(Long... values) { mResults = new HashMap<String, String>(); String selection = InstanceColumns._ID + "=?"; String[] selectionArgs = new String[(values == null) ? 0 : values.length]; if (values != null) { for (int i = 0; i < values.length; i++) { if (i != values.length - 1) { selection += " or " + InstanceColumns._ID + "=?"; } selectionArgs[i] = values[i].toString(); } } String token = null; try { token = authenticate(GoogleMapsEngineUploaderActivity.this, mGoogleUserName); } catch (IOException e) { // network or server error, the call is expected to succeed if // you try again later. Don't attempt to call again immediately // - the request is likely to fail, you'll hit quotas or // back-off. e.printStackTrace(); mResults.put("0", oauth_fail + e.getMessage()); return mResults; } catch (GooglePlayServicesAvailabilityException playEx) { Dialog alert = GooglePlayServicesUtil.getErrorDialog( playEx.getConnectionStatusCode(), GoogleMapsEngineUploaderActivity.this, PLAYSTORE_REQUEST_CODE); alert.show(); return null; } catch (UserRecoverableAuthException e) { GoogleMapsEngineUploaderActivity.this.startActivityForResult(e.getIntent(), USER_RECOVERABLE_REQUEST_CODE); e.printStackTrace(); return null; } catch (GoogleAuthException e) { // Failure. The call is not expected to ever succeed so it // should not be retried. e.printStackTrace(); mResults.put("0", oauth_fail + e.getMessage()); return mResults; } if (token == null) { // if token is null, return null; } uploadInstances(selection, selectionArgs, token); return mResults; } } @Override public void authRequest(Uri url, HashMap<String, String> doneSoFar) { // this shouldn't be in the interface... } }
Java
/* * Copyright (C) 2009 University of Washington * * 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 org.odk.collect.android.activities; import java.io.File; import java.io.FileFilter; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.LinkedHashMap; import java.util.List; import java.util.Locale; import org.javarosa.core.model.FormIndex; import org.javarosa.core.model.data.IAnswerData; import org.javarosa.core.model.instance.TreeElement; import org.javarosa.form.api.FormEntryCaption; import org.javarosa.form.api.FormEntryController; import org.javarosa.form.api.FormEntryPrompt; import org.odk.collect.android.R; import org.odk.collect.android.application.Collect; import org.odk.collect.android.exception.JavaRosaException; import org.odk.collect.android.listeners.AdvanceToNextListener; import org.odk.collect.android.listeners.FormLoaderListener; import org.odk.collect.android.listeners.FormSavedListener; import org.odk.collect.android.listeners.SavePointListener; import org.odk.collect.android.logic.FormController; import org.odk.collect.android.logic.FormController.FailedConstraint; import org.odk.collect.android.preferences.AdminPreferencesActivity; import org.odk.collect.android.preferences.PreferencesActivity; import org.odk.collect.android.provider.FormsProviderAPI.FormsColumns; import org.odk.collect.android.provider.InstanceProviderAPI; import org.odk.collect.android.provider.InstanceProviderAPI.InstanceColumns; import org.odk.collect.android.tasks.FormLoaderTask; import org.odk.collect.android.tasks.SavePointTask; import org.odk.collect.android.tasks.SaveResult; import org.odk.collect.android.tasks.SaveToDiskTask; import org.odk.collect.android.utilities.CompatibilityUtils; import org.odk.collect.android.utilities.FileUtils; import org.odk.collect.android.utilities.MediaUtils; import org.odk.collect.android.views.ODKView; import org.odk.collect.android.widgets.QuestionWidget; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.app.ProgressDialog; import android.content.ContentValues; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.database.Cursor; import android.graphics.Color; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.preference.PreferenceManager; import android.provider.MediaStore.Images; import android.text.InputFilter; import android.text.Spanned; import android.util.DisplayMetrics; import android.util.Log; import android.view.ContextMenu; import android.view.ContextMenu.ContextMenuInfo; import android.view.GestureDetector; import android.view.GestureDetector.OnGestureListener; import android.view.Gravity; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.MotionEvent; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup.LayoutParams; import android.view.animation.Animation; import android.view.animation.Animation.AnimationListener; import android.view.animation.AnimationUtils; import android.view.inputmethod.InputMethodManager; import android.widget.Button; import android.widget.CheckBox; import android.widget.EditText; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.Toast; /** * FormEntryActivity is responsible for displaying questions, animating * transitions between questions, and allowing the user to enter data. * * @author Carl Hartung (carlhartung@gmail.com) * @author Thomas Smyth, Sassafras Tech Collective (tom@sassafrastech.com; constraint behavior option) */ public class FormEntryActivity extends Activity implements AnimationListener, FormLoaderListener, FormSavedListener, AdvanceToNextListener, OnGestureListener, SavePointListener { private static final String t = "FormEntryActivity"; // save with every swipe forward or back. Timings indicate this takes .25 // seconds. // if it ever becomes an issue, this value can be changed to save every n'th // screen. private static final int SAVEPOINT_INTERVAL = 1; // Defines for FormEntryActivity private static final boolean EXIT = true; private static final boolean DO_NOT_EXIT = false; private static final boolean EVALUATE_CONSTRAINTS = true; private static final boolean DO_NOT_EVALUATE_CONSTRAINTS = false; // Request codes for returning data from specified intent. public static final int IMAGE_CAPTURE = 1; public static final int BARCODE_CAPTURE = 2; public static final int AUDIO_CAPTURE = 3; public static final int VIDEO_CAPTURE = 4; public static final int LOCATION_CAPTURE = 5; public static final int HIERARCHY_ACTIVITY = 6; public static final int IMAGE_CHOOSER = 7; public static final int AUDIO_CHOOSER = 8; public static final int VIDEO_CHOOSER = 9; public static final int EX_STRING_CAPTURE = 10; public static final int EX_INT_CAPTURE = 11; public static final int EX_DECIMAL_CAPTURE = 12; public static final int DRAW_IMAGE = 13; public static final int SIGNATURE_CAPTURE = 14; public static final int ANNOTATE_IMAGE = 15; public static final int ALIGNED_IMAGE = 16; public static final int BEARING_CAPTURE = 17; public static final int EX_GROUP_CAPTURE = 18; // Extra returned from gp activity public static final String LOCATION_RESULT = "LOCATION_RESULT"; public static final String BEARING_RESULT = "BEARING_RESULT"; public static final String KEY_INSTANCES = "instances"; public static final String KEY_SUCCESS = "success"; public static final String KEY_ERROR = "error"; // Identifies the gp of the form used to launch form entry public static final String KEY_FORMPATH = "formpath"; // Identifies whether this is a new form, or reloading a form after a screen // rotation (or similar) private static final String NEWFORM = "newform"; // these are only processed if we shut down and are restoring after an // external intent fires public static final String KEY_INSTANCEPATH = "instancepath"; public static final String KEY_XPATH = "xpath"; public static final String KEY_XPATH_WAITING_FOR_DATA = "xpathwaiting"; // Tracks whether we are autosaving public static final String KEY_AUTO_SAVED = "autosaved"; private static final int MENU_LANGUAGES = Menu.FIRST; private static final int MENU_HIERARCHY_VIEW = Menu.FIRST + 1; private static final int MENU_SAVE = Menu.FIRST + 2; private static final int MENU_PREFERENCES = Menu.FIRST + 3; private static final int PROGRESS_DIALOG = 1; private static final int SAVING_DIALOG = 2; private boolean mAutoSaved; // Random ID private static final int DELETE_REPEAT = 654321; private String mFormPath; private GestureDetector mGestureDetector; private Animation mInAnimation; private Animation mOutAnimation; private View mStaleView = null; private LinearLayout mQuestionHolder; private View mCurrentView; private AlertDialog mAlertDialog; private ProgressDialog mProgressDialog; private String mErrorMessage; // used to limit forward/backward swipes to one per question private boolean mBeenSwiped = false; private final Object saveDialogLock = new Object(); private int viewCount = 0; private FormLoaderTask mFormLoaderTask; private SaveToDiskTask mSaveToDiskTask; private ImageButton mNextButton; private ImageButton mBackButton; private String stepMessage = ""; enum AnimationType { LEFT, RIGHT, FADE } private SharedPreferences mAdminPreferences; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // must be at the beginning of any activity that can be called from an // external intent try { Collect.createODKDirs(); } catch (RuntimeException e) { createErrorDialog(e.getMessage(), EXIT); return; } setContentView(R.layout.form_entry); setTitle(getString(R.string.app_name) + " > " + getString(R.string.loading_form)); mErrorMessage = null; mBeenSwiped = false; mAlertDialog = null; mCurrentView = null; mInAnimation = null; mOutAnimation = null; mGestureDetector = new GestureDetector(this, this); mQuestionHolder = (LinearLayout) findViewById(R.id.questionholder); // get admin preference settings mAdminPreferences = getSharedPreferences( AdminPreferencesActivity.ADMIN_PREFERENCES, 0); mNextButton = (ImageButton) findViewById(R.id.form_forward_button); mNextButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { mBeenSwiped = true; showNextView(); } }); mBackButton = (ImageButton) findViewById(R.id.form_back_button); mBackButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { mBeenSwiped = true; showPreviousView(); } }); String startingXPath = null; String waitingXPath = null; String instancePath = null; Boolean newForm = true; mAutoSaved = false; if (savedInstanceState != null) { if (savedInstanceState.containsKey(KEY_FORMPATH)) { mFormPath = savedInstanceState.getString(KEY_FORMPATH); } if (savedInstanceState.containsKey(KEY_INSTANCEPATH)) { instancePath = savedInstanceState.getString(KEY_INSTANCEPATH); } if (savedInstanceState.containsKey(KEY_XPATH)) { startingXPath = savedInstanceState.getString(KEY_XPATH); Log.i(t, "startingXPath is: " + startingXPath); } if (savedInstanceState.containsKey(KEY_XPATH_WAITING_FOR_DATA)) { waitingXPath = savedInstanceState .getString(KEY_XPATH_WAITING_FOR_DATA); Log.i(t, "waitingXPath is: " + waitingXPath); } if (savedInstanceState.containsKey(NEWFORM)) { newForm = savedInstanceState.getBoolean(NEWFORM, true); } if (savedInstanceState.containsKey(KEY_ERROR)) { mErrorMessage = savedInstanceState.getString(KEY_ERROR); } if (savedInstanceState.containsKey(KEY_AUTO_SAVED)) { mAutoSaved = savedInstanceState.getBoolean(KEY_AUTO_SAVED); } } // If a parse error message is showing then nothing else is loaded // Dialogs mid form just disappear on rotation. if (mErrorMessage != null) { createErrorDialog(mErrorMessage, EXIT); return; } // Check to see if this is a screen flip or a new form load. Object data = getLastNonConfigurationInstance(); if (data instanceof FormLoaderTask) { mFormLoaderTask = (FormLoaderTask) data; } else if (data instanceof SaveToDiskTask) { mSaveToDiskTask = (SaveToDiskTask) data; } else if (data == null) { if (!newForm) { if (Collect.getInstance().getFormController() != null) { refreshCurrentView(); } else { Log.w(t, "Reloading form and restoring state."); // we need to launch the form loader to load the form // controller... mFormLoaderTask = new FormLoaderTask(instancePath, startingXPath, waitingXPath); Collect.getInstance().getActivityLogger() .logAction(this, "formReloaded", mFormPath); // TODO: this doesn' work (dialog does not get removed): // showDialog(PROGRESS_DIALOG); // show dialog before we execute... mFormLoaderTask.execute(mFormPath); } return; } // Not a restart from a screen orientation change (or other). Collect.getInstance().setFormController(null); CompatibilityUtils.invalidateOptionsMenu(this); Intent intent = getIntent(); if (intent != null) { Uri uri = intent.getData(); if (getContentResolver().getType(uri).equals(InstanceColumns.CONTENT_ITEM_TYPE)) { // get the formId and version for this instance... String jrFormId = null; String jrVersion = null; { Cursor instanceCursor = null; try { instanceCursor = getContentResolver().query(uri, null, null, null, null); if (instanceCursor.getCount() != 1) { this.createErrorDialog("Bad URI: " + uri, EXIT); return; } else { instanceCursor.moveToFirst(); instancePath = instanceCursor .getString(instanceCursor .getColumnIndex(InstanceColumns.INSTANCE_FILE_PATH)); Collect.getInstance() .getActivityLogger() .logAction(this, "instanceLoaded", instancePath); jrFormId = instanceCursor .getString(instanceCursor .getColumnIndex(InstanceColumns.JR_FORM_ID)); int idxJrVersion = instanceCursor .getColumnIndex(InstanceColumns.JR_VERSION); jrVersion = instanceCursor.isNull(idxJrVersion) ? null : instanceCursor .getString(idxJrVersion); } } finally { if (instanceCursor != null) { instanceCursor.close(); } } } String[] selectionArgs; String selection; if (jrVersion == null) { selectionArgs = new String[] { jrFormId }; selection = FormsColumns.JR_FORM_ID + "=? AND " + FormsColumns.JR_VERSION + " IS NULL"; } else { selectionArgs = new String[] { jrFormId, jrVersion }; selection = FormsColumns.JR_FORM_ID + "=? AND " + FormsColumns.JR_VERSION + "=?"; } { Cursor formCursor = null; try { formCursor = getContentResolver().query( FormsColumns.CONTENT_URI, null, selection, selectionArgs, null); if (formCursor.getCount() == 1) { formCursor.moveToFirst(); mFormPath = formCursor .getString(formCursor .getColumnIndex(FormsColumns.FORM_FILE_PATH)); } else if (formCursor.getCount() < 1) { this.createErrorDialog( getString( R.string.parent_form_not_present, jrFormId) + ((jrVersion == null) ? "" : "\n" + getString(R.string.version) + " " + jrVersion), EXIT); return; } else if (formCursor.getCount() > 1) { // still take the first entry, but warn that // there are multiple rows. // user will need to hand-edit the SQLite // database to fix it. formCursor.moveToFirst(); mFormPath = formCursor.getString(formCursor.getColumnIndex(FormsColumns.FORM_FILE_PATH)); this.createErrorDialog(getString(R.string.survey_multiple_forms_error), EXIT); return; } } finally { if (formCursor != null) { formCursor.close(); } } } } else if (getContentResolver().getType(uri).equals(FormsColumns.CONTENT_ITEM_TYPE)) { Cursor c = null; try { c = getContentResolver().query(uri, null, null, null, null); if (c.getCount() != 1) { this.createErrorDialog("Bad URI: " + uri, EXIT); return; } else { c.moveToFirst(); mFormPath = c.getString(c.getColumnIndex(FormsColumns.FORM_FILE_PATH)); // This is the fill-blank-form code path. // See if there is a savepoint for this form that // has never been // explicitly saved // by the user. If there is, open this savepoint // (resume this filled-in // form). // Savepoints for forms that were explicitly saved // will be recovered // when that // explicitly saved instance is edited via // edit-saved-form. final String filePrefix = mFormPath.substring( mFormPath.lastIndexOf('/') + 1, mFormPath.lastIndexOf('.')) + "_"; final String fileSuffix = ".xml.save"; File cacheDir = new File(Collect.CACHE_PATH); File[] files = cacheDir.listFiles(new FileFilter() { @Override public boolean accept(File pathname) { String name = pathname.getName(); return name.startsWith(filePrefix) && name.endsWith(fileSuffix); } }); // see if any of these savepoints are for a // filled-in form that has never been // explicitly saved by the user... for (int i = 0; i < files.length; ++i) { File candidate = files[i]; String instanceDirName = candidate.getName() .substring( 0, candidate.getName().length() - fileSuffix.length()); File instanceDir = new File( Collect.INSTANCES_PATH + File.separator + instanceDirName); File instanceFile = new File(instanceDir, instanceDirName + ".xml"); if (instanceDir.exists() && instanceDir.isDirectory() && !instanceFile.exists()) { // yes! -- use this savepoint file instancePath = instanceFile .getAbsolutePath(); break; } } } } finally { if (c != null) { c.close(); } } } else { Log.e(t, "unrecognized URI"); this.createErrorDialog("Unrecognized URI: " + uri, EXIT); return; } mFormLoaderTask = new FormLoaderTask(instancePath, null, null); Collect.getInstance().getActivityLogger() .logAction(this, "formLoaded", mFormPath); showDialog(PROGRESS_DIALOG); // show dialog before we execute... mFormLoaderTask.execute(mFormPath); } } } /** * Create save-points asynchronously in order to not affect swiping performance * on larger forms. */ private void nonblockingCreateSavePointData() { try { SavePointTask savePointTask = new SavePointTask(this); savePointTask.execute(); } catch (Exception e) { Log.e(t, "Could not schedule SavePointTask. Perhaps a lot of swiping is taking place?"); } } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putString(KEY_FORMPATH, mFormPath); FormController formController = Collect.getInstance() .getFormController(); if (formController != null) { outState.putString(KEY_INSTANCEPATH, formController .getInstancePath().getAbsolutePath()); outState.putString(KEY_XPATH, formController.getXPath(formController.getFormIndex())); FormIndex waiting = formController.getIndexWaitingForData(); if (waiting != null) { outState.putString(KEY_XPATH_WAITING_FOR_DATA, formController.getXPath(waiting)); } // save the instance to a temp path... nonblockingCreateSavePointData(); } outState.putBoolean(NEWFORM, false); outState.putString(KEY_ERROR, mErrorMessage); outState.putBoolean(KEY_AUTO_SAVED, mAutoSaved); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent intent) { super.onActivityResult(requestCode, resultCode, intent); FormController formController = Collect.getInstance() .getFormController(); if (formController == null) { // we must be in the midst of a reload of the FormController. // try to save this callback data to the FormLoaderTask if (mFormLoaderTask != null && mFormLoaderTask.getStatus() != AsyncTask.Status.FINISHED) { mFormLoaderTask.setActivityResult(requestCode, resultCode, intent); } else { Log.e(t, "Got an activityResult without any pending form loader"); } return; } if (resultCode == RESULT_CANCELED) { // request was canceled... if (requestCode != HIERARCHY_ACTIVITY) { ((ODKView) mCurrentView).cancelWaitingForBinaryData(); } return; } switch (requestCode) { case BARCODE_CAPTURE: String sb = intent.getStringExtra("SCAN_RESULT"); ((ODKView) mCurrentView).setBinaryData(sb); saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS); break; case EX_STRING_CAPTURE: case EX_INT_CAPTURE: case EX_DECIMAL_CAPTURE: String key = "value"; boolean exists = intent.getExtras().containsKey(key); if (exists) { Object externalValue = intent.getExtras().get(key); ((ODKView) mCurrentView).setBinaryData(externalValue); saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS); } break; case EX_GROUP_CAPTURE: try { Bundle extras = intent.getExtras(); ((ODKView) mCurrentView).setDataForFields(extras); } catch (JavaRosaException e) { Log.e(t, e.getMessage(), e); createErrorDialog(e.getCause().getMessage(), DO_NOT_EXIT); } break; case DRAW_IMAGE: case ANNOTATE_IMAGE: case SIGNATURE_CAPTURE: case IMAGE_CAPTURE: /* * We saved the image to the tempfile_path, but we really want it to * be in: /sdcard/odk/instances/[current instnace]/something.jpg so * we move it there before inserting it into the content provider. * Once the android image capture bug gets fixed, (read, we move on * from Android 1.6) we want to handle images the audio and video */ // The intent is empty, but we know we saved the image to the temp // file File fi = new File(Collect.TMPFILE_PATH); String mInstanceFolder = formController.getInstancePath() .getParent(); String s = mInstanceFolder + File.separator + System.currentTimeMillis() + ".jpg"; File nf = new File(s); if (!fi.renameTo(nf)) { Log.e(t, "Failed to rename " + fi.getAbsolutePath()); } else { Log.i(t, "renamed " + fi.getAbsolutePath() + " to " + nf.getAbsolutePath()); } ((ODKView) mCurrentView).setBinaryData(nf); saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS); break; case ALIGNED_IMAGE: /* * We saved the image to the tempfile_path; the app returns the full * path to the saved file in the EXTRA_OUTPUT extra. Take that file * and move it into the instance folder. */ String path = intent .getStringExtra(android.provider.MediaStore.EXTRA_OUTPUT); fi = new File(path); mInstanceFolder = formController.getInstancePath().getParent(); s = mInstanceFolder + File.separator + System.currentTimeMillis() + ".jpg"; nf = new File(s); if (!fi.renameTo(nf)) { Log.e(t, "Failed to rename " + fi.getAbsolutePath()); } else { Log.i(t, "renamed " + fi.getAbsolutePath() + " to " + nf.getAbsolutePath()); } ((ODKView) mCurrentView).setBinaryData(nf); saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS); break; case IMAGE_CHOOSER: /* * We have a saved image somewhere, but we really want it to be in: * /sdcard/odk/instances/[current instnace]/something.jpg so we move * it there before inserting it into the content provider. Once the * android image capture bug gets fixed, (read, we move on from * Android 1.6) we want to handle images the audio and video */ // get gp of chosen file Uri selectedImage = intent.getData(); String sourceImagePath = MediaUtils.getPathFromUri(this, selectedImage, Images.Media.DATA); // Copy file to sdcard String mInstanceFolder1 = formController.getInstancePath() .getParent(); String destImagePath = mInstanceFolder1 + File.separator + System.currentTimeMillis() + ".jpg"; File source = new File(sourceImagePath); File newImage = new File(destImagePath); FileUtils.copyFile(source, newImage); ((ODKView) mCurrentView).setBinaryData(newImage); saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS); break; case AUDIO_CAPTURE: case VIDEO_CAPTURE: case AUDIO_CHOOSER: case VIDEO_CHOOSER: // For audio/video capture/chooser, we get the URI from the content // provider // then the widget copies the file and makes a new entry in the // content provider. Uri media = intent.getData(); ((ODKView) mCurrentView).setBinaryData(media); saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS); break; case LOCATION_CAPTURE: String sl = intent.getStringExtra(LOCATION_RESULT); ((ODKView) mCurrentView).setBinaryData(sl); saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS); break; case BEARING_CAPTURE: String bearing = intent.getStringExtra(BEARING_RESULT); ((ODKView) mCurrentView).setBinaryData(bearing); saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS); case HIERARCHY_ACTIVITY: // We may have jumped to a new index in hierarchy activity, so // refresh break; } refreshCurrentView(); } /** * Refreshes the current view. the controller and the displayed view can get * out of sync due to dialogs and restarts caused by screen orientation * changes, so they're resynchronized here. */ public void refreshCurrentView() { FormController formController = Collect.getInstance() .getFormController(); int event = formController.getEvent(); // When we refresh, repeat dialog state isn't maintained, so step back // to the previous // question. // Also, if we're within a group labeled 'field list', step back to the // beginning of that // group. // That is, skip backwards over repeat prompts, groups that are not // field-lists, // repeat events, and indexes in field-lists that is not the containing // group. if (event == FormEntryController.EVENT_PROMPT_NEW_REPEAT) { createRepeatDialog(); } else { View current = createView(event, false); showView(current, AnimationType.FADE); } } @Override public boolean onCreateOptionsMenu(Menu menu) { Collect.getInstance().getActivityLogger() .logInstanceAction(this, "onCreateOptionsMenu", "show"); super.onCreateOptionsMenu(menu); CompatibilityUtils.setShowAsAction( menu.add(0, MENU_SAVE, 0, R.string.save_all_answers).setIcon( android.R.drawable.ic_menu_save), MenuItem.SHOW_AS_ACTION_IF_ROOM); CompatibilityUtils.setShowAsAction( menu.add(0, MENU_HIERARCHY_VIEW, 0, R.string.view_hierarchy) .setIcon(R.drawable.ic_menu_goto), MenuItem.SHOW_AS_ACTION_IF_ROOM); CompatibilityUtils.setShowAsAction( menu.add(0, MENU_LANGUAGES, 0, R.string.change_language) .setIcon(R.drawable.ic_menu_start_conversation), MenuItem.SHOW_AS_ACTION_NEVER); CompatibilityUtils.setShowAsAction( menu.add(0, MENU_PREFERENCES, 0, R.string.general_preferences) .setIcon(R.drawable.ic_menu_preferences), MenuItem.SHOW_AS_ACTION_NEVER); return true; } @Override public boolean onPrepareOptionsMenu(Menu menu) { super.onPrepareOptionsMenu(menu); FormController formController = Collect.getInstance() .getFormController(); boolean useability; useability = mAdminPreferences.getBoolean( AdminPreferencesActivity.KEY_SAVE_MID, true); menu.findItem(MENU_SAVE).setVisible(useability).setEnabled(useability); useability = mAdminPreferences.getBoolean( AdminPreferencesActivity.KEY_JUMP_TO, true); menu.findItem(MENU_HIERARCHY_VIEW).setVisible(useability) .setEnabled(useability); useability = mAdminPreferences.getBoolean( AdminPreferencesActivity.KEY_CHANGE_LANGUAGE, true) && (formController != null) && formController.getLanguages() != null && formController.getLanguages().length > 1; menu.findItem(MENU_LANGUAGES).setVisible(useability) .setEnabled(useability); useability = mAdminPreferences.getBoolean( AdminPreferencesActivity.KEY_ACCESS_SETTINGS, true); menu.findItem(MENU_PREFERENCES).setVisible(useability) .setEnabled(useability); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { FormController formController = Collect.getInstance() .getFormController(); switch (item.getItemId()) { case MENU_LANGUAGES: Collect.getInstance() .getActivityLogger() .logInstanceAction(this, "onOptionsItemSelected", "MENU_LANGUAGES"); createLanguageDialog(); return true; case MENU_SAVE: Collect.getInstance() .getActivityLogger() .logInstanceAction(this, "onOptionsItemSelected", "MENU_SAVE"); // don't exit saveDataToDisk(DO_NOT_EXIT, isInstanceComplete(false), null); return true; case MENU_HIERARCHY_VIEW: Collect.getInstance() .getActivityLogger() .logInstanceAction(this, "onOptionsItemSelected", "MENU_HIERARCHY_VIEW"); if (formController.currentPromptIsQuestion()) { saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS); } Intent i = new Intent(this, FormHierarchyActivity.class); startActivityForResult(i, HIERARCHY_ACTIVITY); return true; case MENU_PREFERENCES: Collect.getInstance() .getActivityLogger() .logInstanceAction(this, "onOptionsItemSelected", "MENU_PREFERENCES"); Intent pref = new Intent(this, PreferencesActivity.class); startActivity(pref); return true; } return super.onOptionsItemSelected(item); } /** * Attempt to save the answer(s) in the current screen to into the data * model. * * @param evaluateConstraints * @return false if any error occurs while saving (constraint violated, * etc...), true otherwise. */ private boolean saveAnswersForCurrentScreen(boolean evaluateConstraints) { FormController formController = Collect.getInstance() .getFormController(); // only try to save if the current event is a question or a field-list // group if (formController.currentPromptIsQuestion()) { LinkedHashMap<FormIndex, IAnswerData> answers = ((ODKView) mCurrentView) .getAnswers(); try { FailedConstraint constraint = formController.saveAllScreenAnswers(answers, evaluateConstraints); if (constraint != null) { createConstraintToast(constraint.index, constraint.status); return false; } } catch (JavaRosaException e) { Log.e(t, e.getMessage(), e); createErrorDialog(e.getCause().getMessage(), DO_NOT_EXIT); return false; } } return true; } /** * Clears the answer on the screen. */ private void clearAnswer(QuestionWidget qw) { if (qw.getAnswer() != null) { qw.clearAnswer(); } } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); Collect.getInstance().getActivityLogger() .logInstanceAction(this, "onCreateContextMenu", "show"); FormController formController = Collect.getInstance() .getFormController(); menu.add(0, v.getId(), 0, getString(R.string.clear_answer)); if (formController.indexContainsRepeatableGroup()) { menu.add(0, DELETE_REPEAT, 0, getString(R.string.delete_repeat)); } menu.setHeaderTitle(getString(R.string.edit_prompt)); } @Override public boolean onContextItemSelected(MenuItem item) { /* * We don't have the right view here, so we store the View's ID as the * item ID and loop through the possible views to find the one the user * clicked on. */ for (QuestionWidget qw : ((ODKView) mCurrentView).getWidgets()) { if (item.getItemId() == qw.getId()) { Collect.getInstance() .getActivityLogger() .logInstanceAction(this, "onContextItemSelected", "createClearDialog", qw.getPrompt().getIndex()); createClearDialog(qw); } } if (item.getItemId() == DELETE_REPEAT) { Collect.getInstance() .getActivityLogger() .logInstanceAction(this, "onContextItemSelected", "createDeleteRepeatConfirmDialog"); createDeleteRepeatConfirmDialog(); } return super.onContextItemSelected(item); } /** * If we're loading, then we pass the loading thread to our next instance. */ @Override public Object onRetainNonConfigurationInstance() { FormController formController = Collect.getInstance() .getFormController(); // if a form is loading, pass the loader task if (mFormLoaderTask != null && mFormLoaderTask.getStatus() != AsyncTask.Status.FINISHED) return mFormLoaderTask; // if a form is writing to disk, pass the save to disk task if (mSaveToDiskTask != null && mSaveToDiskTask.getStatus() != AsyncTask.Status.FINISHED) return mSaveToDiskTask; // mFormEntryController is static so we don't need to pass it. if (formController != null && formController.currentPromptIsQuestion()) { saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS); } return null; } /** * Creates a view given the View type and an event * * @param event * @param advancingPage * -- true if this results from advancing through the form * @return newly created View */ private View createView(int event, boolean advancingPage) { FormController formController = Collect.getInstance() .getFormController(); setTitle(getString(R.string.app_name) + " > " + formController.getFormTitle()); switch (event) { case FormEntryController.EVENT_BEGINNING_OF_FORM: View startView = View .inflate(this, R.layout.form_entry_start, null); setTitle(getString(R.string.app_name) + " > " + formController.getFormTitle()); Drawable image = null; File mediaFolder = formController.getMediaFolder(); String mediaDir = mediaFolder.getAbsolutePath(); BitmapDrawable bitImage = null; // attempt to load the form-specific logo... // this is arbitrarily silly bitImage = new BitmapDrawable(getResources(), mediaDir + File.separator + "form_logo.png"); if (bitImage != null && bitImage.getBitmap() != null && bitImage.getIntrinsicHeight() > 0 && bitImage.getIntrinsicWidth() > 0) { image = bitImage; } if (image == null) { // show the opendatakit zig... // image = // getResources().getDrawable(R.drawable.opendatakit_zig); ((ImageView) startView.findViewById(R.id.form_start_bling)) .setVisibility(View.GONE); } else { ImageView v = ((ImageView) startView .findViewById(R.id.form_start_bling)); v.setImageDrawable(image); v.setContentDescription(formController.getFormTitle()); } // change start screen based on navigation prefs String navigationChoice = PreferenceManager .getDefaultSharedPreferences(this).getString( PreferencesActivity.KEY_NAVIGATION, PreferencesActivity.KEY_NAVIGATION); Boolean useSwipe = false; Boolean useButtons = false; ImageView ia = ((ImageView) startView .findViewById(R.id.image_advance)); ImageView ib = ((ImageView) startView .findViewById(R.id.image_backup)); TextView ta = ((TextView) startView.findViewById(R.id.text_advance)); TextView tb = ((TextView) startView.findViewById(R.id.text_backup)); TextView d = ((TextView) startView.findViewById(R.id.description)); if (navigationChoice != null) { if (navigationChoice .contains(PreferencesActivity.NAVIGATION_SWIPE)) { useSwipe = true; } if (navigationChoice .contains(PreferencesActivity.NAVIGATION_BUTTONS)) { useButtons = true; } } if (useSwipe && !useButtons) { d.setText(getString(R.string.swipe_instructions, formController.getFormTitle())); } else if (useButtons && !useSwipe) { ia.setVisibility(View.GONE); ib.setVisibility(View.GONE); ta.setVisibility(View.GONE); tb.setVisibility(View.GONE); d.setText(getString(R.string.buttons_instructions, formController.getFormTitle())); } else { d.setText(getString(R.string.swipe_buttons_instructions, formController.getFormTitle())); } if (mBackButton.isShown()) { mBackButton.setEnabled(false); } if (mNextButton.isShown()) { mNextButton.setEnabled(true); } return startView; case FormEntryController.EVENT_END_OF_FORM: View endView = View.inflate(this, R.layout.form_entry_end, null); ((TextView) endView.findViewById(R.id.description)) .setText(getString(R.string.save_enter_data_description, formController.getFormTitle())); // checkbox for if finished or ready to send final CheckBox instanceComplete = ((CheckBox) endView .findViewById(R.id.mark_finished)); instanceComplete.setChecked(isInstanceComplete(true)); if (!mAdminPreferences.getBoolean( AdminPreferencesActivity.KEY_MARK_AS_FINALIZED, true)) { instanceComplete.setVisibility(View.GONE); } // edittext to change the displayed name of the instance final EditText saveAs = (EditText) endView .findViewById(R.id.save_name); // disallow carriage returns in the name InputFilter returnFilter = new InputFilter() { public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) { for (int i = start; i < end; i++) { if (Character.getType((source.charAt(i))) == Character.CONTROL) { return ""; } } return null; } }; saveAs.setFilters(new InputFilter[] { returnFilter }); String saveName = formController.getSubmissionMetadata().instanceName; if (saveName == null) { // no meta/instanceName field in the form -- see if we have a // name for this instance from a previous save attempt... if (getContentResolver().getType(getIntent().getData()) == InstanceColumns.CONTENT_ITEM_TYPE) { Uri instanceUri = getIntent().getData(); Cursor instance = null; try { instance = getContentResolver().query(instanceUri, null, null, null, null); if (instance.getCount() == 1) { instance.moveToFirst(); saveName = instance .getString(instance .getColumnIndex(InstanceColumns.DISPLAY_NAME)); } } finally { if (instance != null) { instance.close(); } } } if (saveName == null) { // last resort, default to the form title saveName = formController.getFormTitle(); } // present the prompt to allow user to name the form TextView sa = (TextView) endView .findViewById(R.id.save_form_as); sa.setVisibility(View.VISIBLE); saveAs.setText(saveName); saveAs.setEnabled(true); saveAs.setVisibility(View.VISIBLE); } else { // if instanceName is defined in form, this is the name -- no // revisions // display only the name, not the prompt, and disable edits TextView sa = (TextView) endView .findViewById(R.id.save_form_as); sa.setVisibility(View.GONE); saveAs.setText(saveName); saveAs.setEnabled(false); saveAs.setBackgroundColor(Color.WHITE); saveAs.setVisibility(View.VISIBLE); } // override the visibility settings based upon admin preferences if (!mAdminPreferences.getBoolean( AdminPreferencesActivity.KEY_SAVE_AS, true)) { saveAs.setVisibility(View.GONE); TextView sa = (TextView) endView .findViewById(R.id.save_form_as); sa.setVisibility(View.GONE); } // Create 'save' button ((Button) endView.findViewById(R.id.save_exit_button)) .setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Collect.getInstance() .getActivityLogger() .logInstanceAction( this, "createView.saveAndExit", instanceComplete.isChecked() ? "saveAsComplete" : "saveIncomplete"); // Form is marked as 'saved' here. if (saveAs.getText().length() < 1) { Toast.makeText(FormEntryActivity.this, R.string.save_as_error, Toast.LENGTH_SHORT).show(); } else { saveDataToDisk(EXIT, instanceComplete .isChecked(), saveAs.getText() .toString()); } } }); if (mBackButton.isShown()) { mBackButton.setEnabled(true); } if (mNextButton.isShown()) { mNextButton.setEnabled(false); } return endView; case FormEntryController.EVENT_QUESTION: case FormEntryController.EVENT_GROUP: case FormEntryController.EVENT_REPEAT: ODKView odkv = null; // should only be a group here if the event_group is a field-list try { FormEntryPrompt[] prompts = formController.getQuestionPrompts(); FormEntryCaption[] groups = formController .getGroupsForCurrentIndex(); odkv = new ODKView(this, formController.getQuestionPrompts(), groups, advancingPage); Log.i(t, "created view for group " + (groups.length > 0 ? groups[groups.length - 1] .getLongText() : "[top]") + " " + (prompts.length > 0 ? prompts[0] .getQuestionText() : "[no question]")); } catch (RuntimeException e) { Log.e(t, e.getMessage(), e); // this is badness to avoid a crash. try { event = formController.stepToNextScreenEvent(); createErrorDialog(e.getMessage(), DO_NOT_EXIT); } catch (JavaRosaException e1) { Log.e(t, e1.getMessage(), e1); createErrorDialog(e.getMessage() + "\n\n" + e1.getCause().getMessage(), DO_NOT_EXIT); } return createView(event, advancingPage); } // Makes a "clear answer" menu pop up on long-click for (QuestionWidget qw : odkv.getWidgets()) { if (!qw.getPrompt().isReadOnly()) { registerForContextMenu(qw); } } if (mBackButton.isShown() && mNextButton.isShown()) { mBackButton.setEnabled(true); mNextButton.setEnabled(true); } return odkv; default: Log.e(t, "Attempted to create a view that does not exist."); // this is badness to avoid a crash. try { event = formController.stepToNextScreenEvent(); createErrorDialog(getString(R.string.survey_internal_error), EXIT); } catch (JavaRosaException e) { Log.e(t, e.getMessage(), e); createErrorDialog(e.getCause().getMessage(), EXIT); } return createView(event, advancingPage); } } @Override public boolean dispatchTouchEvent(MotionEvent mv) { boolean handled = mGestureDetector.onTouchEvent(mv); if (!handled) { return super.dispatchTouchEvent(mv); } return handled; // this is always true } /** * Determines what should be displayed on the screen. Possible options are: * a question, an ask repeat dialog, or the submit screen. Also saves * answers to the data model after checking constraints. */ private void showNextView() { try { FormController formController = Collect.getInstance() .getFormController(); // get constraint behavior preference value with appropriate default String constraint_behavior = PreferenceManager.getDefaultSharedPreferences(this) .getString(PreferencesActivity.KEY_CONSTRAINT_BEHAVIOR, PreferencesActivity.CONSTRAINT_BEHAVIOR_DEFAULT); if (formController.currentPromptIsQuestion()) { // if constraint behavior says we should validate on swipe, do so if (constraint_behavior.equals(PreferencesActivity.CONSTRAINT_BEHAVIOR_ON_SWIPE)) { if (!saveAnswersForCurrentScreen(EVALUATE_CONSTRAINTS)) { // A constraint was violated so a dialog should be showing. mBeenSwiped = false; return; } // otherwise, just save without validating (constraints will be validated on finalize) } else saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS); } View next; int event = formController.stepToNextScreenEvent(); switch (event) { case FormEntryController.EVENT_QUESTION: case FormEntryController.EVENT_GROUP: // create a savepoint if ((++viewCount) % SAVEPOINT_INTERVAL == 0) { nonblockingCreateSavePointData(); } next = createView(event, true); showView(next, AnimationType.RIGHT); break; case FormEntryController.EVENT_END_OF_FORM: case FormEntryController.EVENT_REPEAT: next = createView(event, true); showView(next, AnimationType.RIGHT); break; case FormEntryController.EVENT_PROMPT_NEW_REPEAT: createRepeatDialog(); break; case FormEntryController.EVENT_REPEAT_JUNCTURE: Log.i(t, "repeat juncture: " + formController.getFormIndex().getReference()); // skip repeat junctures until we implement them break; default: Log.w(t, "JavaRosa added a new EVENT type and didn't tell us... shame on them."); break; } } catch (JavaRosaException e) { Log.e(t, e.getMessage(), e); createErrorDialog(e.getCause().getMessage(), DO_NOT_EXIT); } } /** * Determines what should be displayed between a question, or the start * screen and displays the appropriate view. Also saves answers to the data * model without checking constraints. */ private void showPreviousView() { try { FormController formController = Collect.getInstance() .getFormController(); // The answer is saved on a back swipe, but question constraints are // ignored. if (formController.currentPromptIsQuestion()) { saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS); } if (formController.getEvent() != FormEntryController.EVENT_BEGINNING_OF_FORM) { int event = formController.stepToPreviousScreenEvent(); if (event == FormEntryController.EVENT_BEGINNING_OF_FORM || event == FormEntryController.EVENT_GROUP || event == FormEntryController.EVENT_QUESTION) { // create savepoint if ((++viewCount) % SAVEPOINT_INTERVAL == 0) { nonblockingCreateSavePointData(); } } View next = createView(event, false); showView(next, AnimationType.LEFT); } else { mBeenSwiped = false; } } catch (JavaRosaException e) { Log.e(t, e.getMessage(), e); createErrorDialog(e.getCause().getMessage(), DO_NOT_EXIT); } } /** * Displays the View specified by the parameter 'next', animating both the * current view and next appropriately given the AnimationType. Also updates * the progress bar. */ public void showView(View next, AnimationType from) { // disable notifications... if (mInAnimation != null) { mInAnimation.setAnimationListener(null); } if (mOutAnimation != null) { mOutAnimation.setAnimationListener(null); } // logging of the view being shown is already done, as this was handled // by createView() switch (from) { case RIGHT: mInAnimation = AnimationUtils.loadAnimation(this, R.anim.push_left_in); mOutAnimation = AnimationUtils.loadAnimation(this, R.anim.push_left_out); // if animation is left or right then it was a swipe, and we want to re-save on entry mAutoSaved = false; break; case LEFT: mInAnimation = AnimationUtils.loadAnimation(this, R.anim.push_right_in); mOutAnimation = AnimationUtils.loadAnimation(this, R.anim.push_right_out); mAutoSaved = false; break; case FADE: mInAnimation = AnimationUtils.loadAnimation(this, R.anim.fade_in); mOutAnimation = AnimationUtils.loadAnimation(this, R.anim.fade_out); break; } // complete setup for animations... mInAnimation.setAnimationListener(this); mOutAnimation.setAnimationListener(this); // drop keyboard before transition... if (mCurrentView != null) { InputMethodManager inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); inputManager.hideSoftInputFromWindow(mCurrentView.getWindowToken(), 0); } RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams( LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT); // adjust which view is in the layout container... mStaleView = mCurrentView; mCurrentView = next; mQuestionHolder.addView(mCurrentView, lp); mAnimationCompletionSet = 0; if (mStaleView != null) { // start OutAnimation for transition... mStaleView.startAnimation(mOutAnimation); // and remove the old view (MUST occur after start of animation!!!) mQuestionHolder.removeView(mStaleView); } else { mAnimationCompletionSet = 2; } // start InAnimation for transition... mCurrentView.startAnimation(mInAnimation); String logString = ""; switch (from) { case RIGHT: logString = "next"; break; case LEFT: logString = "previous"; break; case FADE: logString = "refresh"; break; } Collect.getInstance().getActivityLogger().logInstanceAction(this, "showView", logString); FormController formController = Collect.getInstance().getFormController(); if (formController.getEvent() == FormEntryController.EVENT_QUESTION || formController.getEvent() == FormEntryController.EVENT_GROUP || formController.getEvent() == FormEntryController.EVENT_REPEAT) { FormEntryPrompt[] prompts = Collect.getInstance().getFormController() .getQuestionPrompts(); for (FormEntryPrompt p : prompts) { List<TreeElement> attrs = p.getBindAttributes(); for (int i = 0; i < attrs.size(); i++) { if (!mAutoSaved && "saveIncomplete".equals(attrs.get(i).getName())) { saveDataToDisk(false, false, null, false); mAutoSaved = true; } } } } } // Hopefully someday we can use managed dialogs when the bugs are fixed /* * Ideally, we'd like to use Android to manage dialogs with onCreateDialog() * and onPrepareDialog(), but dialogs with dynamic content are broken in 1.5 * (cupcake). We do use managed dialogs for our static loading * ProgressDialog. The main issue we noticed and are waiting to see fixed * is: onPrepareDialog() is not called after a screen orientation change. * http://code.google.com/p/android/issues/detail?id=1639 */ // /** * Creates and displays a dialog displaying the violated constraint. */ private void createConstraintToast(FormIndex index, int saveStatus) { FormController formController = Collect.getInstance() .getFormController(); String constraintText; switch (saveStatus) { case FormEntryController.ANSWER_CONSTRAINT_VIOLATED: Collect.getInstance() .getActivityLogger() .logInstanceAction(this, "createConstraintToast.ANSWER_CONSTRAINT_VIOLATED", "show", index); constraintText = formController .getQuestionPromptConstraintText(index); if (constraintText == null) { constraintText = formController.getQuestionPrompt(index) .getSpecialFormQuestionText("constraintMsg"); if (constraintText == null) { constraintText = getString(R.string.invalid_answer_error); } } break; case FormEntryController.ANSWER_REQUIRED_BUT_EMPTY: Collect.getInstance() .getActivityLogger() .logInstanceAction(this, "createConstraintToast.ANSWER_REQUIRED_BUT_EMPTY", "show", index); constraintText = formController .getQuestionPromptRequiredText(index); if (constraintText == null) { constraintText = formController.getQuestionPrompt(index) .getSpecialFormQuestionText("requiredMsg"); if (constraintText == null) { constraintText = getString(R.string.required_answer_error); } } break; default: return; } showCustomToast(constraintText, Toast.LENGTH_SHORT); } /** * Creates a toast with the specified message. * * @param message */ private void showCustomToast(String message, int duration) { LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE); View view = inflater.inflate(R.layout.toast_view, null); // set the text in the view TextView tv = (TextView) view.findViewById(R.id.message); tv.setText(message); Toast t = new Toast(this); t.setView(view); t.setDuration(duration); t.setGravity(Gravity.CENTER, 0, 0); t.show(); } /** * Creates and displays a dialog asking the user if they'd like to create a * repeat of the current group. */ private void createRepeatDialog() { FormController formController = Collect.getInstance() .getFormController(); Collect.getInstance().getActivityLogger() .logInstanceAction(this, "createRepeatDialog", "show"); mAlertDialog = new AlertDialog.Builder(this).create(); mAlertDialog.setIcon(android.R.drawable.ic_dialog_info); DialogInterface.OnClickListener repeatListener = new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int i) { FormController formController = Collect.getInstance() .getFormController(); switch (i) { case DialogInterface.BUTTON_POSITIVE: // yes, repeat Collect.getInstance() .getActivityLogger() .logInstanceAction(this, "createRepeatDialog", "addRepeat"); try { formController.newRepeat(); } catch (Exception e) { FormEntryActivity.this.createErrorDialog( e.getMessage(), DO_NOT_EXIT); return; } if (!formController.indexIsInFieldList()) { // we are at a REPEAT event that does not have a // field-list appearance // step to the next visible field... // which could be the start of a new repeat group... showNextView(); } else { // we are at a REPEAT event that has a field-list // appearance // just display this REPEAT event's group. refreshCurrentView(); } break; case DialogInterface. BUTTON_NEGATIVE: // no, no repeat Collect.getInstance() .getActivityLogger() .logInstanceAction(this, "createRepeatDialog", "showNext"); // // Make sure the error dialog will not disappear. // // When showNextView() popups an error dialog (because of a JavaRosaException) // the issue is that the "add new repeat dialog" is referenced by mAlertDialog // like the error dialog. When the "no repeat" is clicked, the error dialog // is shown. Android by default dismisses the dialogs when a button is clicked, // so instead of closing the first dialog, it closes the second. new Thread() { @Override public void run() { FormEntryActivity.this.runOnUiThread(new Runnable() { @Override public void run() { try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } showNextView(); } }); } }.start(); break; } } }; if (formController.getLastRepeatCount() > 0) { mAlertDialog.setTitle(getString(R.string.leaving_repeat_ask)); mAlertDialog.setMessage(getString(R.string.add_another_repeat, formController.getLastGroupText())); mAlertDialog.setButton(getString(R.string.add_another), repeatListener); mAlertDialog.setButton2(getString(R.string.leave_repeat_yes), repeatListener); } else { mAlertDialog.setTitle(getString(R.string.entering_repeat_ask)); mAlertDialog.setMessage(getString(R.string.add_repeat, formController.getLastGroupText())); mAlertDialog.setButton(getString(R.string.entering_repeat), repeatListener); mAlertDialog.setButton2(getString(R.string.add_repeat_no), repeatListener); } mAlertDialog.setCancelable(false); mBeenSwiped = false; mAlertDialog.show(); } /** * Creates and displays dialog with the given errorMsg. */ private void createErrorDialog(String errorMsg, final boolean shouldExit) { Collect.getInstance() .getActivityLogger() .logInstanceAction(this, "createErrorDialog", "show." + Boolean.toString(shouldExit)); if (mAlertDialog != null && mAlertDialog.isShowing()) { errorMsg = mErrorMessage + "\n\n" + errorMsg; mErrorMessage = errorMsg; } else { mAlertDialog = new AlertDialog.Builder(this).create(); mErrorMessage = errorMsg; } mAlertDialog.setIcon(android.R.drawable.ic_dialog_info); mAlertDialog.setTitle(getString(R.string.error_occured)); mAlertDialog.setMessage(errorMsg); DialogInterface.OnClickListener errorListener = new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int i) { switch (i) { case DialogInterface.BUTTON_POSITIVE: Collect.getInstance().getActivityLogger() .logInstanceAction(this, "createErrorDialog", "OK"); if (shouldExit) { mErrorMessage = null; finish(); } break; } } }; mAlertDialog.setCancelable(false); mAlertDialog.setButton(getString(R.string.ok), errorListener); mBeenSwiped = false; mAlertDialog.show(); } /** * Creates a confirm/cancel dialog for deleting repeats. */ private void createDeleteRepeatConfirmDialog() { Collect.getInstance() .getActivityLogger() .logInstanceAction(this, "createDeleteRepeatConfirmDialog", "show"); FormController formController = Collect.getInstance() .getFormController(); mAlertDialog = new AlertDialog.Builder(this).create(); mAlertDialog.setIcon(android.R.drawable.ic_dialog_info); String name = formController.getLastRepeatedGroupName(); int repeatcount = formController.getLastRepeatedGroupRepeatCount(); if (repeatcount != -1) { name += " (" + (repeatcount + 1) + ")"; } mAlertDialog.setTitle(getString(R.string.delete_repeat_ask)); mAlertDialog .setMessage(getString(R.string.delete_repeat_confirm, name)); DialogInterface.OnClickListener quitListener = new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int i) { FormController formController = Collect.getInstance() .getFormController(); switch (i) { case DialogInterface.BUTTON_POSITIVE: // yes Collect.getInstance() .getActivityLogger() .logInstanceAction(this, "createDeleteRepeatConfirmDialog", "OK"); formController.deleteRepeat(); showPreviousView(); break; case DialogInterface. BUTTON_NEGATIVE: // no Collect.getInstance() .getActivityLogger() .logInstanceAction(this, "createDeleteRepeatConfirmDialog", "cancel"); break; } } }; mAlertDialog.setCancelable(false); mAlertDialog.setButton(getString(R.string.discard_group), quitListener); mAlertDialog.setButton2(getString(R.string.delete_repeat_no), quitListener); mAlertDialog.show(); } /** * Saves data and writes it to disk. If exit is set, program will exit after * save completes. Complete indicates whether the user has marked the * isntancs as complete. If updatedSaveName is non-null, the instances * content provider is updated with the new name */ // by default, save the current screen private boolean saveDataToDisk(boolean exit, boolean complete, String updatedSaveName) { return saveDataToDisk(exit, complete, updatedSaveName, true); } // but if you want save in the background, can't be current screen private boolean saveDataToDisk(boolean exit, boolean complete, String updatedSaveName, boolean current) { // save current answer if (current) { if (!saveAnswersForCurrentScreen(complete)) { Toast.makeText(this, getString(R.string.data_saved_error), Toast.LENGTH_SHORT) .show(); return false; } } synchronized (saveDialogLock) { mSaveToDiskTask = new SaveToDiskTask(getIntent().getData(), exit, complete, updatedSaveName); mSaveToDiskTask.setFormSavedListener(this); mAutoSaved = true; showDialog(SAVING_DIALOG); // show dialog before we execute... mSaveToDiskTask.execute(); } return true; } /** * Create a dialog with options to save and exit, save, or quit without * saving */ private void createQuitDialog() { String title; { FormController formController = Collect.getInstance().getFormController(); title = (formController == null) ? null : formController.getFormTitle(); if ( title == null ) { title = "<no form loaded>"; } } String[] items; if (mAdminPreferences.getBoolean(AdminPreferencesActivity.KEY_SAVE_MID, true)) { String[] two = { getString(R.string.keep_changes), getString(R.string.do_not_save) }; items = two; } else { String[] one = { getString(R.string.do_not_save) }; items = one; } Collect.getInstance().getActivityLogger() .logInstanceAction(this, "createQuitDialog", "show"); mAlertDialog = new AlertDialog.Builder(this) .setIcon(android.R.drawable.ic_dialog_info) .setTitle( getString(R.string.quit_application, title)) .setNeutralButton(getString(R.string.do_not_exit), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int id) { Collect.getInstance() .getActivityLogger() .logInstanceAction(this, "createQuitDialog", "cancel"); dialog.cancel(); } }) .setItems(items, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { switch (which) { case 0: // save and exit // this is slightly complicated because if the // option is disabled in // the admin menu, then case 0 actually becomes // 'discard and exit' // whereas if it's enabled it's 'save and exit' if (mAdminPreferences .getBoolean( AdminPreferencesActivity.KEY_SAVE_MID, true)) { Collect.getInstance() .getActivityLogger() .logInstanceAction(this, "createQuitDialog", "saveAndExit"); saveDataToDisk(EXIT, isInstanceComplete(false), null); } else { Collect.getInstance() .getActivityLogger() .logInstanceAction(this, "createQuitDialog", "discardAndExit"); removeTempInstance(); finishReturnInstance(); } break; case 1: // discard changes and exit Collect.getInstance() .getActivityLogger() .logInstanceAction(this, "createQuitDialog", "discardAndExit"); // close all open databases of external data. Collect.getInstance().getExternalDataManager().close(); removeTempInstance(); finishReturnInstance(); break; case 2:// do nothing Collect.getInstance() .getActivityLogger() .logInstanceAction(this, "createQuitDialog", "cancel"); break; } } }).create(); mAlertDialog.show(); } /** * this method cleans up unneeded files when the user selects 'discard and * exit' */ private void removeTempInstance() { FormController formController = Collect.getInstance() .getFormController(); // attempt to remove any scratch file File temp = SaveToDiskTask.savepointFile(formController .getInstancePath()); if (temp.exists()) { temp.delete(); } String selection = InstanceColumns.INSTANCE_FILE_PATH + "=?"; String[] selectionArgs = { formController.getInstancePath() .getAbsolutePath() }; boolean erase = false; { Cursor c = null; try { c = getContentResolver().query(InstanceColumns.CONTENT_URI, null, selection, selectionArgs, null); erase = (c.getCount() < 1); } finally { if (c != null) { c.close(); } } } // if it's not already saved, erase everything if (erase) { // delete media first String instanceFolder = formController.getInstancePath() .getParent(); Log.i(t, "attempting to delete: " + instanceFolder); int images = MediaUtils .deleteImagesInFolderFromMediaProvider(formController .getInstancePath().getParentFile()); int audio = MediaUtils .deleteAudioInFolderFromMediaProvider(formController .getInstancePath().getParentFile()); int video = MediaUtils .deleteVideoInFolderFromMediaProvider(formController .getInstancePath().getParentFile()); Log.i(t, "removed from content providers: " + images + " image files, " + audio + " audio files," + " and " + video + " video files."); File f = new File(instanceFolder); if (f.exists() && f.isDirectory()) { for (File del : f.listFiles()) { Log.i(t, "deleting file: " + del.getAbsolutePath()); del.delete(); } f.delete(); } } } /** * Confirm clear answer dialog */ private void createClearDialog(final QuestionWidget qw) { Collect.getInstance() .getActivityLogger() .logInstanceAction(this, "createClearDialog", "show", qw.getPrompt().getIndex()); mAlertDialog = new AlertDialog.Builder(this).create(); mAlertDialog.setIcon(android.R.drawable.ic_dialog_info); mAlertDialog.setTitle(getString(R.string.clear_answer_ask)); String question = qw.getPrompt().getLongText(); if (question == null) { question = ""; } if (question.length() > 50) { question = question.substring(0, 50) + "..."; } mAlertDialog.setMessage(getString(R.string.clearanswer_confirm, question)); DialogInterface.OnClickListener quitListener = new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int i) { switch (i) { case DialogInterface.BUTTON_POSITIVE: // yes Collect.getInstance() .getActivityLogger() .logInstanceAction(this, "createClearDialog", "clearAnswer", qw.getPrompt().getIndex()); clearAnswer(qw); saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS); break; case DialogInterface. BUTTON_NEGATIVE: // no Collect.getInstance() .getActivityLogger() .logInstanceAction(this, "createClearDialog", "cancel", qw.getPrompt().getIndex()); break; } } }; mAlertDialog.setCancelable(false); mAlertDialog .setButton(getString(R.string.discard_answer), quitListener); mAlertDialog.setButton2(getString(R.string.clear_answer_no), quitListener); mAlertDialog.show(); } /** * Creates and displays a dialog allowing the user to set the language for * the form. */ private void createLanguageDialog() { Collect.getInstance().getActivityLogger() .logInstanceAction(this, "createLanguageDialog", "show"); FormController formController = Collect.getInstance() .getFormController(); final String[] languages = formController.getLanguages(); int selected = -1; if (languages != null) { String language = formController.getLanguage(); for (int i = 0; i < languages.length; i++) { if (language.equals(languages[i])) { selected = i; } } } mAlertDialog = new AlertDialog.Builder(this) .setSingleChoiceItems(languages, selected, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int whichButton) { FormController formController = Collect .getInstance().getFormController(); // Update the language in the content provider // when selecting a new // language ContentValues values = new ContentValues(); values.put(FormsColumns.LANGUAGE, languages[whichButton]); String selection = FormsColumns.FORM_FILE_PATH + "=?"; String selectArgs[] = { mFormPath }; int updated = getContentResolver().update( FormsColumns.CONTENT_URI, values, selection, selectArgs); Log.i(t, "Updated language to: " + languages[whichButton] + " in " + updated + " rows"); Collect.getInstance() .getActivityLogger() .logInstanceAction( this, "createLanguageDialog", "changeLanguage." + languages[whichButton]); formController .setLanguage(languages[whichButton]); dialog.dismiss(); if (formController.currentPromptIsQuestion()) { saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS); } refreshCurrentView(); } }) .setTitle(getString(R.string.change_language)) .setNegativeButton(getString(R.string.do_not_change), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int whichButton) { Collect.getInstance() .getActivityLogger() .logInstanceAction(this, "createLanguageDialog", "cancel"); } }).create(); mAlertDialog.show(); } /** * We use Android's dialog management for loading/saving progress dialogs */ @Override protected Dialog onCreateDialog(int id) { switch (id) { case PROGRESS_DIALOG: Log.e(t, "Creating PROGRESS_DIALOG"); Collect.getInstance() .getActivityLogger() .logInstanceAction(this, "onCreateDialog.PROGRESS_DIALOG", "show"); mProgressDialog = new ProgressDialog(this); DialogInterface.OnClickListener loadingButtonListener = new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Collect.getInstance() .getActivityLogger() .logInstanceAction(this, "onCreateDialog.PROGRESS_DIALOG", "cancel"); dialog.dismiss(); mFormLoaderTask.setFormLoaderListener(null); FormLoaderTask t = mFormLoaderTask; mFormLoaderTask = null; t.cancel(true); t.destroy(); finish(); } }; mProgressDialog.setIcon(android.R.drawable.ic_dialog_info); mProgressDialog.setTitle(getString(R.string.loading_form)); mProgressDialog.setMessage(getString(R.string.please_wait)); mProgressDialog.setIndeterminate(true); mProgressDialog.setCancelable(false); mProgressDialog.setButton(getString(R.string.cancel_loading_form), loadingButtonListener); return mProgressDialog; case SAVING_DIALOG: Log.e(t, "Creating SAVING_DIALOG"); Collect.getInstance() .getActivityLogger() .logInstanceAction(this, "onCreateDialog.SAVING_DIALOG", "show"); mProgressDialog = new ProgressDialog(this); DialogInterface.OnClickListener cancelSavingButtonListener = new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Collect.getInstance() .getActivityLogger() .logInstanceAction(this, "onCreateDialog.SAVING_DIALOG", "cancel"); dialog.dismiss(); cancelSaveToDiskTask(); } }; mProgressDialog.setIcon(android.R.drawable.ic_dialog_info); mProgressDialog.setTitle(getString(R.string.saving_form)); mProgressDialog.setMessage(getString(R.string.please_wait)); mProgressDialog.setIndeterminate(true); mProgressDialog.setOnDismissListener(new DialogInterface.OnDismissListener() { @Override public void onDismiss(DialogInterface dialog) { Collect.getInstance() .getActivityLogger() .logInstanceAction(this, "onCreateDialog.SAVING_DIALOG", "OnDismissListener"); cancelSaveToDiskTask(); } }); return mProgressDialog; } return null; } private void cancelSaveToDiskTask() { synchronized (saveDialogLock) { mSaveToDiskTask.setFormSavedListener(null); boolean cancelled = mSaveToDiskTask.cancel(true); Log.w(t, "Cancelled SaveToDiskTask! (" + cancelled + ")"); mSaveToDiskTask = null; } } /** * Dismiss any showing dialogs that we manually manage. */ private void dismissDialogs() { Log.e(t, "Dismiss dialogs"); if (mAlertDialog != null && mAlertDialog.isShowing()) { mAlertDialog.dismiss(); } } @Override protected void onPause() { FormController formController = Collect.getInstance() .getFormController(); dismissDialogs(); // make sure we're not already saving to disk. if we are, currentPrompt // is getting constantly updated if (mSaveToDiskTask == null || mSaveToDiskTask.getStatus() == AsyncTask.Status.FINISHED) { if (mCurrentView != null && formController != null && formController.currentPromptIsQuestion()) { saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS); } } super.onPause(); } @Override protected void onResume() { super.onResume(); if (mErrorMessage != null) { if (mAlertDialog != null && !mAlertDialog.isShowing()) { createErrorDialog(mErrorMessage, EXIT); } else { return; } } FormController formController = Collect.getInstance().getFormController(); Collect.getInstance().getActivityLogger().open(); if (mFormLoaderTask != null) { mFormLoaderTask.setFormLoaderListener(this); if (formController == null && mFormLoaderTask.getStatus() == AsyncTask.Status.FINISHED) { FormController fec = mFormLoaderTask.getFormController(); if (fec != null) { loadingComplete(mFormLoaderTask); } else { dismissDialog(PROGRESS_DIALOG); FormLoaderTask t = mFormLoaderTask; mFormLoaderTask = null; t.cancel(true); t.destroy(); // there is no formController -- fire MainMenu activity? startActivity(new Intent(this, MainMenuActivity.class)); } } } else { if (formController == null) { // there is no formController -- fire MainMenu activity? startActivity(new Intent(this, MainMenuActivity.class)); return; } else { refreshCurrentView(); } } if (mSaveToDiskTask != null) { mSaveToDiskTask.setFormSavedListener(this); } // only check the buttons if it's enabled in preferences SharedPreferences sharedPreferences = PreferenceManager .getDefaultSharedPreferences(this); String navigation = sharedPreferences.getString( PreferencesActivity.KEY_NAVIGATION, PreferencesActivity.KEY_NAVIGATION); Boolean showButtons = false; if (navigation.contains(PreferencesActivity.NAVIGATION_BUTTONS)) { showButtons = true; } if (showButtons) { mBackButton.setVisibility(View.VISIBLE); mNextButton.setVisibility(View.VISIBLE); } else { mBackButton.setVisibility(View.GONE); mNextButton.setVisibility(View.GONE); } } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { switch (keyCode) { case KeyEvent.KEYCODE_BACK: Collect.getInstance().getActivityLogger() .logInstanceAction(this, "onKeyDown.KEYCODE_BACK", "quit"); createQuitDialog(); return true; case KeyEvent.KEYCODE_DPAD_RIGHT: if (event.isAltPressed() && !mBeenSwiped) { mBeenSwiped = true; Collect.getInstance() .getActivityLogger() .logInstanceAction(this, "onKeyDown.KEYCODE_DPAD_RIGHT", "showNext"); showNextView(); return true; } break; case KeyEvent.KEYCODE_DPAD_LEFT: if (event.isAltPressed() && !mBeenSwiped) { mBeenSwiped = true; Collect.getInstance() .getActivityLogger() .logInstanceAction(this, "onKeyDown.KEYCODE_DPAD_LEFT", "showPrevious"); showPreviousView(); return true; } break; } return super.onKeyDown(keyCode, event); } @Override protected void onDestroy() { if (mFormLoaderTask != null) { mFormLoaderTask.setFormLoaderListener(null); // We have to call cancel to terminate the thread, otherwise it // lives on and retains the FEC in memory. // but only if it's done, otherwise the thread never returns if (mFormLoaderTask.getStatus() == AsyncTask.Status.FINISHED) { FormLoaderTask t = mFormLoaderTask; mFormLoaderTask = null; t.cancel(true); t.destroy(); } } if (mSaveToDiskTask != null) { mSaveToDiskTask.setFormSavedListener(null); // We have to call cancel to terminate the thread, otherwise it // lives on and retains the FEC in memory. if (mSaveToDiskTask.getStatus() == AsyncTask.Status.FINISHED) { mSaveToDiskTask.cancel(true); mSaveToDiskTask = null; } } super.onDestroy(); } private int mAnimationCompletionSet = 0; private void afterAllAnimations() { Log.i(t, "afterAllAnimations"); if (mStaleView != null) { if (mStaleView instanceof ODKView) { // http://code.google.com/p/android/issues/detail?id=8488 ((ODKView) mStaleView).recycleDrawables(); } mStaleView = null; } if (mCurrentView instanceof ODKView) { ((ODKView) mCurrentView).setFocus(this); } mBeenSwiped = false; } @Override public void onAnimationEnd(Animation animation) { Log.i(t, "onAnimationEnd " + ((animation == mInAnimation) ? "in" : ((animation == mOutAnimation) ? "out" : "other"))); if (mInAnimation == animation) { mAnimationCompletionSet |= 1; } else if (mOutAnimation == animation) { mAnimationCompletionSet |= 2; } else { Log.e(t, "Unexpected animation"); } if (mAnimationCompletionSet == 3) { this.afterAllAnimations(); } } @Override public void onAnimationRepeat(Animation animation) { // Added by AnimationListener interface. Log.i(t, "onAnimationRepeat " + ((animation == mInAnimation) ? "in" : ((animation == mOutAnimation) ? "out" : "other"))); } @Override public void onAnimationStart(Animation animation) { // Added by AnimationListener interface. Log.i(t, "onAnimationStart " + ((animation == mInAnimation) ? "in" : ((animation == mOutAnimation) ? "out" : "other"))); } /** * loadingComplete() is called by FormLoaderTask once it has finished * loading a form. */ @Override public void loadingComplete(FormLoaderTask task) { dismissDialog(PROGRESS_DIALOG); FormController formController = task.getFormController(); boolean pendingActivityResult = task.hasPendingActivityResult(); boolean hasUsedSavepoint = task.hasUsedSavepoint(); int requestCode = task.getRequestCode(); // these are bogus if // pendingActivityResult is // false int resultCode = task.getResultCode(); Intent intent = task.getIntent(); mFormLoaderTask.setFormLoaderListener(null); FormLoaderTask t = mFormLoaderTask; mFormLoaderTask = null; t.cancel(true); t.destroy(); Collect.getInstance().setFormController(formController); CompatibilityUtils.invalidateOptionsMenu(this); Collect.getInstance().setExternalDataManager(task.getExternalDataManager()); // Set the language if one has already been set in the past String[] languageTest = formController.getLanguages(); if (languageTest != null) { String defaultLanguage = formController.getLanguage(); String newLanguage = ""; String selection = FormsColumns.FORM_FILE_PATH + "=?"; String selectArgs[] = { mFormPath }; Cursor c = null; try { c = getContentResolver().query(FormsColumns.CONTENT_URI, null, selection, selectArgs, null); if (c.getCount() == 1) { c.moveToFirst(); newLanguage = c.getString(c .getColumnIndex(FormsColumns.LANGUAGE)); } } finally { if (c != null) { c.close(); } } // if somehow we end up with a bad language, set it to the default try { formController.setLanguage(newLanguage); } catch (Exception e) { formController.setLanguage(defaultLanguage); } } if (pendingActivityResult) { // set the current view to whatever group we were at... refreshCurrentView(); // process the pending activity request... onActivityResult(requestCode, resultCode, intent); return; } // it can be a normal flow for a pending activity result to restore from // a savepoint // (the call flow handled by the above if statement). For all other use // cases, the // user should be notified, as it means they wandered off doing other // things then // returned to ODK Collect and chose Edit Saved Form, but that the // savepoint for that // form is newer than the last saved version of their form data. if (hasUsedSavepoint) { runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(FormEntryActivity.this, getString(R.string.savepoint_used), Toast.LENGTH_LONG).show(); } }); } // Set saved answer path if (formController.getInstancePath() == null) { // Create new answer folder. String time = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss", Locale.ENGLISH).format(Calendar.getInstance().getTime()); String file = mFormPath.substring(mFormPath.lastIndexOf('/') + 1, mFormPath.lastIndexOf('.')); String path = Collect.INSTANCES_PATH + File.separator + file + "_" + time; if (FileUtils.createFolder(path)) { formController.setInstancePath(new File(path + File.separator + file + "_" + time + ".xml")); } } else { Intent reqIntent = getIntent(); boolean showFirst = reqIntent.getBooleanExtra("start", false); if (!showFirst) { // we've just loaded a saved form, so start in the hierarchy // view Intent i = new Intent(this, FormHierarchyActivity.class); startActivity(i); return; // so we don't show the intro screen before jumping to // the hierarchy } } refreshCurrentView(); } /** * called by the FormLoaderTask if something goes wrong. */ @Override public void loadingError(String errorMsg) { dismissDialog(PROGRESS_DIALOG); if (errorMsg != null) { createErrorDialog(errorMsg, EXIT); } else { createErrorDialog(getString(R.string.parse_error), EXIT); } } /** * Called by SavetoDiskTask if everything saves correctly. */ @Override public void savingComplete(SaveResult saveResult) { dismissDialog(SAVING_DIALOG); int saveStatus = saveResult.getSaveResult(); switch (saveStatus) { case SaveToDiskTask.SAVED: Toast.makeText(this, getString(R.string.data_saved_ok), Toast.LENGTH_SHORT).show(); sendSavedBroadcast(); break; case SaveToDiskTask.SAVED_AND_EXIT: Toast.makeText(this, getString(R.string.data_saved_ok), Toast.LENGTH_SHORT).show(); sendSavedBroadcast(); finishReturnInstance(); break; case SaveToDiskTask.SAVE_ERROR: String message; if (saveResult.getSaveErrorMessage() != null) { message = getString(R.string.data_saved_error) + ": " + saveResult.getSaveErrorMessage(); } else { message = getString(R.string.data_saved_error); } Toast.makeText(this, message, Toast.LENGTH_LONG).show(); break; case FormEntryController.ANSWER_CONSTRAINT_VIOLATED: case FormEntryController.ANSWER_REQUIRED_BUT_EMPTY: refreshCurrentView(); // get constraint behavior preference value with appropriate default String constraint_behavior = PreferenceManager.getDefaultSharedPreferences(this) .getString(PreferencesActivity.KEY_CONSTRAINT_BEHAVIOR, PreferencesActivity.CONSTRAINT_BEHAVIOR_DEFAULT); // an answer constraint was violated, so we need to display the proper toast(s) // if constraint behavior is on_swipe, this will happen if we do a 'swipe' to the next question if (constraint_behavior.equals(PreferencesActivity.CONSTRAINT_BEHAVIOR_ON_SWIPE)) next(); // otherwise, we can get the proper toast(s) by saving with constraint check else saveAnswersForCurrentScreen(EVALUATE_CONSTRAINTS); break; } } @Override public void onProgressStep(String stepMessage) { this.stepMessage = stepMessage; if (mProgressDialog != null) { mProgressDialog.setMessage(getString(R.string.please_wait) + "\n\n" + stepMessage); } } /** * Attempts to save an answer to the specified index. * * @param answer * @param index * @param evaluateConstraints * @return status as determined in FormEntryController */ public int saveAnswer(IAnswerData answer, FormIndex index, boolean evaluateConstraints) throws JavaRosaException { FormController formController = Collect.getInstance() .getFormController(); if (evaluateConstraints) { return formController.answerQuestion(index, answer); } else { formController.saveAnswer(index, answer); return FormEntryController.ANSWER_OK; } } /** * Checks the database to determine if the current instance being edited has * already been 'marked completed'. A form can be 'unmarked' complete and * then resaved. * * @return true if form has been marked completed, false otherwise. */ private boolean isInstanceComplete(boolean end) { FormController formController = Collect.getInstance() .getFormController(); // default to false if we're mid form boolean complete = false; // if we're at the end of the form, then check the preferences if (end) { // First get the value from the preferences SharedPreferences sharedPreferences = PreferenceManager .getDefaultSharedPreferences(this); complete = sharedPreferences.getBoolean( PreferencesActivity.KEY_COMPLETED_DEFAULT, true); } // Then see if we've already marked this form as complete before String selection = InstanceColumns.INSTANCE_FILE_PATH + "=?"; String[] selectionArgs = { formController.getInstancePath() .getAbsolutePath() }; Cursor c = null; try { c = getContentResolver().query(InstanceColumns.CONTENT_URI, null, selection, selectionArgs, null); if (c != null && c.getCount() > 0) { c.moveToFirst(); String status = c.getString(c .getColumnIndex(InstanceColumns.STATUS)); if (InstanceProviderAPI.STATUS_COMPLETE.compareTo(status) == 0) { complete = true; } } } finally { if (c != null) { c.close(); } } return complete; } public void next() { if (!mBeenSwiped) { mBeenSwiped = true; showNextView(); } } /** * Returns the instance that was just filled out to the calling activity, if * requested. */ private void finishReturnInstance() { FormController formController = Collect.getInstance() .getFormController(); String action = getIntent().getAction(); if (Intent.ACTION_PICK.equals(action) || Intent.ACTION_EDIT.equals(action)) { // caller is waiting on a picked form String selection = InstanceColumns.INSTANCE_FILE_PATH + "=?"; String[] selectionArgs = { formController.getInstancePath() .getAbsolutePath() }; Cursor c = null; try { c = getContentResolver().query(InstanceColumns.CONTENT_URI, null, selection, selectionArgs, null); if (c.getCount() > 0) { // should only be one... c.moveToFirst(); String id = c.getString(c .getColumnIndex(InstanceColumns._ID)); Uri instance = Uri.withAppendedPath( InstanceColumns.CONTENT_URI, id); setResult(RESULT_OK, new Intent().setData(instance)); } } finally { if (c != null) { c.close(); } } } finish(); } @Override public boolean onDown(MotionEvent e) { return false; } @Override public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { // only check the swipe if it's enabled in preferences SharedPreferences sharedPreferences = PreferenceManager .getDefaultSharedPreferences(this); String navigation = sharedPreferences.getString( PreferencesActivity.KEY_NAVIGATION, PreferencesActivity.NAVIGATION_SWIPE); Boolean doSwipe = false; if (navigation.contains(PreferencesActivity.NAVIGATION_SWIPE)) { doSwipe = true; } if (doSwipe) { // Looks for user swipes. If the user has swiped, move to the // appropriate screen. // for all screens a swipe is left/right of at least // .25" and up/down of less than .25" // OR left/right of > .5" DisplayMetrics dm = new DisplayMetrics(); getWindowManager().getDefaultDisplay().getMetrics(dm); int xPixelLimit = (int) (dm.xdpi * .25); int yPixelLimit = (int) (dm.ydpi * .25); if (mCurrentView instanceof ODKView) { if (((ODKView) mCurrentView).suppressFlingGesture(e1, e2, velocityX, velocityY)) { return false; } } if (mBeenSwiped) { return false; } if ((Math.abs(e1.getX() - e2.getX()) > xPixelLimit && Math.abs(e1 .getY() - e2.getY()) < yPixelLimit) || Math.abs(e1.getX() - e2.getX()) > xPixelLimit * 2) { mBeenSwiped = true; if (velocityX > 0) { if (e1.getX() > e2.getX()) { Log.e(t, "showNextView VelocityX is bogus! " + e1.getX() + " > " + e2.getX()); Collect.getInstance().getActivityLogger() .logInstanceAction(this, "onFling", "showNext"); showNextView(); } else { Collect.getInstance() .getActivityLogger() .logInstanceAction(this, "onFling", "showPrevious"); showPreviousView(); } } else { if (e1.getX() < e2.getX()) { Log.e(t, "showPreviousView VelocityX is bogus! " + e1.getX() + " < " + e2.getX()); Collect.getInstance() .getActivityLogger() .logInstanceAction(this, "onFling", "showPrevious"); showPreviousView(); } else { Collect.getInstance().getActivityLogger() .logInstanceAction(this, "onFling", "showNext"); showNextView(); } } return true; } } return false; } @Override public void onLongPress(MotionEvent e) { } @Override public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) { // The onFling() captures the 'up' event so our view thinks it gets long // pressed. // We don't wnat that, so cancel it. if (mCurrentView != null) { mCurrentView.cancelLongPress(); } return false; } @Override public void onShowPress(MotionEvent e) { } @Override public boolean onSingleTapUp(MotionEvent e) { return false; } @Override public void advance() { next(); } @Override protected void onStart() { super.onStart(); Collect.getInstance().getActivityLogger().logOnStart(this); } @Override protected void onStop() { Collect.getInstance().getActivityLogger().logOnStop(this); super.onStop(); } private void sendSavedBroadcast() { Intent i = new Intent(); i.setAction("org.odk.collect.android.FormSaved"); this.sendBroadcast(i); } @Override public void onSavePointError(String errorMessage) { if (errorMessage != null && errorMessage.trim().length() > 0) { Toast.makeText(this, getString(R.string.save_point_error, errorMessage), Toast.LENGTH_LONG).show(); } } }
Java
/* * Copyright (C) 2009 University of Washington * * 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 org.odk.collect.android.activities; import org.odk.collect.android.R; import org.odk.collect.android.application.Collect; import android.app.TabActivity; import android.content.Intent; import android.graphics.Color; import android.os.Bundle; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.TabHost; import android.widget.TabWidget; import android.widget.TextView; /** * A host activity for {@link InstanceChooserList}. * * @author Yaw Anokwa (yanokwa@gmail.com) */ public class InstanceChooserTabs extends TabActivity { private static final String SAVED_TAB = "saved_tab"; private static final String COMPLETED_TAB = "completed_tab"; // count for tab menu bar private int mSavedCount; private int mCompletedCount; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setTitle(getString(R.string.app_name) + " > " + getString(R.string.review_data)); // create tab host and tweak color final TabHost tabHost = getTabHost(); tabHost.setBackgroundColor(Color.WHITE); tabHost.getTabWidget().setBackgroundColor(Color.BLACK); // create intent for saved tab Intent saved = new Intent(this, InstanceChooserList.class); tabHost.addTab(tabHost.newTabSpec(SAVED_TAB) .setIndicator(getString(R.string.saved_data, mSavedCount)).setContent(saved)); // create intent for completed tab Intent completed = new Intent(this, InstanceChooserList.class); tabHost.addTab(tabHost.newTabSpec(COMPLETED_TAB) .setIndicator(getString(R.string.completed_data, mCompletedCount)) .setContent(completed)); // hack to set font size and padding in tab headers // arrived at these paths by using hierarchy viewer LinearLayout ll = (LinearLayout) tabHost.getChildAt(0); TabWidget tw = (TabWidget) ll.getChildAt(0); int fontsize = Collect.getQuestionFontsize(); RelativeLayout rls = (RelativeLayout) tw.getChildAt(0); TextView tvs = (TextView) rls.getChildAt(1); tvs.setTextSize(fontsize); tvs.setPadding(0, 0, 0, 6); RelativeLayout rlc = (RelativeLayout) tw.getChildAt(1); TextView tvc = (TextView) rlc.getChildAt(1); tvc.setTextSize(fontsize); tvc.setPadding(0, 0, 0, 6); if (mSavedCount >= mCompletedCount) { getTabHost().setCurrentTabByTag(SAVED_TAB); } else { getTabHost().setCurrentTabByTag(COMPLETED_TAB); } } }
Java
/* * Copyright (C) 2009 University of Washington * * 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 org.odk.collect.android.activities; import org.odk.collect.android.R; import org.odk.collect.android.application.Collect; import android.app.TabActivity; import android.content.Intent; import android.graphics.Color; import android.os.Bundle; import android.view.View; import android.view.ViewGroup; import android.widget.LinearLayout; import android.widget.TabHost; import android.widget.TabWidget; import android.widget.TextView; /** * An example of tab content that launches an activity via * {@link android.widget.TabHost.TabSpec#setContent(android.content.Intent)} */ public class FileManagerTabs extends TabActivity { private TextView mTVFF; private TextView mTVDF; private static final String FORMS_TAB = "forms_tab"; private static final String DATA_TAB = "data_tab"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setTitle(getString(R.string.app_name) + " > " + getString(R.string.manage_files)); final TabHost tabHost = getTabHost(); tabHost.setBackgroundColor(Color.WHITE); tabHost.getTabWidget().setBackgroundColor(Color.DKGRAY); Intent remote = new Intent(this, DataManagerList.class); tabHost.addTab(tabHost.newTabSpec(DATA_TAB) .setIndicator(getString(R.string.data)).setContent(remote)); Intent local = new Intent(this, FormManagerList.class); tabHost.addTab(tabHost.newTabSpec(FORMS_TAB) .setIndicator(getString(R.string.forms)).setContent(local)); // hack to set font size LinearLayout ll = (LinearLayout) tabHost.getChildAt(0); TabWidget tw = (TabWidget) ll.getChildAt(0); int fontsize = Collect.getQuestionFontsize(); ViewGroup rllf = (ViewGroup) tw.getChildAt(0); mTVFF = getTextViewChild(rllf); if (mTVFF != null) { mTVFF.setTextSize(fontsize); mTVFF.setTextColor(Color.WHITE); mTVFF.setPadding(0, 0, 0, 6); } ViewGroup rlrf = (ViewGroup) tw.getChildAt(1); mTVDF = getTextViewChild(rlrf); if (mTVDF != null) { mTVDF.setTextSize(fontsize); mTVDF.setTextColor(Color.WHITE); mTVDF.setPadding(0, 0, 0, 6); } } private TextView getTextViewChild(ViewGroup viewGroup) { for (int i = 0; i < viewGroup.getChildCount(); i++) { View view = viewGroup.getChildAt(i); if (view instanceof TextView) { return (TextView) view; } } return null; } @Override protected void onStart() { super.onStart(); Collect.getInstance().getActivityLogger().logOnStart(this); } @Override protected void onStop() { Collect.getInstance().getActivityLogger().logOnStop(this); super.onStop(); } }
Java
/* * Copyright (C) 2009 University of Washington * * 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 org.odk.collect.android.activities; import org.odk.collect.android.R; import org.odk.collect.android.application.Collect; import org.odk.collect.android.provider.InstanceProviderAPI; import org.odk.collect.android.provider.InstanceProviderAPI.InstanceColumns; import android.app.AlertDialog; import android.app.ListActivity; import android.content.ContentUris; import android.content.DialogInterface; import android.content.Intent; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.view.View; import android.widget.ListView; import android.widget.SimpleCursorAdapter; import android.widget.TextView; /** * Responsible for displaying all the valid instances in the instance directory. * * @author Yaw Anokwa (yanokwa@gmail.com) * @author Carl Hartung (carlhartung@gmail.com) */ public class InstanceChooserList extends ListActivity { private static final boolean EXIT = true; private static final boolean DO_NOT_EXIT = false; private AlertDialog mAlertDialog; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // must be at the beginning of any activity that can be called from an external intent try { Collect.createODKDirs(); } catch (RuntimeException e) { createErrorDialog(e.getMessage(), EXIT); return; } setContentView(R.layout.chooser_list_layout); setTitle(getString(R.string.app_name) + " > " + getString(R.string.review_data)); TextView tv = (TextView) findViewById(R.id.status_text); tv.setVisibility(View.GONE); String selection = InstanceColumns.STATUS + " != ?"; String[] selectionArgs = {InstanceProviderAPI.STATUS_SUBMITTED}; String sortOrder = InstanceColumns.STATUS + " DESC, " + InstanceColumns.DISPLAY_NAME + " ASC"; Cursor c = managedQuery(InstanceColumns.CONTENT_URI, null, selection, selectionArgs, sortOrder); String[] data = new String[] { InstanceColumns.DISPLAY_NAME, InstanceColumns.DISPLAY_SUBTEXT }; int[] view = new int[] { R.id.text1, R.id.text2 }; // render total instance view SimpleCursorAdapter instances = new SimpleCursorAdapter(this, R.layout.two_item, c, data, view); setListAdapter(instances); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent intent) { super.onActivityResult(requestCode, resultCode, intent); } /** * Stores the path of selected instance in the parent class and finishes. */ @Override protected void onListItemClick(ListView listView, View view, int position, long id) { Cursor c = (Cursor) getListAdapter().getItem(position); startManagingCursor(c); Uri instanceUri = ContentUris.withAppendedId(InstanceColumns.CONTENT_URI, c.getLong(c.getColumnIndex(InstanceColumns._ID))); Collect.getInstance().getActivityLogger().logAction(this, "onListItemClick", instanceUri.toString()); String action = getIntent().getAction(); if (Intent.ACTION_PICK.equals(action)) { // caller is waiting on a picked form setResult(RESULT_OK, new Intent().setData(instanceUri)); } else { // the form can be edited if it is incomplete or if, when it was // marked as complete, it was determined that it could be edited // later. String status = c.getString(c.getColumnIndex(InstanceColumns.STATUS)); String strCanEditWhenComplete = c.getString(c.getColumnIndex(InstanceColumns.CAN_EDIT_WHEN_COMPLETE)); boolean canEdit = status.equals(InstanceProviderAPI.STATUS_INCOMPLETE) || Boolean.parseBoolean(strCanEditWhenComplete); if (!canEdit) { createErrorDialog(getString(R.string.cannot_edit_completed_form), DO_NOT_EXIT); return; } // caller wants to view/edit a form, so launch formentryactivity startActivity(new Intent(Intent.ACTION_EDIT, instanceUri)); } finish(); } @Override protected void onStart() { super.onStart(); Collect.getInstance().getActivityLogger().logOnStart(this); } @Override protected void onStop() { Collect.getInstance().getActivityLogger().logOnStop(this); super.onStop(); } private void createErrorDialog(String errorMsg, final boolean shouldExit) { Collect.getInstance().getActivityLogger().logAction(this, "createErrorDialog", "show"); mAlertDialog = new AlertDialog.Builder(this).create(); mAlertDialog.setIcon(android.R.drawable.ic_dialog_info); mAlertDialog.setMessage(errorMsg); DialogInterface.OnClickListener errorListener = new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int i) { switch (i) { case DialogInterface.BUTTON_POSITIVE: Collect.getInstance().getActivityLogger().logAction(this, "createErrorDialog", shouldExit ? "exitApplication" : "OK"); if (shouldExit) { finish(); } break; } } }; mAlertDialog.setCancelable(false); mAlertDialog.setButton(getString(R.string.ok), errorListener); mAlertDialog.show(); } }
Java
/* * Copyright (C) 2009 University of Washington * * 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 org.odk.collect.android.activities; import java.util.ArrayList; import java.util.List; import org.javarosa.core.model.FormIndex; import org.javarosa.form.api.FormEntryCaption; import org.javarosa.form.api.FormEntryController; import org.javarosa.form.api.FormEntryPrompt; import org.odk.collect.android.R; import org.odk.collect.android.adapters.HierarchyListAdapter; import org.odk.collect.android.application.Collect; import org.odk.collect.android.exception.JavaRosaException; import org.odk.collect.android.logic.FormController; import org.odk.collect.android.logic.HierarchyElement; import android.app.AlertDialog; import android.app.ListActivity; import android.content.DialogInterface; import android.graphics.Color; import android.os.Bundle; import android.util.Log; import android.view.KeyEvent; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.ListView; import android.widget.TextView; public class FormHierarchyActivity extends ListActivity { private static final String t = "FormHierarchyActivity"; private static final int CHILD = 1; private static final int EXPANDED = 2; private static final int COLLAPSED = 3; private static final int QUESTION = 4; private static final String mIndent = " "; private Button jumpPreviousButton; List<HierarchyElement> formList; TextView mPath; FormIndex mStartIndex; private FormIndex currentIndex; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.hierarchy_layout); FormController formController = Collect.getInstance().getFormController(); // We use a static FormEntryController to make jumping faster. mStartIndex = formController.getFormIndex(); setTitle(getString(R.string.app_name) + " > " + formController.getFormTitle()); mPath = (TextView) findViewById(R.id.pathtext); jumpPreviousButton = (Button) findViewById(R.id.jumpPreviousButton); jumpPreviousButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Collect.getInstance().getActivityLogger().logInstanceAction(this, "goUpLevelButton", "click"); goUpLevel(); } }); Button jumpBeginningButton = (Button) findViewById(R.id.jumpBeginningButton); jumpBeginningButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Collect.getInstance().getActivityLogger().logInstanceAction(this, "jumpToBeginning", "click"); Collect.getInstance().getFormController().jumpToIndex(FormIndex .createBeginningOfFormIndex()); setResult(RESULT_OK); finish(); } }); Button jumpEndButton = (Button) findViewById(R.id.jumpEndButton); jumpEndButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Collect.getInstance().getActivityLogger().logInstanceAction(this, "jumpToEnd", "click"); Collect.getInstance().getFormController().jumpToIndex(FormIndex.createEndOfFormIndex()); setResult(RESULT_OK); finish(); } }); refreshView(); // kinda slow, but works. // this scrolls to the last question the user was looking at if (getListAdapter() != null && getListView() != null) { getListView().post(new Runnable() { @Override public void run() { int position = 0; for (int i = 0; i < getListAdapter().getCount(); i++) { HierarchyElement he = (HierarchyElement) getListAdapter().getItem(i); if (mStartIndex.equals(he.getFormIndex())) { position = i; break; } } getListView().setSelection(position); } }); } } @Override protected void onStart() { super.onStart(); Collect.getInstance().getActivityLogger().logOnStart(this); } @Override protected void onStop() { Collect.getInstance().getActivityLogger().logOnStop(this); super.onStop(); } private void goUpLevel() { Collect.getInstance().getFormController().stepToOuterScreenEvent(); refreshView(); } private String getCurrentPath() { FormController formController = Collect.getInstance().getFormController(); FormIndex index = formController.getFormIndex(); // move to enclosing group... index = formController.stepIndexOut(index); String path = ""; while (index != null) { path = formController.getCaptionPrompt(index).getLongText() + " (" + (formController.getCaptionPrompt(index) .getMultiplicity() + 1) + ") > " + path; index = formController.stepIndexOut(index); } // return path? return path.substring(0, path.length() - 2); } public void refreshView() { try { FormController formController = Collect.getInstance().getFormController(); // Record the current index so we can return to the same place if the user hits 'back'. currentIndex = formController.getFormIndex(); // If we're not at the first level, we're inside a repeated group so we want to only display // everything enclosed within that group. String contextGroupRef = ""; formList = new ArrayList<HierarchyElement>(); // If we're currently at a repeat node, record the name of the node and step to the next // node to display. if (formController.getEvent() == FormEntryController.EVENT_REPEAT) { contextGroupRef = formController.getFormIndex().getReference().toString(true); formController.stepToNextEvent(FormController.STEP_INTO_GROUP); } else { FormIndex startTest = formController.stepIndexOut(currentIndex); // If we have a 'group' tag, we want to step back until we hit a repeat or the // beginning. while (startTest != null && formController.getEvent(startTest) == FormEntryController.EVENT_GROUP) { startTest = formController.stepIndexOut(startTest); } if (startTest == null) { // check to see if the question is at the first level of the hierarchy. If it is, // display the root level from the beginning. formController.jumpToIndex(FormIndex .createBeginningOfFormIndex()); } else { // otherwise we're at a repeated group formController.jumpToIndex(startTest); } // now test again for repeat. This should be true at this point or we're at the // beginning if (formController.getEvent() == FormEntryController.EVENT_REPEAT) { contextGroupRef = formController.getFormIndex().getReference().toString(true); formController.stepToNextEvent(FormController.STEP_INTO_GROUP); } } int event = formController.getEvent(); if (event == FormEntryController.EVENT_BEGINNING_OF_FORM) { // The beginning of form has no valid prompt to display. formController.stepToNextEvent(FormController.STEP_INTO_GROUP); contextGroupRef = formController.getFormIndex().getReference().getParentRef().toString(true); mPath.setVisibility(View.GONE); jumpPreviousButton.setEnabled(false); } else { mPath.setVisibility(View.VISIBLE); mPath.setText(getCurrentPath()); jumpPreviousButton.setEnabled(true); } // Refresh the current event in case we did step forward. event = formController.getEvent(); // Big change from prior implementation: // // The ref strings now include the instance number designations // i.e., [0], [1], etc. of the repeat groups (and also [1] for // non-repeat elements). // // The contextGroupRef is now also valid for the top-level form. // // The repeatGroupRef is null if we are not skipping a repeat // section. // String repeatGroupRef = null; event_search: while (event != FormEntryController.EVENT_END_OF_FORM) { // get the ref to this element String currentRef = formController.getFormIndex().getReference().toString(true); // retrieve the current group String curGroup = (repeatGroupRef == null) ? contextGroupRef : repeatGroupRef; if (!currentRef.startsWith(curGroup)) { // We have left the current group if ( repeatGroupRef == null ) { // We are done. break event_search; } else { // exit the inner repeat group repeatGroupRef = null; } } if (repeatGroupRef != null) { // We're in a repeat group within the one we want to list // skip this question/group/repeat and move to the next index. event = formController.stepToNextEvent(FormController.STEP_INTO_GROUP); continue; } switch (event) { case FormEntryController.EVENT_QUESTION: FormEntryPrompt fp = formController.getQuestionPrompt(); String label = fp.getLongText(); if ( !fp.isReadOnly() || (label != null && label.length() > 0) ) { // show the question if it is an editable field. // or if it is read-only and the label is not blank. formList.add(new HierarchyElement(fp.getLongText(), fp.getAnswerText(), null, Color.WHITE, QUESTION, fp.getIndex())); } break; case FormEntryController.EVENT_GROUP: // ignore group events break; case FormEntryController.EVENT_PROMPT_NEW_REPEAT: // this would display the 'add new repeat' dialog // ignore it. break; case FormEntryController.EVENT_REPEAT: FormEntryCaption fc = formController.getCaptionPrompt(); // push this repeat onto the stack. repeatGroupRef = currentRef; // Because of the guard conditions above, we will skip // everything until we exit this repeat. // // Note that currentRef includes the multiplicity of the // repeat (e.g., [0], [1], ...), so every repeat will be // detected as different and reach this case statement. // Only the [0] emits the repeat header. // Every one displays the descend-into action element. if (fc.getMultiplicity() == 0) { // Display the repeat header for the group. HierarchyElement group = new HierarchyElement(fc.getLongText(), null, getResources() .getDrawable(R.drawable.expander_ic_minimized), Color.WHITE, COLLAPSED, fc.getIndex()); formList.add(group); } // Add this group name to the drop down list for this repeating group. HierarchyElement h = formList.get(formList.size() - 1); h.addChild(new HierarchyElement(mIndent + fc.getLongText() + " " + (fc.getMultiplicity() + 1), null, null, Color.WHITE, CHILD, fc .getIndex())); break; } event = formController.stepToNextEvent(FormController.STEP_INTO_GROUP); } HierarchyListAdapter itla = new HierarchyListAdapter(this); itla.setListItems(formList); setListAdapter(itla); // set the controller back to the current index in case the user hits 'back' formController.jumpToIndex(currentIndex); } catch (Exception e) { Log.e(t, e.getMessage(), e); createErrorDialog(e.getMessage()); } } /** * Creates and displays dialog with the given errorMsg. */ private void createErrorDialog(String errorMsg) { Collect.getInstance() .getActivityLogger() .logInstanceAction(this, "createErrorDialog", "show."); AlertDialog alertDialog = new AlertDialog.Builder(this).create(); alertDialog.setIcon(android.R.drawable.ic_dialog_info); alertDialog.setTitle(getString(R.string.error_occured)); alertDialog.setMessage(errorMsg); DialogInterface.OnClickListener errorListener = new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int i) { switch (i) { case DialogInterface.BUTTON_POSITIVE: Collect.getInstance().getActivityLogger() .logInstanceAction(this, "createErrorDialog", "OK"); FormController formController = Collect.getInstance().getFormController(); formController.jumpToIndex(currentIndex); break; } } }; alertDialog.setCancelable(false); alertDialog.setButton(getString(R.string.ok), errorListener); alertDialog.show(); } @Override protected void onListItemClick(ListView l, View v, int position, long id) { HierarchyElement h = (HierarchyElement) l.getItemAtPosition(position); FormIndex index = h.getFormIndex(); if (index == null) { goUpLevel(); return; } switch (h.getType()) { case EXPANDED: Collect.getInstance().getActivityLogger().logInstanceAction(this, "onListItemClick", "COLLAPSED", h.getFormIndex()); h.setType(COLLAPSED); ArrayList<HierarchyElement> children = h.getChildren(); for (int i = 0; i < children.size(); i++) { formList.remove(position + 1); } h.setIcon(getResources().getDrawable(R.drawable.expander_ic_minimized)); h.setColor(Color.WHITE); break; case COLLAPSED: Collect.getInstance().getActivityLogger().logInstanceAction(this, "onListItemClick", "EXPANDED", h.getFormIndex()); h.setType(EXPANDED); ArrayList<HierarchyElement> children1 = h.getChildren(); for (int i = 0; i < children1.size(); i++) { Log.i(t, "adding child: " + children1.get(i).getFormIndex()); formList.add(position + 1 + i, children1.get(i)); } h.setIcon(getResources().getDrawable(R.drawable.expander_ic_maximized)); h.setColor(Color.WHITE); break; case QUESTION: Collect.getInstance().getActivityLogger().logInstanceAction(this, "onListItemClick", "QUESTION-JUMP", index); Collect.getInstance().getFormController().jumpToIndex(index); if ( Collect.getInstance().getFormController().indexIsInFieldList() ) { try { Collect.getInstance().getFormController().stepToPreviousScreenEvent(); } catch (JavaRosaException e) { Log.e(t, e.getMessage(), e); createErrorDialog(e.getCause().getMessage()); return; } } setResult(RESULT_OK); finish(); return; case CHILD: Collect.getInstance().getActivityLogger().logInstanceAction(this, "onListItemClick", "REPEAT-JUMP", h.getFormIndex()); Collect.getInstance().getFormController().jumpToIndex(h.getFormIndex()); setResult(RESULT_OK); refreshView(); return; } // Should only get here if we've expanded or collapsed a group HierarchyListAdapter itla = new HierarchyListAdapter(this); itla.setListItems(formList); setListAdapter(itla); getListView().setSelection(position); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { switch (keyCode) { case KeyEvent.KEYCODE_BACK: Collect.getInstance().getActivityLogger().logInstanceAction(this, "onKeyDown", "KEYCODE_BACK.JUMP", mStartIndex); Collect.getInstance().getFormController().jumpToIndex(mStartIndex); } return super.onKeyDown(keyCode, event); } }
Java
/* * Copyright (C) 2011 University of Washington * * 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 org.odk.collect.android.activities; import java.text.DecimalFormat; import java.util.List; import org.odk.collect.android.R; import org.odk.collect.android.application.Collect; import org.odk.collect.android.utilities.InfoLogger; import org.odk.collect.android.widgets.GeoPointWidget; import android.content.Context; import android.content.Intent; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.os.Bundle; import android.support.v4.app.FragmentActivity; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.view.Window; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.GoogleMap.OnMapLongClickListener; import com.google.android.gms.maps.GoogleMap.OnMarkerDragListener; import com.google.android.gms.maps.SupportMapFragment; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.Marker; import com.google.android.gms.maps.model.MarkerOptions; /** * Version of the GeoPointMapActivity that uses the new Maps v2 API and Fragments to enable * specifying a location via placing a tracker on a map. * * @author guisalmon@gmail.com * */ public class GeoPointMapActivity extends FragmentActivity implements LocationListener, OnMarkerDragListener, OnMapLongClickListener { private static final String LOCATION_COUNT = "locationCount"; private GoogleMap mMap; private MarkerOptions mMarkerOption; private Marker mMarker; private LatLng mLatLng; private TextView mLocationStatus; private LocationManager mLocationManager; private Location mLocation; private Button mAcceptLocation; private Button mCancelLocation; private Button mReloadLocation; private boolean mCaptureLocation = true; private boolean mRefreshLocation = true; private boolean mIsDragged = false; private Button mShowLocation; private boolean mGPSOn = false; private boolean mNetworkOn = false; private double mLocationAccuracy; private int mLocationCount = 0; private boolean mZoomed = false; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if ( savedInstanceState != null ) { mLocationCount = savedInstanceState.getInt(LOCATION_COUNT); } requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.geopoint_layout); Intent intent = getIntent(); mLocationAccuracy = GeoPointWidget.DEFAULT_LOCATION_ACCURACY; if (intent != null && intent.getExtras() != null) { if ( intent.hasExtra(GeoPointWidget.LOCATION) ) { double[] location = intent.getDoubleArrayExtra(GeoPointWidget.LOCATION); mLatLng = new LatLng(location[0], location[1]); } if ( intent.hasExtra(GeoPointWidget.ACCURACY_THRESHOLD) ) { mLocationAccuracy = intent.getDoubleExtra(GeoPointWidget.ACCURACY_THRESHOLD, GeoPointWidget.DEFAULT_LOCATION_ACCURACY); } mCaptureLocation = !intent.getBooleanExtra(GeoPointWidget.READ_ONLY, false); mRefreshLocation = mCaptureLocation; } /* Set up the map and the marker */ mMarkerOption = new MarkerOptions(); mMap = ((SupportMapFragment) getSupportFragmentManager() .findFragmentById(R.id.map)).getMap(); mMap.setOnMarkerDragListener(this); mLocationStatus = (TextView) findViewById(R.id.location_status); /*Zoom only if there's a previous location*/ if (mLatLng != null){ mLocationStatus.setVisibility(View.GONE); mMarkerOption.position(mLatLng); mMarker = mMap.addMarker(mMarkerOption); mRefreshLocation = false; // just show this position; don't change it... mMarker.setDraggable(mCaptureLocation); mZoomed = true; mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(mLatLng, 16)); } mCancelLocation = (Button) findViewById(R.id.cancel_location); mCancelLocation.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Collect.getInstance().getActivityLogger().logInstanceAction(this, "cancelLocation", "cancel"); finish(); } }); mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); // make sure we have a good location provider before continuing List<String> providers = mLocationManager.getProviders(true); for (String provider : providers) { if (provider.equalsIgnoreCase(LocationManager.GPS_PROVIDER)) { mGPSOn = true; } if (provider.equalsIgnoreCase(LocationManager.NETWORK_PROVIDER)) { mNetworkOn = true; } } if (!mGPSOn && !mNetworkOn) { Toast.makeText(getBaseContext(), getString(R.string.provider_disabled_error), Toast.LENGTH_SHORT).show(); finish(); } if ( mGPSOn ) { Location loc = mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); if ( loc != null ) { InfoLogger.geolog("GeoPointMapActivity: " + System.currentTimeMillis() + " lastKnownLocation(GPS) lat: " + loc.getLatitude() + " long: " + loc.getLongitude() + " acc: " + loc.getAccuracy() ); } else { InfoLogger.geolog("GeoPointMapActivity: " + System.currentTimeMillis() + " lastKnownLocation(GPS) null location"); } } if ( mNetworkOn ) { Location loc = mLocationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER); if ( loc != null ) { InfoLogger.geolog("GeoPointMapActivity: " + System.currentTimeMillis() + " lastKnownLocation(Network) lat: " + loc.getLatitude() + " long: " + loc.getLongitude() + " acc: " + loc.getAccuracy() ); } else { InfoLogger.geolog("GeoPointMapActivity: " + System.currentTimeMillis() + " lastKnownLocation(Network) null location"); } } mAcceptLocation = (Button) findViewById(R.id.accept_location); if (mCaptureLocation){ mAcceptLocation.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Collect.getInstance().getActivityLogger().logInstanceAction(this, "acceptLocation", "OK"); returnLocation(); } }); mMap.setOnMapLongClickListener(this); }else{ mAcceptLocation.setVisibility(View.GONE); } mReloadLocation = (Button) findViewById(R.id.reload_location); if (mCaptureLocation) { mReloadLocation.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { mRefreshLocation = true; mReloadLocation.setVisibility(View.GONE); mLocationStatus.setVisibility(View.VISIBLE); if (mGPSOn) { mLocationManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, 0, 0, GeoPointMapActivity.this); } if (mNetworkOn) { mLocationManager.requestLocationUpdates( LocationManager.NETWORK_PROVIDER, 0, 0, GeoPointMapActivity.this); } } }); mReloadLocation.setVisibility(!mRefreshLocation ? View.VISIBLE : View.GONE); } else { mReloadLocation.setVisibility(View.GONE); } // Focuses on marked location mShowLocation = ((Button) findViewById(R.id.show_location)); mShowLocation.setVisibility(View.VISIBLE); mShowLocation.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Collect.getInstance().getActivityLogger() .logInstanceAction(this, "showLocation", "onClick"); mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(mLatLng, 16)); } }); mShowLocation.setClickable(mMarker != null); } private void stopGeolocating() { mRefreshLocation = false; mReloadLocation.setVisibility(View.VISIBLE); mLocationManager.removeUpdates(this); mMarker.setDraggable(true); mLocationStatus.setVisibility(View.GONE); } @Override protected void onStart() { super.onStart(); Collect.getInstance().getActivityLogger().logOnStart(this); } @Override protected void onStop() { Collect.getInstance().getActivityLogger().logOnStop(this); super.onStop(); } private void returnLocation() { if (mIsDragged){ Log.i(getClass().getName(), "IsDragged !!!"); Intent i = new Intent(); i.putExtra( FormEntryActivity.LOCATION_RESULT, mLatLng.latitude + " " + mLatLng.longitude + " " + 0 + " " + 0); setResult(RESULT_OK, i); } else if (mLocation != null) { Log.i(getClass().getName(), "IsNotDragged !!!"); Intent i = new Intent(); i.putExtra( FormEntryActivity.LOCATION_RESULT, mLocation.getLatitude() + " " + mLocation.getLongitude() + " " + mLocation.getAltitude() + " " + mLocation.getAccuracy()); setResult(RESULT_OK, i); } finish(); } private String truncateFloat(float f) { return new DecimalFormat("#.##").format(f); } @Override protected void onPause() { super.onPause(); mLocationManager.removeUpdates(this); } @Override protected void onResume() { super.onResume(); if ( mRefreshLocation ) { mLocationStatus.setVisibility(View.VISIBLE); if (mGPSOn) { mLocationManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, 0, 0, this); } if (mNetworkOn) { mLocationManager.requestLocationUpdates( LocationManager.NETWORK_PROVIDER, 0, 0, this); } } } @Override public void onLocationChanged(Location location) { if (mRefreshLocation) { mLocation = location; if (mLocation != null) { // Bug report: cached GeoPoint is being returned as the first value. // Wait for the 2nd value to be returned, which is hopefully not cached? ++mLocationCount; InfoLogger.geolog("GeoPointMapActivity: " + System.currentTimeMillis() + " onLocationChanged(" + mLocationCount + ") lat: " + mLocation.getLatitude() + " long: " + mLocation.getLongitude() + " acc: " + mLocation.getAccuracy() ); if (mLocationCount > 1) { mLocationStatus.setText(getString(R.string.location_provider_accuracy, mLocation.getProvider(), truncateFloat(mLocation.getAccuracy()))); mLatLng = new LatLng(mLocation.getLatitude(), mLocation.getLongitude()); if ( !mZoomed ) { mZoomed = true; mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(mLatLng, 16)); } else { mMap.animateCamera(CameraUpdateFactory.newLatLng(mLatLng)); } // create a marker on the map or move the existing marker to the // new location if (mMarker == null) { mMarkerOption.position(mLatLng); mMarker = mMap.addMarker(mMarkerOption); mShowLocation.setClickable(true); } else { mMarker.setPosition(mLatLng); } //If location is accurate enough, stop updating position and make the marker draggable if (mLocation.getAccuracy() <= mLocationAccuracy) { stopGeolocating(); } } } else { InfoLogger.geolog("GeoPointMapActivity: " + System.currentTimeMillis() + " onLocationChanged(" + mLocationCount + ") null location"); } } } @Override public void onProviderDisabled(String provider) { } @Override public void onProviderEnabled(String provider) { } @Override public void onStatusChanged(String provider, int status, Bundle extras) { } @Override public void onMarkerDrag(Marker arg0) { } @Override public void onMarkerDragEnd(Marker marker) { mLatLng = marker.getPosition(); mAcceptLocation.setClickable(true); mIsDragged = true; mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(mLatLng, mMap.getCameraPosition().zoom)); } @Override public void onMarkerDragStart(Marker arg0) { stopGeolocating(); } @Override public void onMapLongClick(LatLng latLng) { if (mMarker == null) { mMarkerOption.position(latLng); mMarker = mMap.addMarker(mMarkerOption); mShowLocation.setClickable(true); } else { mMarker.setPosition(latLng); } mLatLng=latLng; mIsDragged = true; stopGeolocating(); mMarker.setDraggable(true); } }
Java
/* * Copyright (C) 2009 University of Washington * * 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 org.odk.collect.android.activities; import java.text.DecimalFormat; import java.util.List; import org.odk.collect.android.R; import org.odk.collect.android.application.Collect; import org.odk.collect.android.utilities.InfoLogger; import org.odk.collect.android.widgets.GeoPointWidget; import android.app.Activity; import android.app.ProgressDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.location.LocationProvider; import android.os.Bundle; import android.widget.Toast; public class GeoPointActivity extends Activity implements LocationListener { private static final String LOCATION_COUNT = "locationCount"; private ProgressDialog mLocationDialog; private LocationManager mLocationManager; private Location mLocation; private boolean mGPSOn = false; private boolean mNetworkOn = false; private double mLocationAccuracy; private int mLocationCount = 0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if ( savedInstanceState != null ) { mLocationCount = savedInstanceState.getInt(LOCATION_COUNT); } Intent intent = getIntent(); mLocationAccuracy = GeoPointWidget.DEFAULT_LOCATION_ACCURACY; if (intent != null && intent.getExtras() != null) { if ( intent.hasExtra(GeoPointWidget.ACCURACY_THRESHOLD) ) { mLocationAccuracy = intent.getDoubleExtra(GeoPointWidget.ACCURACY_THRESHOLD, GeoPointWidget.DEFAULT_LOCATION_ACCURACY); } } setTitle(getString(R.string.app_name) + " > " + getString(R.string.get_location)); mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); // make sure we have a good location provider before continuing List<String> providers = mLocationManager.getProviders(true); for (String provider : providers) { if (provider.equalsIgnoreCase(LocationManager.GPS_PROVIDER)) { mGPSOn = true; } if (provider.equalsIgnoreCase(LocationManager.NETWORK_PROVIDER)) { mNetworkOn = true; } } if (!mGPSOn && !mNetworkOn) { Toast.makeText(getBaseContext(), getString(R.string.provider_disabled_error), Toast.LENGTH_SHORT).show(); finish(); } if ( mGPSOn ) { Location loc = mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); if ( loc != null ) { InfoLogger.geolog("GeoPointActivity: " + System.currentTimeMillis() + " lastKnownLocation(GPS) lat: " + loc.getLatitude() + " long: " + loc.getLongitude() + " acc: " + loc.getAccuracy() ); } else { InfoLogger.geolog("GeoPointActivity: " + System.currentTimeMillis() + " lastKnownLocation(GPS) null location"); } } if ( mNetworkOn ) { Location loc = mLocationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER); if ( loc != null ) { InfoLogger.geolog("GeoPointActivity: " + System.currentTimeMillis() + " lastKnownLocation(Network) lat: " + loc.getLatitude() + " long: " + loc.getLongitude() + " acc: " + loc.getAccuracy() ); } else { InfoLogger.geolog("GeoPointActivity: " + System.currentTimeMillis() + " lastKnownLocation(Network) null location"); } } setupLocationDialog(); } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putInt(LOCATION_COUNT, mLocationCount); } @Override protected void onPause() { super.onPause(); // stops the GPS. Note that this will turn off the GPS if the screen goes to sleep. mLocationManager.removeUpdates(this); // We're not using managed dialogs, so we have to dismiss the dialog to prevent it from // leaking memory. if (mLocationDialog != null && mLocationDialog.isShowing()) mLocationDialog.dismiss(); } @Override protected void onResume() { super.onResume(); if (mGPSOn) { mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this); } if (mNetworkOn) { mLocationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this); } mLocationDialog.show(); } @Override protected void onStart() { super.onStart(); Collect.getInstance().getActivityLogger().logOnStart(this); } @Override protected void onStop() { Collect.getInstance().getActivityLogger().logOnStop(this); super.onStop(); } /** * Sets up the look and actions for the progress dialog while the GPS is searching. */ private void setupLocationDialog() { Collect.getInstance().getActivityLogger().logInstanceAction(this, "setupLocationDialog", "show"); // dialog displayed while fetching gps location mLocationDialog = new ProgressDialog(this); DialogInterface.OnClickListener geopointButtonListener = new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { switch (which) { case DialogInterface.BUTTON_POSITIVE: Collect.getInstance().getActivityLogger().logInstanceAction(this, "acceptLocation", "OK"); returnLocation(); break; case DialogInterface. BUTTON_NEGATIVE: Collect.getInstance().getActivityLogger().logInstanceAction(this, "cancelLocation", "cancel"); mLocation = null; finish(); break; } } }; // back button doesn't cancel mLocationDialog.setCancelable(false); mLocationDialog.setIndeterminate(true); mLocationDialog.setIcon(android.R.drawable.ic_dialog_info); mLocationDialog.setTitle(getString(R.string.getting_location)); mLocationDialog.setMessage(getString(R.string.please_wait_long)); mLocationDialog.setButton(DialogInterface.BUTTON_POSITIVE, getString(R.string.accept_location), geopointButtonListener); mLocationDialog.setButton(DialogInterface. BUTTON_NEGATIVE, getString(R.string.cancel_location), geopointButtonListener); } private void returnLocation() { if (mLocation != null) { Intent i = new Intent(); i.putExtra( FormEntryActivity.LOCATION_RESULT, mLocation.getLatitude() + " " + mLocation.getLongitude() + " " + mLocation.getAltitude() + " " + mLocation.getAccuracy()); setResult(RESULT_OK, i); } finish(); } @Override public void onLocationChanged(Location location) { mLocation = location; if (mLocation != null) { // Bug report: cached GeoPoint is being returned as the first value. // Wait for the 2nd value to be returned, which is hopefully not cached? ++mLocationCount; InfoLogger.geolog("GeoPointActivity: " + System.currentTimeMillis() + " onLocationChanged(" + mLocationCount + ") lat: " + mLocation.getLatitude() + " long: " + mLocation.getLongitude() + " acc: " + mLocation.getAccuracy() ); if (mLocationCount > 1) { mLocationDialog.setMessage(getString(R.string.location_provider_accuracy, mLocation.getProvider(), truncateDouble(mLocation.getAccuracy()))); if (mLocation.getAccuracy() <= mLocationAccuracy) { returnLocation(); } } } else { InfoLogger.geolog("GeoPointActivity: " + System.currentTimeMillis() + " onLocationChanged(" + mLocationCount + ") null location"); } } private String truncateDouble(float number) { DecimalFormat df = new DecimalFormat("#.##"); return df.format(number); } @Override public void onProviderDisabled(String provider) { } @Override public void onProviderEnabled(String provider) { } @Override public void onStatusChanged(String provider, int status, Bundle extras) { switch (status) { case LocationProvider.AVAILABLE: if (mLocation != null) { mLocationDialog.setMessage(getString(R.string.location_accuracy, mLocation.getAccuracy())); } break; case LocationProvider.OUT_OF_SERVICE: break; case LocationProvider.TEMPORARILY_UNAVAILABLE: break; } } }
Java
package org.odk.collect.android.activities; import org.odk.collect.android.R; import org.odk.collect.android.application.Collect; import android.app.Activity; import android.graphics.Typeface; import android.os.Bundle; import android.util.TypedValue; import android.widget.TextView; public class NotificationActivity extends Activity { public final static String NOTIFICATION_KEY = "message"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.notification_layout); String note = this.getIntent().getStringExtra(NOTIFICATION_KEY); if (note == null) { note = getString(R.string.notification_error); } TextView notificationText = (TextView)findViewById(R.id.notification); notificationText.setTextSize(TypedValue.COMPLEX_UNIT_DIP, Collect.getQuestionFontsize()); notificationText.setTypeface(null, Typeface.BOLD); notificationText.setPadding(0, 0, 0, 7); notificationText.setText(note); } }
Java
/* * Copyright (C) 2009 University of Washington * * 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 org.odk.collect.android.activities; import java.util.ArrayList; import org.odk.collect.android.R; import org.odk.collect.android.application.Collect; import org.odk.collect.android.preferences.PreferencesActivity; import org.odk.collect.android.provider.InstanceProviderAPI; import org.odk.collect.android.provider.InstanceProviderAPI.InstanceColumns; import org.odk.collect.android.receivers.NetworkReceiver; import org.odk.collect.android.utilities.CompatibilityUtils; import android.app.AlertDialog; import android.app.Dialog; import android.app.ListActivity; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.database.Cursor; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.Bundle; import android.preference.PreferenceManager; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.view.View.OnLongClickListener; import android.widget.Button; import android.widget.ListView; import android.widget.SimpleCursorAdapter; import android.widget.Toast; /** * Responsible for displaying all the valid forms in the forms directory. Stores * the path to selected form for use by {@link MainMenuActivity}. * * @author Carl Hartung (carlhartung@gmail.com) * @author Yaw Anokwa (yanokwa@gmail.com) */ public class InstanceUploaderList extends ListActivity implements OnLongClickListener { private static final String BUNDLE_SELECTED_ITEMS_KEY = "selected_items"; private static final String BUNDLE_TOGGLED_KEY = "toggled"; private static final int MENU_PREFERENCES = Menu.FIRST; private static final int MENU_SHOW_UNSENT = Menu.FIRST + 1; private static final int INSTANCE_UPLOADER = 0; private static final int GOOGLE_USER_DIALOG = 1; private Button mUploadButton; private Button mToggleButton; private boolean mShowUnsent = true; private SimpleCursorAdapter mInstances; private ArrayList<Long> mSelected = new ArrayList<Long>(); private boolean mRestored = false; private boolean mToggled = false; public Cursor getUnsentCursor() { // get all complete or failed submission instances String selection = InstanceColumns.STATUS + "=? or " + InstanceColumns.STATUS + "=?"; String selectionArgs[] = { InstanceProviderAPI.STATUS_COMPLETE, InstanceProviderAPI.STATUS_SUBMISSION_FAILED }; String sortOrder = InstanceColumns.DISPLAY_NAME + " ASC"; Cursor c = managedQuery(InstanceColumns.CONTENT_URI, null, selection, selectionArgs, sortOrder); return c; } public Cursor getAllCursor() { // get all complete or failed submission instances String selection = InstanceColumns.STATUS + "=? or " + InstanceColumns.STATUS + "=? or " + InstanceColumns.STATUS + "=?"; String selectionArgs[] = { InstanceProviderAPI.STATUS_COMPLETE, InstanceProviderAPI.STATUS_SUBMISSION_FAILED, InstanceProviderAPI.STATUS_SUBMITTED }; String sortOrder = InstanceColumns.DISPLAY_NAME + " ASC"; Cursor c = managedQuery(InstanceColumns.CONTENT_URI, null, selection, selectionArgs, sortOrder); return c; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.instance_uploader_list); // set up long click listener mUploadButton = (Button) findViewById(R.id.upload_button); mUploadButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo ni = connectivityManager.getActiveNetworkInfo(); if (NetworkReceiver.running == true) { Toast.makeText( InstanceUploaderList.this, "Background send running, please try again shortly", Toast.LENGTH_SHORT).show(); } else if (ni == null || !ni.isConnected()) { Collect.getInstance().getActivityLogger() .logAction(this, "uploadButton", "noConnection"); Toast.makeText(InstanceUploaderList.this, R.string.no_connection, Toast.LENGTH_SHORT).show(); } else { Collect.getInstance() .getActivityLogger() .logAction(this, "uploadButton", Integer.toString(mSelected.size())); if (mSelected.size() > 0) { // items selected uploadSelectedFiles(); mToggled = false; mSelected.clear(); InstanceUploaderList.this.getListView().clearChoices(); mUploadButton.setEnabled(false); } else { // no items selected Toast.makeText(getApplicationContext(), getString(R.string.noselect_error), Toast.LENGTH_SHORT).show(); } } } }); mToggleButton = (Button) findViewById(R.id.toggle_button); mToggleButton.setLongClickable(true); mToggleButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // toggle selections of items to all or none ListView ls = getListView(); mToggled = !mToggled; Collect.getInstance() .getActivityLogger() .logAction(this, "toggleButton", Boolean.toString(mToggled)); // remove all items from selected list mSelected.clear(); for (int pos = 0; pos < ls.getCount(); pos++) { ls.setItemChecked(pos, mToggled); // add all items if mToggled sets to select all if (mToggled) mSelected.add(ls.getItemIdAtPosition(pos)); } mUploadButton.setEnabled(!(mSelected.size() == 0)); } }); mToggleButton.setOnLongClickListener(this); Cursor c = mShowUnsent ? getUnsentCursor() : getAllCursor(); String[] data = new String[] { InstanceColumns.DISPLAY_NAME, InstanceColumns.DISPLAY_SUBTEXT }; int[] view = new int[] { R.id.text1, R.id.text2 }; // render total instance view mInstances = new SimpleCursorAdapter(this, R.layout.two_item_multiple_choice, c, data, view); setListAdapter(mInstances); getListView().setChoiceMode(ListView.CHOICE_MODE_MULTIPLE); getListView().setItemsCanFocus(false); mUploadButton.setEnabled(!(mSelected.size() == 0)); // set title setTitle(getString(R.string.app_name) + " > " + getString(R.string.send_data)); // if current activity is being reinitialized due to changing // orientation restore all check // marks for ones selected if (mRestored) { ListView ls = getListView(); for (long id : mSelected) { for (int pos = 0; pos < ls.getCount(); pos++) { if (id == ls.getItemIdAtPosition(pos)) { ls.setItemChecked(pos, true); break; } } } mRestored = false; } } @Override protected void onStart() { super.onStart(); Collect.getInstance().getActivityLogger().logOnStart(this); } @Override protected void onStop() { Collect.getInstance().getActivityLogger().logOnStop(this); super.onStop(); } private void uploadSelectedFiles() { // send list of _IDs. long[] instanceIDs = new long[mSelected.size()]; for (int i = 0; i < mSelected.size(); i++) { instanceIDs[i] = mSelected.get(i); } SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); String server = prefs.getString(PreferencesActivity.KEY_PROTOCOL, null); if (server.equalsIgnoreCase(getString(R.string.protocol_google_maps_engine))) { // if it's maps engine, start the maps-engine uploader // first make sure we have a google account selected String googleUsername = prefs.getString( PreferencesActivity.KEY_SELECTED_GOOGLE_ACCOUNT, null); if (googleUsername == null || googleUsername.equals("")) { showDialog(GOOGLE_USER_DIALOG); return; } Intent i = new Intent(this, GoogleMapsEngineUploaderActivity.class); i.putExtra(FormEntryActivity.KEY_INSTANCES, instanceIDs); startActivityForResult(i, INSTANCE_UPLOADER); } else { // otherwise, do the normal agregate/other thing. Intent i = new Intent(this, InstanceUploaderActivity.class); i.putExtra(FormEntryActivity.KEY_INSTANCES, instanceIDs); startActivityForResult(i, INSTANCE_UPLOADER); } } @Override public boolean onCreateOptionsMenu(Menu menu) { Collect.getInstance().getActivityLogger() .logAction(this, "onCreateOptionsMenu", "show"); super.onCreateOptionsMenu(menu); CompatibilityUtils.setShowAsAction( menu.add(0, MENU_PREFERENCES, 0, R.string.general_preferences) .setIcon(R.drawable.ic_menu_preferences), MenuItem.SHOW_AS_ACTION_NEVER); CompatibilityUtils.setShowAsAction( menu.add(0, MENU_SHOW_UNSENT, 1, R.string.change_view) .setIcon(R.drawable.ic_menu_manage), MenuItem.SHOW_AS_ACTION_NEVER); return true; } @Override public boolean onMenuItemSelected(int featureId, MenuItem item) { switch (item.getItemId()) { case MENU_PREFERENCES: Collect.getInstance().getActivityLogger() .logAction(this, "onMenuItemSelected", "MENU_PREFERENCES"); createPreferencesMenu(); return true; case MENU_SHOW_UNSENT: Collect.getInstance().getActivityLogger() .logAction(this, "onMenuItemSelected", "MENU_SHOW_UNSENT"); showSentAndUnsentChoices(); return true; } return super.onMenuItemSelected(featureId, item); } private void createPreferencesMenu() { Intent i = new Intent(this, PreferencesActivity.class); startActivity(i); } @Override protected void onListItemClick(ListView l, View v, int position, long id) { super.onListItemClick(l, v, position, id); // get row id from db Cursor c = (Cursor) getListAdapter().getItem(position); long k = c.getLong(c.getColumnIndex(InstanceColumns._ID)); Collect.getInstance().getActivityLogger() .logAction(this, "onListItemClick", Long.toString(k)); // add/remove from selected list if (mSelected.contains(k)) mSelected.remove(k); else mSelected.add(k); mUploadButton.setEnabled(!(mSelected.size() == 0)); } @Override protected void onRestoreInstanceState(Bundle savedInstanceState) { super.onRestoreInstanceState(savedInstanceState); long[] selectedArray = savedInstanceState .getLongArray(BUNDLE_SELECTED_ITEMS_KEY); for (int i = 0; i < selectedArray.length; i++) mSelected.add(selectedArray[i]); mToggled = savedInstanceState.getBoolean(BUNDLE_TOGGLED_KEY); mRestored = true; mUploadButton.setEnabled(selectedArray.length > 0); } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); long[] selectedArray = new long[mSelected.size()]; for (int i = 0; i < mSelected.size(); i++) selectedArray[i] = mSelected.get(i); outState.putLongArray(BUNDLE_SELECTED_ITEMS_KEY, selectedArray); outState.putBoolean(BUNDLE_TOGGLED_KEY, mToggled); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent intent) { if (resultCode == RESULT_CANCELED) { return; } switch (requestCode) { // returns with a form path, start entry case INSTANCE_UPLOADER: if (intent.getBooleanExtra(FormEntryActivity.KEY_SUCCESS, false)) { mSelected.clear(); getListView().clearChoices(); if (mInstances.isEmpty()) { finish(); } } break; default: break; } super.onActivityResult(requestCode, resultCode, intent); } private void showUnsent() { mShowUnsent = true; Cursor c = mShowUnsent ? getUnsentCursor() : getAllCursor(); Cursor old = mInstances.getCursor(); try { mInstances.changeCursor(c); } finally { if (old != null) { old.close(); this.stopManagingCursor(old); } } getListView().invalidate(); } private void showAll() { mShowUnsent = false; Cursor c = mShowUnsent ? getUnsentCursor() : getAllCursor(); Cursor old = mInstances.getCursor(); try { mInstances.changeCursor(c); } finally { if (old != null) { old.close(); this.stopManagingCursor(old); } } getListView().invalidate(); } @Override public boolean onLongClick(View v) { Collect.getInstance() .getActivityLogger() .logAction(this, "toggleButton.longClick", Boolean.toString(mToggled)); return showSentAndUnsentChoices(); } private boolean showSentAndUnsentChoices() { /** * Create a dialog with options to save and exit, save, or quit without * saving */ String[] items = { getString(R.string.show_unsent_forms), getString(R.string.show_sent_and_unsent_forms) }; Collect.getInstance().getActivityLogger() .logAction(this, "changeView", "show"); AlertDialog alertDialog = new AlertDialog.Builder(this) .setIcon(android.R.drawable.ic_dialog_info) .setTitle(getString(R.string.change_view)) .setNeutralButton(getString(R.string.cancel), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int id) { Collect.getInstance() .getActivityLogger() .logAction(this, "changeView", "cancel"); dialog.cancel(); } }) .setItems(items, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { switch (which) { case 0: // show unsent Collect.getInstance() .getActivityLogger() .logAction(this, "changeView", "showUnsent"); InstanceUploaderList.this.showUnsent(); break; case 1: // show all Collect.getInstance().getActivityLogger() .logAction(this, "changeView", "showAll"); InstanceUploaderList.this.showAll(); break; case 2:// do nothing break; } } }).create(); alertDialog.show(); return true; } @Override protected Dialog onCreateDialog(int id) { switch (id) { case GOOGLE_USER_DIALOG: AlertDialog.Builder gudBuilder = new AlertDialog.Builder(this); gudBuilder.setTitle(R.string.no_google_account); gudBuilder .setMessage("You have selected Google Maps Engine as your server, please select a corresponding Google Account in the General Settings before continuing"); gudBuilder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }); gudBuilder.setCancelable(false); return gudBuilder.create(); } return null; } }
Java
/* * Copyright (C) 2012 University of Washington * 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 org.odk.collect.android.activities; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import org.odk.collect.android.R; import org.odk.collect.android.application.Collect; import org.odk.collect.android.utilities.ColorPickerDialog; import org.odk.collect.android.utilities.FileUtils; import android.app.Activity; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.pm.ActivityInfo; import android.content.res.Configuration; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Path; import android.graphics.PorterDuff; import android.net.Uri; import android.os.Bundle; import android.util.Log; import android.view.Display; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.Window; import android.view.WindowManager; import android.widget.Button; import android.widget.LinearLayout; import android.widget.RelativeLayout; /** * Modified from the FingerPaint example found in The Android Open Source * Project. * * @author BehrAtherton@gmail.com * */ public class DrawActivity extends Activity { public static final String t = "DrawActivity"; public static final String OPTION = "option"; public static final String OPTION_SIGNATURE = "signature"; public static final String OPTION_ANNOTATE = "annotate"; public static final String OPTION_DRAW = "draw"; public static final String REF_IMAGE = "refImage"; public static final String EXTRA_OUTPUT = android.provider.MediaStore.EXTRA_OUTPUT; public static final String SAVEPOINT_IMAGE = "savepointImage"; // during // restore // incoming options... private String loadOption = null; private File refImage = null; private File output = null; private File savepointImage = null; private Button btnDrawColor; private Button btnFinished; private Button btnReset; private Button btnCancel; private Paint paint; private Paint pointPaint; private int currentColor = 0xFF000000; private DrawView drawView; private String alertTitleString; private AlertDialog alertDialog; @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); try { saveFile(savepointImage); } catch (FileNotFoundException e) { e.printStackTrace(); } if ( savepointImage.exists() ) { outState.putString(SAVEPOINT_IMAGE, savepointImage.getAbsolutePath()); } } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); Bundle extras = getIntent().getExtras(); if (extras == null) { loadOption = OPTION_DRAW; refImage = null; savepointImage = new File(Collect.TMPDRAWFILE_PATH); savepointImage.delete(); output = new File(Collect.TMPFILE_PATH); } else { loadOption = extras.getString(OPTION); if (loadOption == null) { loadOption = OPTION_DRAW; } // refImage can also be present if resuming a drawing Uri uri = (Uri) extras.get(REF_IMAGE); if (uri != null) { refImage = new File(uri.getPath()); } String savepoint = extras.getString(SAVEPOINT_IMAGE); if (savepoint != null) { savepointImage = new File(savepoint); if (!savepointImage.exists() && refImage != null && refImage.exists()) { FileUtils.copyFile(refImage, savepointImage); } } else { savepointImage = new File(Collect.TMPDRAWFILE_PATH); savepointImage.delete(); if (refImage != null && refImage.exists()) { FileUtils.copyFile(refImage, savepointImage); } } uri = (Uri) extras.get(EXTRA_OUTPUT); if (uri != null) { output = new File(uri.getPath()); } else { output = new File(Collect.TMPFILE_PATH); } } // At this point, we have: // loadOption -- type of activity (draw, signature, annotate) // refImage -- original image to work with // savepointImage -- drawing to use as a starting point (may be copy of // original) // output -- where the output should be written if (OPTION_SIGNATURE.equals(loadOption)) { // set landscape setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); alertTitleString = getString(R.string.quit_application, getString(R.string.sign_button)); } else if (OPTION_ANNOTATE.equals(loadOption)) { setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); alertTitleString = getString(R.string.quit_application, getString(R.string.markup_image)); } else { alertTitleString = getString(R.string.quit_application, getString(R.string.draw_image)); } setTitle(getString(R.string.app_name) + " > " + getString(R.string.draw_image)); LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE); RelativeLayout v = (RelativeLayout) inflater.inflate( R.layout.draw_layout, null); LinearLayout ll = (LinearLayout) v.findViewById(R.id.drawViewLayout); drawView = new DrawView(this, OPTION_SIGNATURE.equals(loadOption), savepointImage); ll.addView(drawView); setContentView(v); paint = new Paint(); paint.setAntiAlias(true); paint.setDither(true); paint.setColor(currentColor); paint.setStyle(Paint.Style.STROKE); paint.setStrokeJoin(Paint.Join.ROUND); paint.setStrokeWidth(10); pointPaint = new Paint(); pointPaint.setAntiAlias(true); pointPaint.setDither(true); pointPaint.setColor(currentColor); pointPaint.setStyle(Paint.Style.FILL_AND_STROKE); pointPaint.setStrokeWidth(10); btnDrawColor = (Button) findViewById(R.id.btnSelectColor); btnDrawColor.setTextColor(getInverseColor(currentColor)); btnDrawColor.getBackground().setColorFilter(currentColor, PorterDuff.Mode.SRC_ATOP); btnDrawColor.setText(getString(R.string.set_color)); btnDrawColor.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { Collect.getInstance() .getActivityLogger() .logInstanceAction( DrawActivity.this, "setColorButton", "click", Collect.getInstance().getFormController() .getFormIndex()); ColorPickerDialog cpd = new ColorPickerDialog( DrawActivity.this, new ColorPickerDialog.OnColorChangedListener() { public void colorChanged(String key, int color) { btnDrawColor .setTextColor(getInverseColor(color)); btnDrawColor.getBackground().setColorFilter( color, PorterDuff.Mode.SRC_ATOP); currentColor = color; paint.setColor(color); pointPaint.setColor(color); } }, "key", currentColor, currentColor, getString(R.string.select_drawing_color)); cpd.show(); } }); btnFinished = (Button) findViewById(R.id.btnFinishDraw); btnFinished.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Collect.getInstance() .getActivityLogger() .logInstanceAction( DrawActivity.this, "saveAndCloseButton", "click", Collect.getInstance().getFormController() .getFormIndex()); SaveAndClose(); } }); btnReset = (Button) findViewById(R.id.btnResetDraw); btnReset.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Collect.getInstance() .getActivityLogger() .logInstanceAction( DrawActivity.this, "resetButton", "click", Collect.getInstance().getFormController() .getFormIndex()); Reset(); } }); btnCancel = (Button) findViewById(R.id.btnCancelDraw); btnCancel.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Collect.getInstance() .getActivityLogger() .logInstanceAction( DrawActivity.this, "cancelAndCloseButton", "click", Collect.getInstance().getFormController() .getFormIndex()); CancelAndClose(); } }); } private int getInverseColor(int color) { int red = Color.red(color); int green = Color.green(color); int blue = Color.blue(color); int alpha = Color.alpha(color); return Color.argb(alpha, 255 - red, 255 - green, 255 - blue); } private void SaveAndClose() { try { saveFile(output); setResult(Activity.RESULT_OK); } catch (FileNotFoundException e) { e.printStackTrace(); setResult(Activity.RESULT_CANCELED); } this.finish(); } private void saveFile(File f) throws FileNotFoundException { if ( drawView.getWidth() == 0 || drawView.getHeight() == 0 ) { // apparently on 4.x, the orientation change notification can occur // sometime before the view is rendered. In that case, the view // dimensions will not be known. Log.e(t,"view has zero width or zero height"); } else { FileOutputStream fos; fos = new FileOutputStream(f); Bitmap bitmap = Bitmap.createBitmap(drawView.getWidth(), drawView.getHeight(), Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(bitmap); drawView.draw(canvas); bitmap.compress(Bitmap.CompressFormat.JPEG, 70, fos); try { if ( fos != null ) { fos.flush(); fos.close(); } } catch ( Exception e) { } } } private void Reset() { savepointImage.delete(); if (!OPTION_SIGNATURE.equals(loadOption) && refImage != null && refImage.exists()) { FileUtils.copyFile(refImage, savepointImage); } drawView.reset(); drawView.invalidate(); } private void CancelAndClose() { setResult(Activity.RESULT_CANCELED); this.finish(); } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { switch (keyCode) { case KeyEvent.KEYCODE_BACK: Collect.getInstance().getActivityLogger() .logInstanceAction(this, "onKeyDown.KEYCODE_BACK", "quit"); createQuitDrawDialog(); return true; case KeyEvent.KEYCODE_DPAD_RIGHT: if (event.isAltPressed()) { Collect.getInstance() .getActivityLogger() .logInstanceAction(this, "onKeyDown.KEYCODE_DPAD_RIGHT", "showNext"); createQuitDrawDialog(); return true; } break; case KeyEvent.KEYCODE_DPAD_LEFT: if (event.isAltPressed()) { Collect.getInstance() .getActivityLogger() .logInstanceAction(this, "onKeyDown.KEYCODE_DPAD_LEFT", "showPrevious"); createQuitDrawDialog(); return true; } break; } return super.onKeyDown(keyCode, event); } /** * Create a dialog with options to save and exit, save, or quit without * saving */ private void createQuitDrawDialog() { String[] items = { getString(R.string.keep_changes), getString(R.string.do_not_save) }; Collect.getInstance().getActivityLogger() .logInstanceAction(this, "createQuitDrawDialog", "show"); alertDialog = new AlertDialog.Builder(this) .setIcon(android.R.drawable.ic_dialog_info) .setTitle(alertTitleString) .setNeutralButton(getString(R.string.do_not_exit), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int id) { Collect.getInstance() .getActivityLogger() .logInstanceAction(this, "createQuitDrawDialog", "cancel"); dialog.cancel(); } }) .setItems(items, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { switch (which) { case 0: // save and exit Collect.getInstance() .getActivityLogger() .logInstanceAction(this, "createQuitDrawDialog", "saveAndExit"); SaveAndClose(); break; case 1: // discard changes and exit Collect.getInstance() .getActivityLogger() .logInstanceAction(this, "createQuitDrawDialog", "discardAndExit"); CancelAndClose(); break; case 2:// do nothing Collect.getInstance() .getActivityLogger() .logInstanceAction(this, "createQuitDrawDialog", "cancel"); break; } } }).create(); alertDialog.show(); } public class DrawView extends View { private boolean isSignature; private Bitmap mBitmap; private Canvas mCanvas; private Path mCurrentPath; private Paint mBitmapPaint; private File mBackgroundBitmapFile; public DrawView(final Context c) { super(c); isSignature = false; mBitmapPaint = new Paint(Paint.DITHER_FLAG); mCurrentPath = new Path(); setBackgroundColor(0xFFFFFFFF); mBackgroundBitmapFile = new File(Collect.TMPDRAWFILE_PATH); } public DrawView(Context c, boolean isSignature, File f) { this(c); this.isSignature = isSignature; mBackgroundBitmapFile = f; } public void reset() { Display display = ((WindowManager) getContext().getSystemService( Context.WINDOW_SERVICE)).getDefaultDisplay(); int screenWidth = display.getWidth(); int screenHeight = display.getHeight(); resetImage(screenWidth, screenHeight); } public void resetImage(int w, int h) { if (mBackgroundBitmapFile.exists()) { mBitmap = FileUtils.getBitmapScaledToDisplay( mBackgroundBitmapFile, w, h).copy( Bitmap.Config.ARGB_8888, true); // mBitmap = // Bitmap.createScaledBitmap(BitmapFactory.decodeFile(mBackgroundBitmapFile.getPath()), // w, h, true); mCanvas = new Canvas(mBitmap); } else { mBitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888); mCanvas = new Canvas(mBitmap); mCanvas.drawColor(0xFFFFFFFF); if (isSignature) drawSignLine(); } } @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { super.onSizeChanged(w, h, oldw, oldh); resetImage(w, h); } @Override protected void onDraw(Canvas canvas) { canvas.drawColor(0xFFAAAAAA); canvas.drawBitmap(mBitmap, 0, 0, mBitmapPaint); canvas.drawPath(mCurrentPath, paint); } private float mX, mY; private void touch_start(float x, float y) { mCurrentPath.reset(); mCurrentPath.moveTo(x, y); mX = x; mY = y; } public void drawSignLine() { mCanvas.drawLine(0, (int) (mCanvas.getHeight() * .7), mCanvas.getWidth(), (int) (mCanvas.getHeight() * .7), paint); } private void touch_move(float x, float y) { mCurrentPath.quadTo(mX, mY, (x + mX) / 2, (y + mY) / 2); mX = x; mY = y; } private void touch_up() { if (mCurrentPath.isEmpty()) { mCanvas.drawPoint(mX, mY, pointPaint); } else { mCurrentPath.lineTo(mX, mY); // commit the path to our offscreen mCanvas.drawPath(mCurrentPath, paint); } // kill this so we don't double draw mCurrentPath.reset(); } @Override public boolean onTouchEvent(MotionEvent event) { float x = event.getX(); float y = event.getY(); switch (event.getAction()) { case MotionEvent.ACTION_DOWN: touch_start(x, y); invalidate(); break; case MotionEvent.ACTION_MOVE: touch_move(x, y); invalidate(); break; case MotionEvent.ACTION_UP: touch_up(); invalidate(); break; } return true; } } }
Java
/* * Copyright (C) 2009 University of Washington * * 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 org.odk.collect.android.activities; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.ObjectInputStream; import java.lang.ref.WeakReference; import java.util.Map; import java.util.Map.Entry; import org.odk.collect.android.R; import org.odk.collect.android.application.Collect; import org.odk.collect.android.preferences.AdminPreferencesActivity; import org.odk.collect.android.preferences.PreferencesActivity; import org.odk.collect.android.provider.InstanceProviderAPI; import org.odk.collect.android.provider.InstanceProviderAPI.InstanceColumns; import org.odk.collect.android.utilities.CompatibilityUtils; import android.app.Activity; 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.database.ContentObserver; import android.database.Cursor; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.preference.PreferenceManager; import android.text.InputType; import android.text.method.PasswordTransformationMethod; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.view.WindowManager; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; /** * Responsible for displaying buttons to launch the major activities. Launches * some activities based on returns of others. * * @author Carl Hartung (carlhartung@gmail.com) * @author Yaw Anokwa (yanokwa@gmail.com) */ public class MainMenuActivity extends Activity { private static final String t = "MainMenuActivity"; private static final int PASSWORD_DIALOG = 1; // menu options private static final int MENU_PREFERENCES = Menu.FIRST; private static final int MENU_ADMIN = Menu.FIRST + 1; // buttons private Button mEnterDataButton; private Button mManageFilesButton; private Button mSendDataButton; private Button mReviewDataButton; private Button mGetFormsButton; private View mReviewSpacer; private View mGetFormsSpacer; private AlertDialog mAlertDialog; private SharedPreferences mAdminPreferences; private int mCompletedCount; private int mSavedCount; private Cursor mFinalizedCursor; private Cursor mSavedCursor; private IncomingHandler mHandler = new IncomingHandler(this); private MyContentObserver mContentObserver = new MyContentObserver(); private static boolean EXIT = true; // private static boolean DO_NOT_EXIT = false; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // must be at the beginning of any activity that can be called from an // external intent Log.i(t, "Starting up, creating directories"); try { Collect.createODKDirs(); } catch (RuntimeException e) { createErrorDialog(e.getMessage(), EXIT); return; } setContentView(R.layout.main_menu); { // dynamically construct the "ODK Collect vA.B" string TextView mainMenuMessageLabel = (TextView) findViewById(R.id.main_menu_header); mainMenuMessageLabel.setText(Collect.getInstance() .getVersionedAppName()); } setTitle(getString(R.string.app_name) + " > " + getString(R.string.main_menu)); File f = new File(Collect.ODK_ROOT + "/collect.settings"); if (f.exists()) { boolean success = loadSharedPreferencesFromFile(f); if (success) { Toast.makeText(this, "Settings successfully loaded from file", Toast.LENGTH_LONG).show(); f.delete(); } else { Toast.makeText( this, "Sorry, settings file is corrupt and should be deleted or replaced", Toast.LENGTH_LONG).show(); } } mReviewSpacer = findViewById(R.id.review_spacer); mGetFormsSpacer = findViewById(R.id.get_forms_spacer); mAdminPreferences = this.getSharedPreferences( AdminPreferencesActivity.ADMIN_PREFERENCES, 0); // enter data button. expects a result. mEnterDataButton = (Button) findViewById(R.id.enter_data); mEnterDataButton.setText(getString(R.string.enter_data_button)); mEnterDataButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Collect.getInstance().getActivityLogger() .logAction(this, "fillBlankForm", "click"); Intent i = new Intent(getApplicationContext(), FormChooserList.class); startActivity(i); } }); // review data button. expects a result. mReviewDataButton = (Button) findViewById(R.id.review_data); mReviewDataButton.setText(getString(R.string.review_data_button)); mReviewDataButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Collect.getInstance().getActivityLogger() .logAction(this, "editSavedForm", "click"); Intent i = new Intent(getApplicationContext(), InstanceChooserList.class); startActivity(i); } }); // send data button. expects a result. mSendDataButton = (Button) findViewById(R.id.send_data); mSendDataButton.setText(getString(R.string.send_data_button)); mSendDataButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Collect.getInstance().getActivityLogger() .logAction(this, "uploadForms", "click"); Intent i = new Intent(getApplicationContext(), InstanceUploaderList.class); startActivity(i); } }); // manage forms button. no result expected. mGetFormsButton = (Button) findViewById(R.id.get_forms); mGetFormsButton.setText(getString(R.string.get_forms)); mGetFormsButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Collect.getInstance().getActivityLogger() .logAction(this, "downloadBlankForms", "click"); SharedPreferences sharedPreferences = PreferenceManager .getDefaultSharedPreferences(MainMenuActivity.this); String protocol = sharedPreferences.getString( PreferencesActivity.KEY_PROTOCOL, getString(R.string.protocol_odk_default)); Intent i = null; if (protocol.equalsIgnoreCase(getString(R.string.protocol_google_maps_engine))) { i = new Intent(getApplicationContext(), GoogleDriveActivity.class); } else { i = new Intent(getApplicationContext(), FormDownloadList.class); } startActivity(i); } }); // manage forms button. no result expected. mManageFilesButton = (Button) findViewById(R.id.manage_forms); mManageFilesButton.setText(getString(R.string.manage_files)); mManageFilesButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Collect.getInstance().getActivityLogger() .logAction(this, "deleteSavedForms", "click"); Intent i = new Intent(getApplicationContext(), FileManagerTabs.class); startActivity(i); } }); // count for finalized instances String selection = InstanceColumns.STATUS + "=? or " + InstanceColumns.STATUS + "=?"; String selectionArgs[] = { InstanceProviderAPI.STATUS_COMPLETE, InstanceProviderAPI.STATUS_SUBMISSION_FAILED }; try { mFinalizedCursor = managedQuery(InstanceColumns.CONTENT_URI, null, selection, selectionArgs, null); } catch (Exception e) { createErrorDialog(e.getMessage(), EXIT); return; } if (mFinalizedCursor != null) { startManagingCursor(mFinalizedCursor); } mCompletedCount = mFinalizedCursor != null ? mFinalizedCursor.getCount() : 0; getContentResolver().registerContentObserver(InstanceColumns.CONTENT_URI, true, mContentObserver); // mFinalizedCursor.registerContentObserver(mContentObserver); // count for finalized instances String selectionSaved = InstanceColumns.STATUS + "=?"; String selectionArgsSaved[] = { InstanceProviderAPI.STATUS_INCOMPLETE }; try { mSavedCursor = managedQuery(InstanceColumns.CONTENT_URI, null, selectionSaved, selectionArgsSaved, null); } catch (Exception e) { createErrorDialog(e.getMessage(), EXIT); return; } if (mSavedCursor != null) { startManagingCursor(mSavedCursor); } mSavedCount = mSavedCursor != null ? mSavedCursor.getCount() : 0; // don't need to set a content observer because it can't change in the // background updateButtons(); } @Override protected void onResume() { super.onResume(); SharedPreferences sharedPreferences = this.getSharedPreferences( AdminPreferencesActivity.ADMIN_PREFERENCES, 0); boolean edit = sharedPreferences.getBoolean( AdminPreferencesActivity.KEY_EDIT_SAVED, true); if (!edit) { mReviewDataButton.setVisibility(View.GONE); mReviewSpacer.setVisibility(View.GONE); } else { mReviewDataButton.setVisibility(View.VISIBLE); mReviewSpacer.setVisibility(View.VISIBLE); } boolean send = sharedPreferences.getBoolean( AdminPreferencesActivity.KEY_SEND_FINALIZED, true); if (!send) { mSendDataButton.setVisibility(View.GONE); } else { mSendDataButton.setVisibility(View.VISIBLE); } boolean get_blank = sharedPreferences.getBoolean( AdminPreferencesActivity.KEY_GET_BLANK, true); if (!get_blank) { mGetFormsButton.setVisibility(View.GONE); mGetFormsSpacer.setVisibility(View.GONE); } else { mGetFormsButton.setVisibility(View.VISIBLE); mGetFormsSpacer.setVisibility(View.VISIBLE); } boolean delete_saved = sharedPreferences.getBoolean( AdminPreferencesActivity.KEY_DELETE_SAVED, true); if (!delete_saved) { mManageFilesButton.setVisibility(View.GONE); } else { mManageFilesButton.setVisibility(View.VISIBLE); } } @Override protected void onPause() { super.onPause(); if (mAlertDialog != null && mAlertDialog.isShowing()) { mAlertDialog.dismiss(); } } @Override protected void onStart() { super.onStart(); Collect.getInstance().getActivityLogger().logOnStart(this); } @Override protected void onStop() { Collect.getInstance().getActivityLogger().logOnStop(this); super.onStop(); } @Override public boolean onCreateOptionsMenu(Menu menu) { Collect.getInstance().getActivityLogger() .logAction(this, "onCreateOptionsMenu", "show"); super.onCreateOptionsMenu(menu); CompatibilityUtils.setShowAsAction( menu.add(0, MENU_PREFERENCES, 0, R.string.general_preferences) .setIcon(R.drawable.ic_menu_preferences), MenuItem.SHOW_AS_ACTION_NEVER); CompatibilityUtils.setShowAsAction( menu.add(0, MENU_ADMIN, 0, R.string.admin_preferences) .setIcon(R.drawable.ic_menu_login), MenuItem.SHOW_AS_ACTION_NEVER); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case MENU_PREFERENCES: Collect.getInstance() .getActivityLogger() .logAction(this, "onOptionsItemSelected", "MENU_PREFERENCES"); Intent ig = new Intent(this, PreferencesActivity.class); startActivity(ig); return true; case MENU_ADMIN: Collect.getInstance().getActivityLogger() .logAction(this, "onOptionsItemSelected", "MENU_ADMIN"); String pw = mAdminPreferences.getString( AdminPreferencesActivity.KEY_ADMIN_PW, ""); if ("".equalsIgnoreCase(pw)) { Intent i = new Intent(getApplicationContext(), AdminPreferencesActivity.class); startActivity(i); } else { showDialog(PASSWORD_DIALOG); Collect.getInstance().getActivityLogger() .logAction(this, "createAdminPasswordDialog", "show"); } return true; } return super.onOptionsItemSelected(item); } private void createErrorDialog(String errorMsg, final boolean shouldExit) { Collect.getInstance().getActivityLogger() .logAction(this, "createErrorDialog", "show"); mAlertDialog = new AlertDialog.Builder(this).create(); mAlertDialog.setIcon(android.R.drawable.ic_dialog_info); mAlertDialog.setMessage(errorMsg); DialogInterface.OnClickListener errorListener = new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int i) { switch (i) { case DialogInterface.BUTTON_POSITIVE: Collect.getInstance() .getActivityLogger() .logAction(this, "createErrorDialog", shouldExit ? "exitApplication" : "OK"); if (shouldExit) { finish(); } break; } } }; mAlertDialog.setCancelable(false); mAlertDialog.setButton(getString(R.string.ok), errorListener); mAlertDialog.show(); } @Override protected Dialog onCreateDialog(int id) { switch (id) { case PASSWORD_DIALOG: AlertDialog.Builder builder = new AlertDialog.Builder(this); final AlertDialog passwordDialog = builder.create(); passwordDialog.setTitle(getString(R.string.enter_admin_password)); final EditText input = new EditText(this); input.setInputType(InputType.TYPE_TEXT_VARIATION_PASSWORD); input.setTransformationMethod(PasswordTransformationMethod .getInstance()); passwordDialog.setView(input, 20, 10, 20, 10); passwordDialog.setButton(AlertDialog.BUTTON_POSITIVE, getString(R.string.ok), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { String value = input.getText().toString(); String pw = mAdminPreferences.getString( AdminPreferencesActivity.KEY_ADMIN_PW, ""); if (pw.compareTo(value) == 0) { Intent i = new Intent(getApplicationContext(), AdminPreferencesActivity.class); startActivity(i); input.setText(""); passwordDialog.dismiss(); } else { Toast.makeText( MainMenuActivity.this, getString(R.string.admin_password_incorrect), Toast.LENGTH_SHORT).show(); Collect.getInstance() .getActivityLogger() .logAction(this, "adminPasswordDialog", "PASSWORD_INCORRECT"); } } }); passwordDialog.setButton(AlertDialog.BUTTON_NEGATIVE, getString(R.string.cancel), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { Collect.getInstance() .getActivityLogger() .logAction(this, "adminPasswordDialog", "cancel"); input.setText(""); return; } }); passwordDialog.getWindow().setSoftInputMode( WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE); return passwordDialog; } return null; } private void updateButtons() { if (mFinalizedCursor != null && !mFinalizedCursor.isClosed()) { mFinalizedCursor.requery(); mCompletedCount = mFinalizedCursor.getCount(); if (mCompletedCount > 0) { mSendDataButton.setText(getString(R.string.send_data_button, mCompletedCount)); } else { mSendDataButton.setText(getString(R.string.send_data)); } } else { mSendDataButton.setText(getString(R.string.send_data)); Log.w(t, "Cannot update \"Send Finalized\" button label since the database is closed. Perhaps the app is running in the background?"); } if (mSavedCursor != null && !mSavedCursor.isClosed()) { mSavedCursor.requery(); mSavedCount = mSavedCursor.getCount(); if (mSavedCount > 0) { mReviewDataButton.setText(getString(R.string.review_data_button, mSavedCount)); } else { mReviewDataButton.setText(getString(R.string.review_data)); } } else { mReviewDataButton.setText(getString(R.string.review_data)); Log.w(t, "Cannot update \"Edit Form\" button label since the database is closed. Perhaps the app is running in the background?"); } } /** * notifies us that something changed * */ private class MyContentObserver extends ContentObserver { public MyContentObserver() { super(null); } @Override public void onChange(boolean selfChange) { super.onChange(selfChange); mHandler.sendEmptyMessage(0); } } /* * Used to prevent memory leaks */ static class IncomingHandler extends Handler { private final WeakReference<MainMenuActivity> mTarget; IncomingHandler(MainMenuActivity target) { mTarget = new WeakReference<MainMenuActivity>(target); } @Override public void handleMessage(Message msg) { MainMenuActivity target = mTarget.get(); if (target != null) { target.updateButtons(); } } } private boolean loadSharedPreferencesFromFile(File src) { // this should probably be in a thread if it ever gets big boolean res = false; ObjectInputStream input = null; try { input = new ObjectInputStream(new FileInputStream(src)); Editor prefEdit = PreferenceManager.getDefaultSharedPreferences( this).edit(); prefEdit.clear(); // first object is preferences Map<String, ?> entries = (Map<String, ?>) input.readObject(); for (Entry<String, ?> entry : entries.entrySet()) { Object v = entry.getValue(); String key = entry.getKey(); if (v instanceof Boolean) prefEdit.putBoolean(key, ((Boolean) v).booleanValue()); else if (v instanceof Float) prefEdit.putFloat(key, ((Float) v).floatValue()); else if (v instanceof Integer) prefEdit.putInt(key, ((Integer) v).intValue()); else if (v instanceof Long) prefEdit.putLong(key, ((Long) v).longValue()); else if (v instanceof String) prefEdit.putString(key, ((String) v)); } prefEdit.commit(); // second object is admin options Editor adminEdit = getSharedPreferences(AdminPreferencesActivity.ADMIN_PREFERENCES, 0).edit(); adminEdit.clear(); // first object is preferences Map<String, ?> adminEntries = (Map<String, ?>) input.readObject(); for (Entry<String, ?> entry : adminEntries.entrySet()) { Object v = entry.getValue(); String key = entry.getKey(); if (v instanceof Boolean) adminEdit.putBoolean(key, ((Boolean) v).booleanValue()); else if (v instanceof Float) adminEdit.putFloat(key, ((Float) v).floatValue()); else if (v instanceof Integer) adminEdit.putInt(key, ((Integer) v).intValue()); else if (v instanceof Long) adminEdit.putLong(key, ((Long) v).longValue()); else if (v instanceof String) adminEdit.putString(key, ((String) v)); } adminEdit.commit(); res = true; } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } finally { try { if (input != null) { input.close(); } } catch (IOException ex) { ex.printStackTrace(); } } return res; } }
Java
/* * Copyright (C) 2011 University of Washington * * 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 org.odk.collect.android.activities; import java.util.ArrayList; import org.odk.collect.android.R; import org.odk.collect.android.provider.FormsProviderAPI.FormsColumns; import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.DialogInterface.OnCancelListener; import android.content.Intent; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.os.Parcelable; /** * Allows the user to create desktop shortcuts to any form currently avaiable to Collect * * @author ctsims * @author carlhartung (modified for ODK) */ public class AndroidShortcuts extends Activity { private Uri[] mCommands; private String[] mNames; @Override public void onCreate(Bundle bundle) { super.onCreate(bundle); final Intent intent = getIntent(); final String action = intent.getAction(); // The Android needs to know what shortcuts are available, generate the list if (Intent.ACTION_CREATE_SHORTCUT.equals(action)) { buildMenuList(); } } /** * Builds a list of shortcuts */ private void buildMenuList() { ArrayList<String> names = new ArrayList<String>(); ArrayList<Uri> commands = new ArrayList<Uri>(); AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle("Select ODK Shortcut"); Cursor c = null; try { c = getContentResolver().query(FormsColumns.CONTENT_URI, null, null, null, null); if (c.getCount() > 0) { c.moveToPosition(-1); while (c.moveToNext()) { String formName = c.getString(c.getColumnIndex(FormsColumns.DISPLAY_NAME)); names.add(formName); Uri uri = Uri.withAppendedPath(FormsColumns.CONTENT_URI, c.getString(c.getColumnIndex(FormsColumns._ID))); commands.add(uri); } } } finally { if ( c != null ) { c.close(); } } mNames = names.toArray(new String[0]); mCommands = commands.toArray(new Uri[0]); builder.setItems(this.mNames, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int item) { returnShortcut(mNames[item], mCommands[item]); } }); builder.setOnCancelListener(new OnCancelListener() { public void onCancel(DialogInterface dialog) { AndroidShortcuts sc = AndroidShortcuts.this; sc.setResult(RESULT_CANCELED); sc.finish(); return; } }); AlertDialog alert = builder.create(); alert.show(); } /** * Returns the results to the calling intent. */ private void returnShortcut(String name, Uri command) { Intent shortcutIntent = new Intent(Intent.ACTION_VIEW); shortcutIntent.setData(command); Intent intent = new Intent(); intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent); intent.putExtra(Intent.EXTRA_SHORTCUT_NAME, name); Parcelable iconResource = Intent.ShortcutIconResource.fromContext(this, R.drawable.notes); intent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, iconResource); // Now, return the result to the launcher setResult(RESULT_OK, intent); finish(); return; } }
Java
/* * Copyright (C) 2011 University of Washington * * 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 org.odk.collect.android.activities; import org.odk.collect.android.R; import org.odk.collect.android.application.Collect; import org.odk.collect.android.preferences.PreferencesActivity; import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.pm.PackageManager.NameNotFoundException; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.Bundle; import android.preference.PreferenceManager; import android.view.View; import android.view.Window; import android.widget.ImageView; import android.widget.LinearLayout; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; public class SplashScreenActivity extends Activity { private static final int mSplashTimeout = 2000; // milliseconds private static final boolean EXIT = true; private int mImageMaxWidth; private AlertDialog mAlertDialog; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // must be at the beginning of any activity that can be called from an external intent try { Collect.createODKDirs(); } catch (RuntimeException e) { createErrorDialog(e.getMessage(), EXIT); return; } mImageMaxWidth = getWindowManager().getDefaultDisplay().getWidth(); // this splash screen should be a blank slate requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.splash_screen); // get the shared preferences object SharedPreferences mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(this); Editor editor = mSharedPreferences.edit(); // get the package info object with version number PackageInfo packageInfo = null; try { packageInfo = getPackageManager().getPackageInfo(getPackageName(), PackageManager.GET_META_DATA); } catch (NameNotFoundException e) { e.printStackTrace(); } boolean firstRun = mSharedPreferences.getBoolean(PreferencesActivity.KEY_FIRST_RUN, true); boolean showSplash = mSharedPreferences.getBoolean(PreferencesActivity.KEY_SHOW_SPLASH, false); String splashPath = mSharedPreferences.getString(PreferencesActivity.KEY_SPLASH_PATH, getString(R.string.default_splash_path)); // if you've increased version code, then update the version number and set firstRun to true if (mSharedPreferences.getLong(PreferencesActivity.KEY_LAST_VERSION, 0) < packageInfo.versionCode) { editor.putLong(PreferencesActivity.KEY_LAST_VERSION, packageInfo.versionCode); editor.commit(); firstRun = true; } // do all the first run things if (firstRun || showSplash) { editor.putBoolean(PreferencesActivity.KEY_FIRST_RUN, false); editor.commit(); startSplashScreen(splashPath); } else { endSplashScreen(); } } private void endSplashScreen() { // launch new activity and close splash screen startActivity(new Intent(SplashScreenActivity.this, MainMenuActivity.class)); finish(); } // decodes image and scales it to reduce memory consumption private Bitmap decodeFile(File f) { Bitmap b = null; try { // Decode image size BitmapFactory.Options o = new BitmapFactory.Options(); o.inJustDecodeBounds = true; FileInputStream fis = new FileInputStream(f); BitmapFactory.decodeStream(fis, null, o); try { fis.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } int scale = 1; if (o.outHeight > mImageMaxWidth || o.outWidth > mImageMaxWidth) { scale = (int) Math.pow( 2, (int) Math.round(Math.log(mImageMaxWidth / (double) Math.max(o.outHeight, o.outWidth)) / Math.log(0.5))); } // Decode with inSampleSize BitmapFactory.Options o2 = new BitmapFactory.Options(); o2.inSampleSize = scale; fis = new FileInputStream(f); b = BitmapFactory.decodeStream(fis, null, o2); try { fis.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } catch (FileNotFoundException e) { } return b; } private void startSplashScreen(String path) { // add items to the splash screen here. makes things less distracting. ImageView iv = (ImageView) findViewById(R.id.splash); LinearLayout ll = (LinearLayout) findViewById(R.id.splash_default); File f = new File(path); if (f.exists()) { iv.setImageBitmap(decodeFile(f)); ll.setVisibility(View.GONE); iv.setVisibility(View.VISIBLE); } // create a thread that counts up to the timeout Thread t = new Thread() { int count = 0; @Override public void run() { try { super.run(); while (count < mSplashTimeout) { sleep(100); count += 100; } } catch (Exception e) { e.printStackTrace(); } finally { endSplashScreen(); } } }; t.start(); } private void createErrorDialog(String errorMsg, final boolean shouldExit) { Collect.getInstance().getActivityLogger().logAction(this, "createErrorDialog", "show"); mAlertDialog = new AlertDialog.Builder(this).create(); mAlertDialog.setIcon(android.R.drawable.ic_dialog_info); mAlertDialog.setMessage(errorMsg); DialogInterface.OnClickListener errorListener = new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int i) { switch (i) { case DialogInterface.BUTTON_POSITIVE: Collect.getInstance().getActivityLogger().logAction(this, "createErrorDialog", "OK"); if (shouldExit) { finish(); } break; } } }; mAlertDialog.setCancelable(false); mAlertDialog.setButton(getString(R.string.ok), errorListener); mAlertDialog.show(); } @Override protected void onStart() { super.onStart(); Collect.getInstance().getActivityLogger().logOnStart(this); } @Override protected void onStop() { Collect.getInstance().getActivityLogger().logOnStop(this); super.onStop(); } }
Java
/* * Copyright (C) 2014 Nafundi * * 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. */ /** * @author Carl Hartung (chartung@nafundi.com) */ package org.odk.collect.android.activities; import java.io.BufferedReader; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Stack; import org.odk.collect.android.R; import org.odk.collect.android.adapters.FileArrayAdapter; import org.odk.collect.android.application.Collect; import org.odk.collect.android.listeners.GoogleDriveFormDownloadListener; import org.odk.collect.android.listeners.TaskListener; import org.odk.collect.android.logic.DriveListItem; import org.odk.collect.android.preferences.PreferencesActivity; import android.app.ActionBar.LayoutParams; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.app.ListActivity; import android.app.ProgressDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.IntentSender; import android.content.SharedPreferences; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.AsyncTask; import android.os.Bundle; import android.preference.PreferenceManager; import android.view.Gravity; import android.view.KeyEvent; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.view.Window; import android.view.inputmethod.EditorInfo; import android.view.inputmethod.InputMethodManager; import android.widget.Button; import android.widget.CheckBox; import android.widget.EditText; import android.widget.ImageButton; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.GooglePlayServicesClient.OnConnectionFailedListener; import com.google.android.gms.common.GooglePlayServicesUtil; import com.google.api.client.extensions.android.http.AndroidHttp; import com.google.api.client.googleapis.extensions.android.gms.auth.GoogleAccountCredential; import com.google.api.client.googleapis.extensions.android.gms.auth.UserRecoverableAuthIOException; import com.google.api.client.http.GenericUrl; import com.google.api.client.http.HttpResponse; import com.google.api.client.json.gson.GsonFactory; import com.google.api.services.drive.Drive.Files; import com.google.api.services.drive.model.FileList; import com.google.api.services.drive.model.ParentList; public class GoogleDriveActivity extends ListActivity implements OnConnectionFailedListener, TaskListener, GoogleDriveFormDownloadListener { private final static int PROGRESS_DIALOG = 1; private final static int GOOGLE_USER_DIALOG = 3; private ProgressDialog mProgressDialog; private AlertDialog mAlertDialog; private Button mRootButton; private Button mBackButton; private Button mDownloadButton; private ImageButton mSearchButton; private EditText mSearchText; private Stack<String> mCurrentPath = new Stack<String>(); private String mAlertMsg; private boolean mAlertShowing; private static final int RESOLVE_CONNECTION_REQUEST_CODE = 5555; private static final int COMPLETE_AUTHORIZATION_REQUEST_CODE = 4322; private String rootId = null; private boolean MyDrive; private FileArrayAdapter adapter; private RetrieveDriveFileContentsAsyncTask mRetrieveDriveFileContentsAsyncTask; private GetFileTask mGetFileTask; private String mGoogleUsername = null; private String mParentId; private ArrayList<DriveListItem> toDownload; private static final String MY_DRIVE_KEY = "mydrive"; private static final String PATH_KEY = "path"; private static final String DRIVE_ITEMS_KEY = "drive_list"; private static final String PARENT_KEY = "parent"; private static final String ALERT_MSG_KEY = "alertmsg"; private static final String ALERT_SHOWING_KEY = "alertshowing"; private static final String ROOT_KEY = "root"; private static final String FILE_LIST_KEY = "fileList"; private static final String PARENT_ID_KEY = "parentId"; private static final String CURRENT_ID_KEY = "currentDir"; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setTitle(getString(R.string.app_name) + " > " + getString(R.string.google_drive)); requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS); setProgressBarVisibility(true); setContentView(R.layout.drive_layout); mParentId = null; mAlertShowing = false; toDownload = new ArrayList<DriveListItem>(); // ensure we have a google account selected SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); mGoogleUsername = prefs.getString(PreferencesActivity.KEY_SELECTED_GOOGLE_ACCOUNT, null); if (mGoogleUsername == null || mGoogleUsername.equals("")) { showDialog(GOOGLE_USER_DIALOG); return; } if (savedInstanceState != null && savedInstanceState.containsKey(MY_DRIVE_KEY)) { // recover state on rotate MyDrive = savedInstanceState.getBoolean(MY_DRIVE_KEY); String[] patharray = savedInstanceState.getStringArray(PATH_KEY); mCurrentPath = buildPath(patharray); TextView empty = (TextView)findViewById(android.R.id.empty); getListView().setEmptyView(empty); mParentId = savedInstanceState.getString(PARENT_KEY); mAlertMsg = savedInstanceState.getString(ALERT_MSG_KEY); mAlertShowing = savedInstanceState.getBoolean(ALERT_SHOWING_KEY); ArrayList<DriveListItem> dl = savedInstanceState .getParcelableArrayList(DRIVE_ITEMS_KEY); adapter = new FileArrayAdapter(GoogleDriveActivity.this, R.layout.two_item_image, dl); setListAdapter(adapter); } else { // new TextView emptyView = new TextView(this); emptyView.setText(getString(R.string.gme_search_browse)); emptyView.setGravity(Gravity.CENTER); emptyView.setTextSize(21); getListView().getEmptyView().setVisibility(View.INVISIBLE); LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT); ((ViewGroup)getListView().getParent()).addView(emptyView, lp); getListView().setEmptyView(emptyView); MyDrive = false; if (testNetwork()) { } else { createAlertDialog(getString(R.string.no_connection)); } } // restore any task state if (getLastNonConfigurationInstance() instanceof RetrieveDriveFileContentsAsyncTask) { mRetrieveDriveFileContentsAsyncTask = (RetrieveDriveFileContentsAsyncTask)getLastNonConfigurationInstance(); setProgressBarIndeterminateVisibility(true); } else { mGetFileTask = (GetFileTask)getLastNonConfigurationInstance(); if (mGetFileTask != null) { mGetFileTask.setGoogleDriveFormDownloadListener(this); } } if (mGetFileTask != null && mGetFileTask.getStatus() == AsyncTask.Status.FINISHED) { try { dismissDialog(PROGRESS_DIALOG); } catch (Exception e) { e.printStackTrace(); // don't care... } } if (mAlertShowing) { try { dismissDialog(PROGRESS_DIALOG); } catch (Exception e) { e.printStackTrace(); // don't care... } createAlertDialog(mAlertMsg); } mRootButton = (Button)findViewById(R.id.root_button); if (MyDrive) { mRootButton.setText(getString(R.string.go_shared)); } else { mRootButton.setText(getString(R.string.go_drive)); } mRootButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (testNetwork()) { toDownload.clear(); mRootButton.setEnabled(false); mSearchButton.setEnabled(false); mBackButton.setEnabled(false); mDownloadButton.setEnabled(false); listFiles(ROOT_KEY); MyDrive = !MyDrive; } else { createAlertDialog(getString(R.string.no_connection)); } mCurrentPath.clear(); mCurrentPath.add((String)mRootButton.getText()); } }); mBackButton = (Button)findViewById(R.id.back_button); mBackButton.setEnabled(mParentId != null); mBackButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mBackButton.setEnabled(false); mRootButton.setEnabled(false); mDownloadButton.setEnabled(false); toDownload.clear(); getListView().getEmptyView().setVisibility(View.INVISIBLE); TextView empty = (TextView)findViewById(android.R.id.empty); empty.setVisibility(View.VISIBLE); getListView().setEmptyView(empty); if (testNetwork()) { if (mParentId == null) { mParentId = ROOT_KEY; } listFiles(mParentId); mCurrentPath.pop(); // } } else { createAlertDialog(getString(R.string.no_connection)); } } }); mDownloadButton = (Button)findViewById(R.id.download_button); mDownloadButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { getFiles(); } }); mSearchText = (EditText)findViewById(R.id.search_text); mSearchText.setOnEditorActionListener(new TextView.OnEditorActionListener() { @Override public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { if (actionId == EditorInfo.IME_ACTION_SEARCH) { executeSearch(); return true; } return false; } }); mSearchButton = (ImageButton)findViewById(R.id.search_button); mSearchButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { executeSearch(); } }); } void executeSearch() { String searchString = mSearchText.getText().toString(); if (searchString.length() > 0) { toDownload.clear(); mSearchButton.setEnabled(false); mBackButton.setEnabled(false); mDownloadButton.setEnabled(false); mRootButton.setEnabled(false); InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(mSearchText.getWindowToken(), 0); mCurrentPath.clear(); listFiles(ROOT_KEY, mSearchText.getText().toString()); } else { Toast.makeText(this, R.string.no_blank_search, Toast.LENGTH_SHORT).show(); } } @Override protected void onSaveInstanceState(Bundle outState) { outState.putBoolean(MY_DRIVE_KEY, MyDrive); ArrayList<DriveListItem> dl = new ArrayList<DriveListItem>(); for (int i = 0; i < getListView().getCount(); i++) { dl.add((DriveListItem)getListView().getItemAtPosition(i)); } outState.putParcelableArrayList(DRIVE_ITEMS_KEY, dl); outState.putStringArray(PATH_KEY, mCurrentPath.toArray(new String[mCurrentPath.size()])); outState.putString(PARENT_KEY, mParentId); outState.putBoolean(ALERT_SHOWING_KEY, mAlertShowing); outState.putString(ALERT_MSG_KEY, mAlertMsg); super.onSaveInstanceState(outState); } @Override protected void onListItemClick(ListView l, View v, int position, long id) { super.onListItemClick(l, v, position, id); getListView().getEmptyView().setVisibility(View.INVISIBLE); TextView empty = (TextView)findViewById(android.R.id.empty); empty.setVisibility(View.VISIBLE); getListView().setEmptyView(empty); DriveListItem o = adapter.getItem(position); if (o != null && o.getType() == DriveListItem.DIR) { if (testNetwork()) { toDownload.clear(); mSearchText.setText(null); listFiles(o.getDriveId()); mCurrentPath.push(o.getName()); } else { createAlertDialog(getString(R.string.no_connection)); } } else { // file clicked, download the file, mark checkbox. CheckBox cb = (CheckBox)v.findViewById(R.id.checkbox); cb.setChecked(!cb.isChecked()); if (toDownload.contains(o) && !cb.isChecked()) { toDownload.remove(o); } else { toDownload.add(o); } mDownloadButton.setEnabled(toDownload.size() > 0); } } private void getFiles() { StringBuilder messageBuilder = new StringBuilder(); for (int i = 0; i < toDownload.size(); i++) { DriveListItem o = toDownload.get(i); messageBuilder.append(o.getName()); if (i != toDownload.size() - 1) { messageBuilder.append(", "); } } mAlertMsg = getString(R.string.drive_get_file, messageBuilder.toString()); showDialog(PROGRESS_DIALOG); mGetFileTask = new GetFileTask(); mGetFileTask.setGoogleDriveFormDownloadListener(this); mGetFileTask.execute(toDownload); } @Override public void onConnectionFailed(ConnectionResult connectionResult) { if (connectionResult.hasResolution()) { try { connectionResult.startResolutionForResult(this, RESOLVE_CONNECTION_REQUEST_CODE); } catch (IntentSender.SendIntentException e) { // Unable to resolve, message user appropriately } } else { GooglePlayServicesUtil.getErrorDialog(connectionResult.getErrorCode(), this, 0).show(); } } @Override protected Dialog onCreateDialog(int id) { switch (id) { case PROGRESS_DIALOG: Collect.getInstance().getActivityLogger() .logAction(this, "onCreateDialog.PROGRESS_DIALOG", "show"); mProgressDialog = new ProgressDialog(this); DialogInterface.OnClickListener loadingButtonListener = new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Collect.getInstance().getActivityLogger() .logAction(this, "onCreateDialog.PROGRESS_DIALOG", "cancel"); dialog.dismiss(); mGetFileTask.cancel(true); mGetFileTask.setGoogleDriveFormDownloadListener(null); } }; mProgressDialog.setTitle(getString(R.string.downloading_data)); mProgressDialog.setMessage(mAlertMsg); mProgressDialog.setIndeterminate(true); mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER); mProgressDialog.setCancelable(false); mProgressDialog.setButton(getString(R.string.cancel), loadingButtonListener); return mProgressDialog; case GOOGLE_USER_DIALOG: AlertDialog.Builder gudBuilder = new AlertDialog.Builder(this); gudBuilder.setTitle(getString(R.string.no_google_account)); gudBuilder.setMessage(getString(R.string.gme_set_account)); gudBuilder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { finish(); } }); gudBuilder.setCancelable(false); return gudBuilder.create(); } return null; } private void createAlertDialog(String message) { Collect.getInstance().getActivityLogger().logAction(this, "createAlertDialog", "show"); mAlertDialog = new AlertDialog.Builder(this).create(); mAlertDialog.setTitle(getString(R.string.download_forms_result)); mAlertDialog.setMessage(message); DialogInterface.OnClickListener quitListener = new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int i) { switch (i) { case DialogInterface.BUTTON1: // ok Collect.getInstance().getActivityLogger() .logAction(this, "createAlertDialog", "OK"); mAlertShowing = false; finish(); break; } } }; mAlertDialog.setCancelable(false); mAlertDialog.setButton(getString(R.string.ok), quitListener); mAlertDialog.setIcon(android.R.drawable.ic_dialog_info); mAlertShowing = true; mAlertMsg = message; mAlertDialog.show(); } @Override protected void onActivityResult(final int requestCode, final int resultCode, final Intent data) { switch (requestCode) { case COMPLETE_AUTHORIZATION_REQUEST_CODE: if (resultCode == Activity.RESULT_OK) { if (testNetwork()) { listFiles(ROOT_KEY); } else { createAlertDialog(getString(R.string.no_connection)); } } else { // User denied access, show him the account chooser again } break; } if (resultCode == RESULT_CANCELED) { finish(); } } @Override public Object onRetainNonConfigurationInstance() { if (mRetrieveDriveFileContentsAsyncTask != null && mRetrieveDriveFileContentsAsyncTask.getStatus() == AsyncTask.Status.RUNNING) { return mRetrieveDriveFileContentsAsyncTask; } return mGetFileTask; } // List<com.google.api.services.drive.model.File> private class RetrieveDriveFileContentsAsyncTask extends AsyncTask<String, HashMap<String, Object>, HashMap<String, Object>> { private TaskListener listener; public void setTaskListener(TaskListener tl) { listener = tl; } @Override protected HashMap<String, Object> doInBackground(String... params) { HashMap<String, Object> results = new HashMap<String, Object>(); String currentDir = params[0]; String parentId = ROOT_KEY; String query = null; if (params.length == 2) { // TODO: *.xml or .xml or xml // then search mimetype query = "title contains '" + params[1] + "' and trashed=false"; } Collection<String> collection = new ArrayList<String>(); collection.add(com.google.api.services.drive.DriveScopes.DRIVE); GoogleAccountCredential credential = GoogleAccountCredential.usingOAuth2( GoogleDriveActivity.this.getApplicationContext(), collection); com.google.api.services.drive.Drive service = new com.google.api.services.drive.Drive.Builder( AndroidHttp.newCompatibleTransport(), new GsonFactory(), credential).build(); credential.setSelectedAccountName(mGoogleUsername); if (rootId == null) { com.google.api.services.drive.model.File rootfile = null; try { rootfile = service.files().get(ROOT_KEY).execute(); } catch (UserRecoverableAuthIOException e) { startActivityForResult(e.getIntent(), COMPLETE_AUTHORIZATION_REQUEST_CODE); return null; } catch (IOException e) { e.printStackTrace(); } rootId = rootfile.getId(); } String requestString = "'" + currentDir + "' in parents and trashed=false"; Files.List request = null; try { ParentList parents = service.parents().list(currentDir).execute(); if (parents.getItems().size() > 0) { parentId = parents.getItems().get(0).getId(); if (parents.getItems().get(0).getIsRoot()) { rootId = parentId; } } else { parentId = null; } // Sharedwithme, and root: if (!MyDrive && currentDir.equals(ROOT_KEY)) { requestString = "trashed=false and sharedWithMe=true"; } request = service.files().list().setQ(requestString); } catch (IOException e1) { e1.printStackTrace(); } // If there's a query parameter, we're searching for all the files. if (query != null) { try { request = service.files().list().setQ(query); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } results.put(PARENT_ID_KEY, parentId); results.put(CURRENT_ID_KEY, currentDir); do { try { FileList fa = request.execute(); List<com.google.api.services.drive.model.File> driveFileListPage = new ArrayList<com.google.api.services.drive.model.File>(); driveFileListPage.addAll(fa.getItems()); request.setPageToken(fa.getNextPageToken()); HashMap<String, Object> nextPage = new HashMap<String, Object>(); nextPage.put(PARENT_ID_KEY, parentId); nextPage.put(CURRENT_ID_KEY, currentDir); nextPage.put(FILE_LIST_KEY, driveFileListPage); publishProgress(nextPage); } catch (IOException e) { e.printStackTrace(); } } while (request.getPageToken() != null && request.getPageToken().length() > 0); return results; } @Override protected void onPostExecute(HashMap<String, Object> results) { super.onPostExecute(results); if (results == null) { // was an auth request return; } if (listener != null) { listener.taskComplete(results); } } @Override protected void onProgressUpdate(HashMap<String, Object>... values) { super.onProgressUpdate(values); List<com.google.api.services.drive.model.File> fileList = (List<com.google.api.services.drive.model.File>)values[0] .get(FILE_LIST_KEY); String parentId = (String)values[0].get(PARENT_ID_KEY); String currentDir = (String)values[0].get(CURRENT_ID_KEY); List<DriveListItem> dirs = new ArrayList<DriveListItem>(); List<DriveListItem> forms = new ArrayList<DriveListItem>(); for (com.google.api.services.drive.model.File f : fileList) { if (f.getMimeType().equals("application/xml")) { forms.add(new DriveListItem(f.getTitle(), "", f.getModifiedDate(), "", "", DriveListItem.FILE, f.getId(), currentDir)); } else if (f.getMimeType().equals("application/xhtml")) { forms.add(new DriveListItem(f.getTitle(), "", f.getModifiedDate(), "", "", DriveListItem.FILE, f.getId(), currentDir)); } else if (f.getMimeType().equals("application/vnd.google-apps.folder")) { dirs.add(new DriveListItem(f.getTitle(), "", f.getModifiedDate(), "", "", DriveListItem.DIR, f.getId(), parentId)); } else { // skip the rest of the files } } Collections.sort(dirs); Collections.sort(forms); dirs.addAll(forms); if (adapter == null) { adapter = new FileArrayAdapter(GoogleDriveActivity.this, R.layout.two_item_image, dirs); GoogleDriveActivity.this.setListAdapter(adapter); } else { adapter.addAll(dirs); } adapter.sort(new Comparator<DriveListItem>() { @Override public int compare(DriveListItem lhs, DriveListItem rhs) { if (lhs.getType() != rhs.getType()) { if (lhs.getType() == DriveListItem.DIR) { return -1; } else { return 1; } } else { return lhs.getName().compareTo(rhs.getName()); } } }); adapter.notifyDataSetChanged(); } } private Stack<String> buildPath(String[] path) { Stack<String> pathStack = new Stack<String>(); for (int i = 0; i < path.length; i++) { pathStack.push(path[i]); } return pathStack; } private class GetFileTask extends AsyncTask<ArrayList<DriveListItem>, Boolean, HashMap<String, Object>> { private GoogleDriveFormDownloadListener listener; public void setGoogleDriveFormDownloadListener(GoogleDriveFormDownloadListener gl) { listener = gl; } @Override protected HashMap<String, Object> doInBackground(ArrayList<DriveListItem>... params) { HashMap<String, Object> results = new HashMap<String, Object>(); ArrayList<DriveListItem> fileItems = params[0]; Collection<String> collection = new ArrayList<String>(); collection.add(com.google.api.services.drive.DriveScopes.DRIVE); GoogleAccountCredential credential = GoogleAccountCredential.usingOAuth2( GoogleDriveActivity.this.getApplicationContext(), collection); com.google.api.services.drive.Drive service = new com.google.api.services.drive.Drive.Builder( AndroidHttp.newCompatibleTransport(), new GsonFactory(), credential).build(); credential.setSelectedAccountName(mGoogleUsername); for (int k = 0; k < fileItems.size(); k++) { DriveListItem fileItem = fileItems.get(k); String mediaDir = fileItem.getName().substring(0, fileItem.getName().length() - 4) + "-media"; String requestString = "'" + fileItem.getParentId() + "' in parents and trashed=false and title='" + mediaDir + "'"; Files.List request = null; List<com.google.api.services.drive.model.File> driveFileList = new ArrayList<com.google.api.services.drive.model.File>(); try { request = service.files().list().setQ(requestString); } catch (IOException e1) { e1.printStackTrace(); results.put(fileItem.getName(), e1.getMessage()); return results; } do { try { FileList fa = request.execute(); driveFileList.addAll(fa.getItems()); request.setPageToken(fa.getNextPageToken()); } catch (Exception e2) { e2.printStackTrace(); results.put(fileItem.getName(), e2.getMessage()); return results; } } while (request.getPageToken() != null && request.getPageToken().length() > 0); if (driveFileList.size() > 1) { results.put(fileItem.getName(), "More than one media folder detected, please remove one and try again"); return results; } else if (driveFileList.size() == 1) { requestString = "'" + driveFileList.get(0).getId() + "' in parents and trashed=false"; List<com.google.api.services.drive.model.File> mediaFileList = new ArrayList<com.google.api.services.drive.model.File>(); try { request = service.files().list().setQ(requestString); do { try { FileList fa = request.execute(); mediaFileList.addAll(fa.getItems()); request.setPageToken(fa.getNextPageToken()); } catch (Exception e2) { e2.printStackTrace(); results.put(fileItem.getName(), e2.getMessage()); return results; } } while (request.getPageToken() != null && request.getPageToken().length() > 0); } catch (Exception e) { e.printStackTrace(); results.put(fileItem.getName(), e.getMessage()); return results; } } else { // zero.. just downloda the .xml file } try { com.google.api.services.drive.model.File df = service.files() .get(fileItem.getDriveId()).execute(); InputStream is = downloadFile(service, df); BufferedReader reader = new BufferedReader(new InputStreamReader(is)); FileWriter fw = new FileWriter(Collect.FORMS_PATH + File.separator + fileItem.getName()); int c; while ((c = reader.read()) != -1) { fw.write(c); } fw.flush(); fw.close(); reader.close(); } catch (Exception e) { e.printStackTrace(); results.put(fileItem.getName(), e.getMessage()); return results; } results.put(fileItem.getName(), Collect.getInstance().getString(R.string.success)); } return results; } private InputStream downloadFile(com.google.api.services.drive.Drive service, com.google.api.services.drive.model.File file) { if (file.getDownloadUrl() != null && file.getDownloadUrl().length() > 0) { try { HttpResponse resp = service.getRequestFactory() .buildGetRequest(new GenericUrl(file.getDownloadUrl())).execute(); return resp.getContent(); } catch (IOException e) { // An error occurred. e.printStackTrace(); return null; } } else { // The file doesn't have any content stored on Drive. return null; } } @Override protected void onPostExecute(HashMap<String, Object> results) { listener.formDownloadComplete(results); } } @Override public void taskComplete(HashMap<String, Object> results) { mRootButton.setEnabled(true); mDownloadButton.setEnabled(toDownload.size() > 0); mSearchButton.setEnabled(true); setProgressBarIndeterminateVisibility(false); if (results == null) { // if results was null, then got a google exception // requiring the user to authorize return; } String parentId = (String)results.get(PARENT_ID_KEY); String currentDir = (String)results.get(CURRENT_ID_KEY); if (MyDrive) { mRootButton.setText(getString(R.string.go_shared)); } else { mRootButton.setText(getString(R.string.go_drive)); } if (currentDir.equals(rootId) || (currentDir.equals("root"))) { mBackButton.setEnabled(false); } else { mBackButton.setEnabled(true); } mParentId = parentId; if (mCurrentPath.empty()) { if (MyDrive) { mCurrentPath.add(getString(R.string.go_drive)); } else { mCurrentPath.add(getString(R.string.go_shared)); } } } @Override protected void onPause() { if (mRetrieveDriveFileContentsAsyncTask != null) { mRetrieveDriveFileContentsAsyncTask.setTaskListener(null); } if (mGetFileTask != null) { mGetFileTask.setGoogleDriveFormDownloadListener(null); } super.onPause(); } @Override protected void onResume() { super.onResume(); if (mRetrieveDriveFileContentsAsyncTask != null) { mRetrieveDriveFileContentsAsyncTask.setTaskListener(this); } if (mGetFileTask != null) { mGetFileTask.setGoogleDriveFormDownloadListener(this); } } @Override public void formDownloadComplete(HashMap<String, Object> results) { try { dismissDialog(PROGRESS_DIALOG); } catch (Exception e) { // tried to close a dialog not open. don't care. } StringBuilder sb = new StringBuilder(); Iterator<String> it = results.keySet().iterator(); while (it.hasNext()) { String id = it.next(); sb.append(id + " :: " + results.get(id) + "\n"); } if (sb.length() > 1) { sb.setLength(sb.length() - 1); } createAlertDialog(sb.toString()); } @Override protected void onStart() { super.onStart(); Collect.getInstance().getActivityLogger().logOnStart(this); } @Override protected void onStop() { Collect.getInstance().getActivityLogger().logOnStop(this); super.onStop(); } private boolean testNetwork() { ConnectivityManager manager = (ConnectivityManager)this .getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo currentNetworkInfo = manager.getActiveNetworkInfo(); if (currentNetworkInfo == null) { return false; } return (currentNetworkInfo.getState() == NetworkInfo.State.CONNECTED); } public void listFiles(String dir, String query) { setProgressBarIndeterminateVisibility(true); adapter = null; mRetrieveDriveFileContentsAsyncTask = new RetrieveDriveFileContentsAsyncTask(); mRetrieveDriveFileContentsAsyncTask.setTaskListener(GoogleDriveActivity.this); if (query != null) { mRetrieveDriveFileContentsAsyncTask.execute(dir, query); } else { mRetrieveDriveFileContentsAsyncTask.execute(dir); } } public void listFiles(String dir) { listFiles(dir, null); } }
Java
/* * Copyright (C) 2011 University of Washington * * 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 org.odk.collect.android.activities; import java.text.DecimalFormat; import java.util.List; import org.odk.collect.android.R; import org.odk.collect.android.application.Collect; import org.odk.collect.android.utilities.InfoLogger; import org.odk.collect.android.widgets.GeoPointWidget; import android.content.Context; import android.content.Intent; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Point; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.view.Window; import android.widget.Button; import android.widget.FrameLayout; import android.widget.RelativeLayout.LayoutParams; import android.widget.TextView; import android.widget.Toast; import com.google.android.maps.GeoPoint; import com.google.android.maps.MapActivity; import com.google.android.maps.MapController; import com.google.android.maps.MapView; import com.google.android.maps.MyLocationOverlay; import com.google.android.maps.Overlay; public class GeoPointMapActivitySdk7 extends MapActivity implements LocationListener { private static final String LOCATION_COUNT = "locationCount"; private MapView mMapView; private TextView mLocationStatus; private MapController mMapController; private LocationManager mLocationManager; private Overlay mLocationOverlay; private Overlay mGeoPointOverlay; private GeoPoint mGeoPoint; private Location mLocation; private Button mAcceptLocation; private Button mCancelLocation; private boolean mCaptureLocation = true; private Button mShowLocation; private boolean mGPSOn = false; private boolean mNetworkOn = false; private double mLocationAccuracy; private int mLocationCount = 0; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if ( savedInstanceState != null ) { mLocationCount = savedInstanceState.getInt(LOCATION_COUNT); } requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.geopoint_layout_sdk7); Intent intent = getIntent(); mLocationAccuracy = GeoPointWidget.DEFAULT_LOCATION_ACCURACY; if (intent != null && intent.getExtras() != null) { if ( intent.hasExtra(GeoPointWidget.LOCATION) ) { double[] location = intent.getDoubleArrayExtra(GeoPointWidget.LOCATION); mGeoPoint = new GeoPoint((int) (location[0] * 1E6), (int) (location[1] * 1E6)); } if ( intent.hasExtra(GeoPointWidget.ACCURACY_THRESHOLD) ) { mLocationAccuracy = intent.getDoubleExtra(GeoPointWidget.ACCURACY_THRESHOLD, GeoPointWidget.DEFAULT_LOCATION_ACCURACY); } mCaptureLocation = !intent.getBooleanExtra(GeoPointWidget.READ_ONLY, false); } /** * Add the MapView dynamically to the placeholding frame so as to not * incur the wrath of Android Lint... */ FrameLayout frame = (FrameLayout) findViewById(R.id.mapview_placeholder); String apiKey = "017Xo9E6R7WmcCITvo-lU2V0ERblKPqCcguwxSQ"; // String apiKey = "0wsgFhRvVBLVpgaFzmwaYuqfU898z_2YtlKSlkg"; mMapView = new MapView(this, apiKey); mMapView.setClickable(true); mMapView.setId(R.id.mapview); LayoutParams p = new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT); frame.addView(mMapView, p); mCancelLocation = (Button) findViewById(R.id.cancel_location); mCancelLocation.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Collect.getInstance().getActivityLogger().logInstanceAction(this, "cancelLocation", "cancel"); finish(); } }); mMapController = mMapView.getController(); mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); mMapView.setBuiltInZoomControls(true); mMapView.setSatellite(false); mMapController.setZoom(16); // make sure we have a good location provider before continuing List<String> providers = mLocationManager.getProviders(true); for (String provider : providers) { if (provider.equalsIgnoreCase(LocationManager.GPS_PROVIDER)) { mGPSOn = true; } if (provider.equalsIgnoreCase(LocationManager.NETWORK_PROVIDER)) { mNetworkOn = true; } } if (!mGPSOn && !mNetworkOn) { Toast.makeText(getBaseContext(), getString(R.string.provider_disabled_error), Toast.LENGTH_SHORT).show(); finish(); } if ( mGPSOn ) { Location loc = mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); if ( loc != null ) { InfoLogger.geolog("GeoPointMapActivity: " + System.currentTimeMillis() + " lastKnownLocation(GPS) lat: " + loc.getLatitude() + " long: " + loc.getLongitude() + " acc: " + loc.getAccuracy() ); } else { InfoLogger.geolog("GeoPointMapActivity: " + System.currentTimeMillis() + " lastKnownLocation(GPS) null location"); } } if ( mNetworkOn ) { Location loc = mLocationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER); if ( loc != null ) { InfoLogger.geolog("GeoPointMapActivity: " + System.currentTimeMillis() + " lastKnownLocation(Network) lat: " + loc.getLatitude() + " long: " + loc.getLongitude() + " acc: " + loc.getAccuracy() ); } else { InfoLogger.geolog("GeoPointMapActivity: " + System.currentTimeMillis() + " lastKnownLocation(Network) null location"); } } mLocationOverlay = new MyLocationOverlay(this, mMapView); mMapView.getOverlays().add(mLocationOverlay); if (mCaptureLocation) { mLocationStatus = (TextView) findViewById(R.id.location_status); mAcceptLocation = (Button) findViewById(R.id.accept_location); mAcceptLocation.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Collect.getInstance().getActivityLogger().logInstanceAction(this, "acceptLocation", "OK"); returnLocation(); } }); } else { mGeoPointOverlay = new Marker(mGeoPoint); mMapView.getOverlays().add(mGeoPointOverlay); ((Button) findViewById(R.id.accept_location)).setVisibility(View.GONE); ((TextView) findViewById(R.id.location_status)).setVisibility(View.GONE); mShowLocation = ((Button) findViewById(R.id.show_location)); mShowLocation.setVisibility(View.VISIBLE); mShowLocation.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Collect.getInstance().getActivityLogger().logInstanceAction(this, "showLocation", "onClick"); mMapController.animateTo(mGeoPoint); } }); } if ( mGeoPoint != null ) { mMapController.animateTo(mGeoPoint); } } @Override protected void onStart() { super.onStart(); Collect.getInstance().getActivityLogger().logOnStart(this); } @Override protected void onStop() { Collect.getInstance().getActivityLogger().logOnStop(this); super.onStop(); } private void returnLocation() { if (mLocation != null) { Intent i = new Intent(); i.putExtra( FormEntryActivity.LOCATION_RESULT, mLocation.getLatitude() + " " + mLocation.getLongitude() + " " + mLocation.getAltitude() + " " + mLocation.getAccuracy()); setResult(RESULT_OK, i); } finish(); } private String truncateFloat(float f) { return new DecimalFormat("#.##").format(f); } @Override protected void onPause() { super.onPause(); mLocationManager.removeUpdates(this); ((MyLocationOverlay) mLocationOverlay).disableMyLocation(); } @Override protected void onResume() { super.onResume(); if (mCaptureLocation) { ((MyLocationOverlay) mLocationOverlay).enableMyLocation(); if (mGPSOn) { mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this); } if (mNetworkOn) { mLocationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this); } } } @Override protected boolean isRouteDisplayed() { return false; } @Override public void onLocationChanged(Location location) { if (mCaptureLocation) { mLocation = location; if (mLocation != null) { // Bug report: cached GeoPoint is being returned as the first value. // Wait for the 2nd value to be returned, which is hopefully not cached? ++mLocationCount; InfoLogger.geolog("GeoPointMapActivity: " + System.currentTimeMillis() + " onLocationChanged(" + mLocationCount + ") lat: " + mLocation.getLatitude() + " long: " + mLocation.getLongitude() + " acc: " + mLocation.getAccuracy() ); if (mLocationCount > 1) { mLocationStatus.setText(getString(R.string.location_provider_accuracy, mLocation.getProvider(), truncateFloat(mLocation.getAccuracy()))); mGeoPoint = new GeoPoint((int) (mLocation.getLatitude() * 1E6), (int) (mLocation.getLongitude() * 1E6)); mMapController.animateTo(mGeoPoint); if (mLocation.getAccuracy() <= mLocationAccuracy) { returnLocation(); } } } else { InfoLogger.geolog("GeoPointMapActivity: " + System.currentTimeMillis() + " onLocationChanged(" + mLocationCount + ") null location"); } } } @Override public void onProviderDisabled(String provider) { } @Override public void onProviderEnabled(String provider) { } @Override public void onStatusChanged(String provider, int status, Bundle extras) { } class Marker extends Overlay { GeoPoint gp = null; public Marker(GeoPoint gp) { super(); this.gp = gp; } @Override public void draw(Canvas canvas, MapView mapView, boolean shadow) { super.draw(canvas, mapView, shadow); Point screenPoint = new Point(); mMapView.getProjection().toPixels(gp, screenPoint); canvas.drawBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.ic_maps_indicator_current_position), screenPoint.x, screenPoint.y - 8, null); // -8 as image is 16px high } } }
Java
/* * Copyright (C) 2013 Nafundi * * 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 org.odk.collect.android.activities; import org.odk.collect.android.R; import org.odk.collect.android.application.Collect; import android.app.Activity; import android.app.ProgressDialog; import android.content.DialogInterface; import android.content.Intent; import android.hardware.Sensor; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.hardware.SensorManager; import android.os.Bundle; public class BearingActivity extends Activity implements SensorEventListener { private ProgressDialog mBearingDialog; private SensorManager mSensorManager; private Sensor accelerometer; private Sensor magnetometer; private static float[] mAccelerometer = null; private static float[] mGeomagnetic = null; private String mBearing = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setTitle(getString(R.string.app_name) + " > " + getString(R.string.get_bearing)); mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE); accelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER); magnetometer = mSensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD); setupBearingDialog(); } @Override protected void onPause() { super.onPause(); mSensorManager.unregisterListener(this, accelerometer); mSensorManager.unregisterListener(this, magnetometer); if (mBearingDialog != null && mBearingDialog.isShowing()) mBearingDialog.dismiss(); } @Override protected void onResume() { super.onResume(); mSensorManager.registerListener(this, accelerometer, SensorManager.SENSOR_DELAY_GAME); mSensorManager.registerListener(this, magnetometer, SensorManager.SENSOR_DELAY_GAME); mBearingDialog.show(); } @Override protected void onStart() { super.onStart(); Collect.getInstance().getActivityLogger().logOnStart(this); } @Override protected void onStop() { Collect.getInstance().getActivityLogger().logOnStop(this); super.onStop(); } /** * Sets up the look and actions for the progress dialog while the compass is * searching. */ private void setupBearingDialog() { Collect.getInstance().getActivityLogger() .logInstanceAction(this, "setupBearingDialog", "show"); // dialog displayed while fetching bearing mBearingDialog = new ProgressDialog(this); DialogInterface.OnClickListener geopointButtonListener = new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { switch (which) { case DialogInterface.BUTTON_POSITIVE: Collect.getInstance().getActivityLogger() .logInstanceAction(this, "acceptBearing", "OK"); returnBearing(); break; case DialogInterface.BUTTON_NEGATIVE: Collect.getInstance().getActivityLogger() .logInstanceAction(this, "cancelBearing", "cancel"); mBearing = null; finish(); break; } } }; // back button doesn't cancel mBearingDialog.setCancelable(false); mBearingDialog.setIndeterminate(true); mBearingDialog.setIcon(android.R.drawable.ic_dialog_info); mBearingDialog.setTitle(getString(R.string.getting_bearing)); mBearingDialog.setMessage(getString(R.string.please_wait_long)); mBearingDialog.setButton(DialogInterface.BUTTON_POSITIVE, getString(R.string.accept_bearing), geopointButtonListener); mBearingDialog.setButton(DialogInterface.BUTTON_NEGATIVE, getString(R.string.cancel_location), geopointButtonListener); } private void returnBearing() { if (mBearing != null) { Intent i = new Intent(); i.putExtra( FormEntryActivity.BEARING_RESULT, mBearing); setResult(RESULT_OK, i); } finish(); } @Override public void onAccuracyChanged(Sensor arg0, int arg1) { // TODO Auto-generated method stub } @Override public void onSensorChanged(SensorEvent event) { // onSensorChanged gets called for each sensor so we have to remember // the values if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) { mAccelerometer = event.values; } if (event.sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD) { mGeomagnetic = event.values; } if (mAccelerometer != null && mGeomagnetic != null) { float R[] = new float[9]; float I[] = new float[9]; boolean success = SensorManager.getRotationMatrix(R, I, mAccelerometer, mGeomagnetic); if (success) { float orientation[] = new float[3]; SensorManager.getOrientation(R, orientation); // at this point, orientation contains the azimuth(direction), // pitch and roll values. double azimuth = 180 * orientation[0] / Math.PI; // double pitch = 180 * orientation[1] / Math.PI; // double roll = 180 * orientation[2] / Math.PI; double degrees = normalizeDegree(azimuth); mBearing = String.format("%.3f", degrees); String dir = "N"; if ((degrees > 0 && degrees <= 22.5) || degrees > 337.5) { dir = "N"; } else if (degrees > 22.5 && degrees <= 67.5) { dir = "NE"; } else if (degrees > 67.5 && degrees <= 112.5) { dir = "E"; } else if (degrees > 112.5 && degrees <= 157.5) { dir = "SE"; } else if (degrees > 157.5 && degrees <= 222.5) { dir = "S"; } else if (degrees > 222.5 && degrees <= 247.5) { dir = "SW"; } else if (degrees > 247.5 && degrees <= 292.5) { dir = "W"; } else if (degrees > 292.5 && degrees <= 337.5) { dir = "NW"; } mBearingDialog.setMessage("Dir: " + dir + " Bearing: " + mBearing); } } } private double normalizeDegree(double value) { if (value >= 0.0f && value <= 180.0f) { return value; } else { return 180 + (180 + value); } } }
Java
/* * Copyright (C) 2009 University of Washington * * 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 org.odk.collect.android.activities; import org.odk.collect.android.R; import org.odk.collect.android.application.Collect; import org.odk.collect.android.listeners.DiskSyncListener; import org.odk.collect.android.provider.FormsProviderAPI.FormsColumns; import org.odk.collect.android.tasks.DiskSyncTask; import org.odk.collect.android.utilities.VersionHidingCursorAdapter; import android.app.AlertDialog; import android.app.ListActivity; import android.content.ContentUris; import android.content.DialogInterface; import android.content.Intent; import android.database.Cursor; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.ListView; import android.widget.SimpleCursorAdapter; import android.widget.TextView; /** * Responsible for displaying all the valid forms in the forms directory. Stores the path to * selected form for use by {@link MainMenuActivity}. * * @author Yaw Anokwa (yanokwa@gmail.com) * @author Carl Hartung (carlhartung@gmail.com) */ public class FormChooserList extends ListActivity implements DiskSyncListener { private static final String t = "FormChooserList"; private static final boolean EXIT = true; private static final String syncMsgKey = "syncmsgkey"; private DiskSyncTask mDiskSyncTask; private AlertDialog mAlertDialog; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // must be at the beginning of any activity that can be called from an external intent try { Collect.createODKDirs(); } catch (RuntimeException e) { createErrorDialog(e.getMessage(), EXIT); return; } setContentView(R.layout.chooser_list_layout); setTitle(getString(R.string.app_name) + " > " + getString(R.string.enter_data)); String sortOrder = FormsColumns.DISPLAY_NAME + " ASC, " + FormsColumns.JR_VERSION + " DESC"; Cursor c = managedQuery(FormsColumns.CONTENT_URI, null, null, null, sortOrder); String[] data = new String[] { FormsColumns.DISPLAY_NAME, FormsColumns.DISPLAY_SUBTEXT, FormsColumns.JR_VERSION }; int[] view = new int[] { R.id.text1, R.id.text2, R.id.text3 }; // render total instance view SimpleCursorAdapter instances = new VersionHidingCursorAdapter(FormsColumns.JR_VERSION, this, R.layout.two_item, c, data, view); setListAdapter(instances); if (savedInstanceState != null && savedInstanceState.containsKey(syncMsgKey)) { TextView tv = (TextView) findViewById(R.id.status_text); tv.setText(savedInstanceState.getString(syncMsgKey)); } // DiskSyncTask checks the disk for any forms not already in the content provider // that is, put here by dragging and dropping onto the SDCard mDiskSyncTask = (DiskSyncTask) getLastNonConfigurationInstance(); if (mDiskSyncTask == null) { Log.i(t, "Starting new disk sync task"); mDiskSyncTask = new DiskSyncTask(); mDiskSyncTask.setDiskSyncListener(this); mDiskSyncTask.execute((Void[]) null); } } @Override public Object onRetainNonConfigurationInstance() { // pass the thread on restart return mDiskSyncTask; } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); TextView tv = (TextView) findViewById(R.id.status_text); outState.putString(syncMsgKey, tv.getText().toString()); } /** * Stores the path of selected form and finishes. */ @Override protected void onListItemClick(ListView listView, View view, int position, long id) { // get uri to form long idFormsTable = ((SimpleCursorAdapter) getListAdapter()).getItemId(position); Uri formUri = ContentUris.withAppendedId(FormsColumns.CONTENT_URI, idFormsTable); Collect.getInstance().getActivityLogger().logAction(this, "onListItemClick", formUri.toString()); String action = getIntent().getAction(); if (Intent.ACTION_PICK.equals(action)) { // caller is waiting on a picked form setResult(RESULT_OK, new Intent().setData(formUri)); } else { // caller wants to view/edit a form, so launch formentryactivity startActivity(new Intent(Intent.ACTION_EDIT, formUri)); } finish(); } @Override protected void onResume() { mDiskSyncTask.setDiskSyncListener(this); super.onResume(); if (mDiskSyncTask.getStatus() == AsyncTask.Status.FINISHED) { SyncComplete(mDiskSyncTask.getStatusMessage()); } } @Override protected void onPause() { mDiskSyncTask.setDiskSyncListener(null); super.onPause(); } @Override protected void onStart() { super.onStart(); Collect.getInstance().getActivityLogger().logOnStart(this); } @Override protected void onStop() { Collect.getInstance().getActivityLogger().logOnStop(this); super.onStop(); } /** * Called by DiskSyncTask when the task is finished */ @Override public void SyncComplete(String result) { Log.i(t, "disk sync task complete"); TextView tv = (TextView) findViewById(R.id.status_text); tv.setText(result); } /** * Creates a dialog with the given message. Will exit the activity when the user preses "ok" if * shouldExit is set to true. * * @param errorMsg * @param shouldExit */ private void createErrorDialog(String errorMsg, final boolean shouldExit) { Collect.getInstance().getActivityLogger().logAction(this, "createErrorDialog", "show"); mAlertDialog = new AlertDialog.Builder(this).create(); mAlertDialog.setIcon(android.R.drawable.ic_dialog_info); mAlertDialog.setMessage(errorMsg); DialogInterface.OnClickListener errorListener = new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int i) { switch (i) { case DialogInterface.BUTTON_POSITIVE: Collect.getInstance().getActivityLogger().logAction(this, "createErrorDialog", shouldExit ? "exitApplication" : "OK"); if (shouldExit) { finish(); } break; } } }; mAlertDialog.setCancelable(false); mAlertDialog.setButton(getString(R.string.ok), errorListener); mAlertDialog.show(); } }
Java
/* * Copyright (C) 2009 University of Washington * * 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 org.odk.collect.android.activities; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.Set; import org.odk.collect.android.R; import org.odk.collect.android.application.Collect; import org.odk.collect.android.listeners.InstanceUploaderListener; import org.odk.collect.android.preferences.PreferencesActivity; import org.odk.collect.android.provider.InstanceProviderAPI.InstanceColumns; import org.odk.collect.android.tasks.InstanceUploaderTask; import org.odk.collect.android.utilities.WebUtils; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.app.ProgressDialog; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.preference.PreferenceManager; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.widget.EditText; /** * Activity to upload completed forms. * * @author Carl Hartung (carlhartung@gmail.com) */ public class InstanceUploaderActivity extends Activity implements InstanceUploaderListener { private final static String t = "InstanceUploaderActivity"; private final static int PROGRESS_DIALOG = 1; private final static int AUTH_DIALOG = 2; private final static String AUTH_URI = "auth"; private static final String ALERT_MSG = "alertmsg"; private static final String ALERT_SHOWING = "alertshowing"; private static final String TO_SEND = "tosend"; private ProgressDialog mProgressDialog; private AlertDialog mAlertDialog; private String mAlertMsg; private boolean mAlertShowing; private InstanceUploaderTask mInstanceUploaderTask; // maintain a list of what we've yet to send, in case we're interrupted by auth requests private Long[] mInstancesToSend; // maintain a list of what we've sent, in case we're interrupted by auth requests private HashMap<String, String> mUploadedInstances; private String mUrl; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Log.i(t, "onCreate: " + ((savedInstanceState == null) ? "creating" : "re-initializing")); mAlertMsg = getString(R.string.please_wait); mAlertShowing = false; mUploadedInstances = new HashMap<String, String>(); setTitle(getString(R.string.app_name) + " > " + getString(R.string.send_data)); // get any simple saved state... if (savedInstanceState != null) { if (savedInstanceState.containsKey(ALERT_MSG)) { mAlertMsg = savedInstanceState.getString(ALERT_MSG); } if (savedInstanceState.containsKey(ALERT_SHOWING)) { mAlertShowing = savedInstanceState.getBoolean(ALERT_SHOWING, false); } mUrl = savedInstanceState.getString(AUTH_URI); } // and if we are resuming, use the TO_SEND list of not-yet-sent submissions // Otherwise, construct the list from the incoming intent value long[] selectedInstanceIDs = null; if (savedInstanceState != null && savedInstanceState.containsKey(TO_SEND)) { selectedInstanceIDs = savedInstanceState.getLongArray(TO_SEND); } else { // get instances to upload... Intent intent = getIntent(); selectedInstanceIDs = intent.getLongArrayExtra(FormEntryActivity.KEY_INSTANCES); } mInstancesToSend = new Long[(selectedInstanceIDs == null) ? 0 : selectedInstanceIDs.length]; if ( selectedInstanceIDs != null ) { for ( int i = 0 ; i < selectedInstanceIDs.length ; ++i ) { mInstancesToSend[i] = selectedInstanceIDs[i]; } } // at this point, we don't expect this to be empty... if (mInstancesToSend.length == 0) { Log.e(t, "onCreate: No instances to upload!"); // drop through -- everything will process through OK } else { Log.i(t, "onCreate: Beginning upload of " + mInstancesToSend.length + " instances!"); } // get the task if we've changed orientations. If it's null it's a new upload. mInstanceUploaderTask = (InstanceUploaderTask) getLastNonConfigurationInstance(); if (mInstanceUploaderTask == null) { // setup dialog and upload task showDialog(PROGRESS_DIALOG); mInstanceUploaderTask = new InstanceUploaderTask(); // register this activity with the new uploader task mInstanceUploaderTask.setUploaderListener(InstanceUploaderActivity.this); mInstanceUploaderTask.execute(mInstancesToSend); } } @Override protected void onStart() { super.onStart(); Collect.getInstance().getActivityLogger().logOnStart(this); } @Override protected void onResume() { Log.i(t, "onResume: Resuming upload of " + mInstancesToSend.length + " instances!"); if (mInstanceUploaderTask != null) { mInstanceUploaderTask.setUploaderListener(this); } if (mAlertShowing) { createAlertDialog(mAlertMsg); } super.onResume(); } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putString(ALERT_MSG, mAlertMsg); outState.putBoolean(ALERT_SHOWING, mAlertShowing); outState.putString(AUTH_URI, mUrl); long[] toSend = new long[mInstancesToSend.length]; for ( int i = 0 ; i < mInstancesToSend.length ; ++i ) { toSend[i] = mInstancesToSend[i]; } outState.putLongArray(TO_SEND, toSend); } @Override public Object onRetainNonConfigurationInstance() { return mInstanceUploaderTask; } @Override protected void onPause() { Log.i(t, "onPause: Pausing upload of " + mInstancesToSend.length + " instances!"); super.onPause(); if (mAlertDialog != null && mAlertDialog.isShowing()) { mAlertDialog.dismiss(); } } @Override protected void onStop() { Collect.getInstance().getActivityLogger().logOnStop(this); super.onStop(); } @Override protected void onDestroy() { if (mInstanceUploaderTask != null) { mInstanceUploaderTask.setUploaderListener(null); } super.onDestroy(); } @Override public void uploadingComplete(HashMap<String, String> result) { Log.i(t, "uploadingComplete: Processing results (" + result.size() + ") from upload of " + mInstancesToSend.length + " instances!"); try { dismissDialog(PROGRESS_DIALOG); } catch (Exception e) { // tried to close a dialog not open. don't care. } StringBuilder selection = new StringBuilder(); Set<String> keys = result.keySet(); Iterator<String> it = keys.iterator(); String[] selectionArgs = new String[keys.size()]; int i = 0; while (it.hasNext()) { String id = it.next(); selection.append(InstanceColumns._ID + "=?"); selectionArgs[i++] = id; if (i != keys.size()) { selection.append(" or "); } } StringBuilder message = new StringBuilder(); { Cursor results = null; try { results = getContentResolver().query(InstanceColumns.CONTENT_URI, null, selection.toString(), selectionArgs, null); if (results.getCount() > 0) { results.moveToPosition(-1); while (results.moveToNext()) { String name = results.getString(results.getColumnIndex(InstanceColumns.DISPLAY_NAME)); String id = results.getString(results.getColumnIndex(InstanceColumns._ID)); message.append(name + " - " + result.get(id) + "\n\n"); } } else { message.append(getString(R.string.no_forms_uploaded)); } } finally { if ( results != null ) { results.close(); } } } createAlertDialog(message.toString().trim()); } @Override public void progressUpdate(int progress, int total) { mAlertMsg = getString(R.string.sending_items, progress, total); mProgressDialog.setMessage(mAlertMsg); } @Override protected Dialog onCreateDialog(int id) { switch (id) { case PROGRESS_DIALOG: Collect.getInstance().getActivityLogger().logAction(this, "onCreateDialog.PROGRESS_DIALOG", "show"); mProgressDialog = new ProgressDialog(this); DialogInterface.OnClickListener loadingButtonListener = new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Collect.getInstance().getActivityLogger().logAction(this, "onCreateDialog.PROGRESS_DIALOG", "cancel"); dialog.dismiss(); mInstanceUploaderTask.cancel(true); mInstanceUploaderTask.setUploaderListener(null); finish(); } }; mProgressDialog.setTitle(getString(R.string.uploading_data)); mProgressDialog.setMessage(mAlertMsg); mProgressDialog.setIndeterminate(true); mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER); mProgressDialog.setCancelable(false); mProgressDialog.setButton(getString(R.string.cancel), loadingButtonListener); return mProgressDialog; case AUTH_DIALOG: Log.i(t, "onCreateDialog(AUTH_DIALOG): for upload of " + mInstancesToSend.length + " instances!"); Collect.getInstance().getActivityLogger().logAction(this, "onCreateDialog.AUTH_DIALOG", "show"); AlertDialog.Builder b = new AlertDialog.Builder(this); LayoutInflater factory = LayoutInflater.from(this); final View dialogView = factory.inflate(R.layout.server_auth_dialog, null); // Get the server, username, and password from the settings SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(getBaseContext()); String server = mUrl; if (server == null) { Log.e(t, "onCreateDialog(AUTH_DIALOG): No failing mUrl specified for upload of " + mInstancesToSend.length + " instances!"); // if the bundle is null, we're looking for a formlist String submissionUrl = getString(R.string.default_odk_submission); server = settings.getString(PreferencesActivity.KEY_SERVER_URL, getString(R.string.default_server_url)) + settings.getString(PreferencesActivity.KEY_SUBMISSION_URL, submissionUrl); } final String url = server; Log.i(t, "Trying connecting to: " + url); EditText username = (EditText) dialogView.findViewById(R.id.username_edit); String storedUsername = settings.getString(PreferencesActivity.KEY_USERNAME, null); username.setText(storedUsername); EditText password = (EditText) dialogView.findViewById(R.id.password_edit); String storedPassword = settings.getString(PreferencesActivity.KEY_PASSWORD, null); password.setText(storedPassword); b.setTitle(getString(R.string.server_requires_auth)); b.setMessage(getString(R.string.server_auth_credentials, url)); b.setView(dialogView); b.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Collect.getInstance().getActivityLogger().logAction(this, "onCreateDialog.AUTH_DIALOG", "OK"); EditText username = (EditText) dialogView.findViewById(R.id.username_edit); EditText password = (EditText) dialogView.findViewById(R.id.password_edit); Uri u = Uri.parse(url); WebUtils.addCredentials(username.getText().toString(), password.getText() .toString(), u.getHost()); showDialog(PROGRESS_DIALOG); mInstanceUploaderTask = new InstanceUploaderTask(); // register this activity with the new uploader task mInstanceUploaderTask.setUploaderListener(InstanceUploaderActivity.this); mInstanceUploaderTask.execute(mInstancesToSend); } }); b.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Collect.getInstance().getActivityLogger().logAction(this, "onCreateDialog.AUTH_DIALOG", "cancel"); finish(); } }); b.setCancelable(false); return b.create(); } return null; } @Override public void authRequest(Uri url, HashMap<String, String> doneSoFar) { if (mProgressDialog.isShowing()) { // should always be showing here mProgressDialog.dismiss(); } // add our list of completed uploads to "completed" // and remove them from our toSend list. ArrayList<Long> workingSet = new ArrayList<Long>(); Collections.addAll(workingSet, mInstancesToSend); if (doneSoFar != null) { Set<String> uploadedInstances = doneSoFar.keySet(); Iterator<String> itr = uploadedInstances.iterator(); while (itr.hasNext()) { Long removeMe = Long.valueOf(itr.next()); boolean removed = workingSet.remove(removeMe); if (removed) { Log.i(t, removeMe + " was already sent, removing from queue before restarting task"); } } mUploadedInstances.putAll(doneSoFar); } // and reconstruct the pending set of instances to send Long[] updatedToSend = new Long[workingSet.size()]; for ( int i = 0 ; i < workingSet.size() ; ++i ) { updatedToSend[i] = workingSet.get(i); } mInstancesToSend = updatedToSend; mUrl = url.toString(); showDialog(AUTH_DIALOG); } private void createAlertDialog(String message) { Collect.getInstance().getActivityLogger().logAction(this, "createAlertDialog", "show"); mAlertDialog = new AlertDialog.Builder(this).create(); mAlertDialog.setTitle(getString(R.string.upload_results)); mAlertDialog.setMessage(message); DialogInterface.OnClickListener quitListener = new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int i) { switch (i) { case DialogInterface.BUTTON_POSITIVE: // ok Collect.getInstance().getActivityLogger().logAction(this, "createAlertDialog", "OK"); // always exit this activity since it has no interface mAlertShowing = false; finish(); break; } } }; mAlertDialog.setCancelable(false); mAlertDialog.setButton(getString(R.string.ok), quitListener); mAlertDialog.setIcon(android.R.drawable.ic_dialog_info); mAlertShowing = true; mAlertMsg = message; mAlertDialog.show(); } }
Java
/* * Copyright (C) 2009 University of Washington * * 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 org.odk.collect.android.activities; import java.util.ArrayList; import java.util.HashMap; import java.util.Set; import org.odk.collect.android.R; import org.odk.collect.android.application.Collect; import org.odk.collect.android.listeners.FormDownloaderListener; import org.odk.collect.android.listeners.FormListDownloaderListener; import org.odk.collect.android.logic.FormDetails; import org.odk.collect.android.preferences.PreferencesActivity; import org.odk.collect.android.tasks.DownloadFormListTask; import org.odk.collect.android.tasks.DownloadFormsTask; import org.odk.collect.android.utilities.CompatibilityUtils; import org.odk.collect.android.utilities.WebUtils; import android.app.AlertDialog; import android.app.Dialog; import android.app.ListActivity; import android.app.ProgressDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.graphics.Color; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.preference.PreferenceManager; import android.util.Log; import android.util.SparseBooleanArray; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.ListView; import android.widget.SimpleAdapter; import android.widget.Toast; /** * Responsible for displaying, adding and deleting all the valid forms in the forms directory. One * caveat. If the server requires authentication, a dialog will pop up asking when you request the * form list. If somehow you manage to wait long enough and then try to download selected forms and * your authorization has timed out, it won't again ask for authentication, it will just throw a 401 * and you'll have to hit 'refresh' where it will ask for credentials again. Technically a server * could point at other servers requiring authentication to download the forms, but the current * implementation in Collect doesn't allow for that. Mostly this is just because it's a pain in the * butt to keep track of which forms we've downloaded and where we're needing to authenticate. I * think we do something similar in the instanceuploader task/activity, so should change the * implementation eventually. * * @author Carl Hartung (carlhartung@gmail.com) */ public class FormDownloadList extends ListActivity implements FormListDownloaderListener, FormDownloaderListener { private static final String t = "RemoveFileManageList"; private static final int PROGRESS_DIALOG = 1; private static final int AUTH_DIALOG = 2; private static final int MENU_PREFERENCES = Menu.FIRST; private static final String BUNDLE_TOGGLED_KEY = "toggled"; private static final String BUNDLE_SELECTED_COUNT = "selectedcount"; private static final String BUNDLE_FORM_MAP = "formmap"; private static final String DIALOG_TITLE = "dialogtitle"; private static final String DIALOG_MSG = "dialogmsg"; private static final String DIALOG_SHOWING = "dialogshowing"; private static final String FORMLIST = "formlist"; public static final String LIST_URL = "listurl"; private static final String FORMNAME = "formname"; private static final String FORMDETAIL_KEY = "formdetailkey"; private static final String FORMID_DISPLAY = "formiddisplay"; private String mAlertMsg; private boolean mAlertShowing = false; private String mAlertTitle; private AlertDialog mAlertDialog; private ProgressDialog mProgressDialog; private Button mDownloadButton; private DownloadFormListTask mDownloadFormListTask; private DownloadFormsTask mDownloadFormsTask; private Button mToggleButton; private Button mRefreshButton; private HashMap<String, FormDetails> mFormNamesAndURLs = new HashMap<String,FormDetails>(); private SimpleAdapter mFormListAdapter; private ArrayList<HashMap<String, String>> mFormList; private boolean mToggled = false; private int mSelectedCount = 0; private static final boolean EXIT = true; private static final boolean DO_NOT_EXIT = false; private boolean mShouldExit; private static final String SHOULD_EXIT = "shouldexit"; @SuppressWarnings("unchecked") @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.remote_file_manage_list); setTitle(getString(R.string.app_name) + " > " + getString(R.string.get_forms)); mAlertMsg = getString(R.string.please_wait); // need white background before load getListView().setBackgroundColor(Color.WHITE); mDownloadButton = (Button) findViewById(R.id.add_button); mDownloadButton.setEnabled(selectedItemCount() > 0); mDownloadButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // this is callled in downloadSelectedFiles(): // Collect.getInstance().getActivityLogger().logAction(this, "downloadSelectedFiles", ...); downloadSelectedFiles(); mToggled = false; clearChoices(); } }); mToggleButton = (Button) findViewById(R.id.toggle_button); mToggleButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // toggle selections of items to all or none ListView ls = getListView(); mToggled = !mToggled; Collect.getInstance().getActivityLogger().logAction(this, "toggleFormCheckbox", Boolean.toString(mToggled)); for (int pos = 0; pos < ls.getCount(); pos++) { ls.setItemChecked(pos, mToggled); } mDownloadButton.setEnabled(!(selectedItemCount() == 0)); } }); mRefreshButton = (Button) findViewById(R.id.refresh_button); mRefreshButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Collect.getInstance().getActivityLogger().logAction(this, "refreshForms", ""); mToggled = false; downloadFormList(); FormDownloadList.this.getListView().clearChoices(); clearChoices(); } }); if (savedInstanceState != null) { // If the screen has rotated, the hashmap with the form ids and urls is passed here. if (savedInstanceState.containsKey(BUNDLE_FORM_MAP)) { mFormNamesAndURLs = (HashMap<String, FormDetails>) savedInstanceState .getSerializable(BUNDLE_FORM_MAP); } // indicating whether or not select-all is on or off. if (savedInstanceState.containsKey(BUNDLE_TOGGLED_KEY)) { mToggled = savedInstanceState.getBoolean(BUNDLE_TOGGLED_KEY); } // how many items we've selected // Android should keep track of this, but broken on rotate... if (savedInstanceState.containsKey(BUNDLE_SELECTED_COUNT)) { mSelectedCount = savedInstanceState.getInt(BUNDLE_SELECTED_COUNT); mDownloadButton.setEnabled(!(mSelectedCount == 0)); } // to restore alert dialog. if (savedInstanceState.containsKey(DIALOG_TITLE)) { mAlertTitle = savedInstanceState.getString(DIALOG_TITLE); } if (savedInstanceState.containsKey(DIALOG_MSG)) { mAlertMsg = savedInstanceState.getString(DIALOG_MSG); } if (savedInstanceState.containsKey(DIALOG_SHOWING)) { mAlertShowing = savedInstanceState.getBoolean(DIALOG_SHOWING); } if (savedInstanceState.containsKey(SHOULD_EXIT)) { mShouldExit = savedInstanceState.getBoolean(SHOULD_EXIT); } } if (savedInstanceState != null && savedInstanceState.containsKey(FORMLIST)) { mFormList = (ArrayList<HashMap<String, String>>) savedInstanceState.getSerializable(FORMLIST); } else { mFormList = new ArrayList<HashMap<String, String>>(); } if (getLastNonConfigurationInstance() instanceof DownloadFormListTask) { mDownloadFormListTask = (DownloadFormListTask) getLastNonConfigurationInstance(); if (mDownloadFormListTask.getStatus() == AsyncTask.Status.FINISHED) { try { dismissDialog(PROGRESS_DIALOG); } catch (IllegalArgumentException e) { Log.i(t, "Attempting to close a dialog that was not previously opened"); } mDownloadFormsTask = null; } } else if (getLastNonConfigurationInstance() instanceof DownloadFormsTask) { mDownloadFormsTask = (DownloadFormsTask) getLastNonConfigurationInstance(); if (mDownloadFormsTask.getStatus() == AsyncTask.Status.FINISHED) { try { dismissDialog(PROGRESS_DIALOG); } catch (IllegalArgumentException e) { Log.i(t, "Attempting to close a dialog that was not previously opened"); } mDownloadFormsTask = null; } } else if (getLastNonConfigurationInstance() == null) { // first time, so get the formlist downloadFormList(); } String[] data = new String[] { FORMNAME, FORMID_DISPLAY, FORMDETAIL_KEY }; int[] view = new int[] { R.id.text1, R.id.text2 }; mFormListAdapter = new SimpleAdapter(this, mFormList, R.layout.two_item_multiple_choice, data, view); getListView().setChoiceMode(ListView.CHOICE_MODE_MULTIPLE); getListView().setItemsCanFocus(false); setListAdapter(mFormListAdapter); } @Override protected void onStart() { super.onStart(); Collect.getInstance().getActivityLogger().logOnStart(this); } @Override protected void onStop() { Collect.getInstance().getActivityLogger().logOnStop(this); super.onStop(); } private void clearChoices() { FormDownloadList.this.getListView().clearChoices(); mDownloadButton.setEnabled(false); } @Override protected void onListItemClick(ListView l, View v, int position, long id) { super.onListItemClick(l, v, position, id); mDownloadButton.setEnabled(!(selectedItemCount() == 0)); Object o = getListAdapter().getItem(position); @SuppressWarnings("unchecked") HashMap<String, String> item = (HashMap<String, String>) o; FormDetails detail = mFormNamesAndURLs.get(item.get(FORMDETAIL_KEY)); if ( detail != null ) { Collect.getInstance().getActivityLogger().logAction(this, "onListItemClick", detail.downloadUrl); } else { Collect.getInstance().getActivityLogger().logAction(this, "onListItemClick", "<missing form detail>"); } } /** * Starts the download task and shows the progress dialog. */ private void downloadFormList() { ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo ni = connectivityManager.getActiveNetworkInfo(); if (ni == null || !ni.isConnected()) { Toast.makeText(this, R.string.no_connection, Toast.LENGTH_SHORT).show(); } else { mFormNamesAndURLs = new HashMap<String, FormDetails>(); if (mProgressDialog != null) { // This is needed because onPrepareDialog() is broken in 1.6. mProgressDialog.setMessage(getString(R.string.please_wait)); } showDialog(PROGRESS_DIALOG); if (mDownloadFormListTask != null && mDownloadFormListTask.getStatus() != AsyncTask.Status.FINISHED) { return; // we are already doing the download!!! } else if (mDownloadFormListTask != null) { mDownloadFormListTask.setDownloaderListener(null); mDownloadFormListTask.cancel(true); mDownloadFormListTask = null; } mDownloadFormListTask = new DownloadFormListTask(); mDownloadFormListTask.setDownloaderListener(this); mDownloadFormListTask.execute(); } } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putBoolean(BUNDLE_TOGGLED_KEY, mToggled); outState.putInt(BUNDLE_SELECTED_COUNT, selectedItemCount()); outState.putSerializable(BUNDLE_FORM_MAP, mFormNamesAndURLs); outState.putString(DIALOG_TITLE, mAlertTitle); outState.putString(DIALOG_MSG, mAlertMsg); outState.putBoolean(DIALOG_SHOWING, mAlertShowing); outState.putBoolean(SHOULD_EXIT, mShouldExit); outState.putSerializable(FORMLIST, mFormList); } /** * returns the number of items currently selected in the list. * * @return */ private int selectedItemCount() { int count = 0; SparseBooleanArray sba = getListView().getCheckedItemPositions(); for (int i = 0; i < getListView().getCount(); i++) { if (sba.get(i, false)) { count++; } } return count; } @Override public boolean onCreateOptionsMenu(Menu menu) { Collect.getInstance().getActivityLogger().logAction(this, "onCreateOptionsMenu", "show"); super.onCreateOptionsMenu(menu); CompatibilityUtils.setShowAsAction( menu.add(0, MENU_PREFERENCES, 0, R.string.general_preferences) .setIcon(R.drawable.ic_menu_preferences), MenuItem.SHOW_AS_ACTION_NEVER); return true; } @Override public boolean onMenuItemSelected(int featureId, MenuItem item) { switch (item.getItemId()) { case MENU_PREFERENCES: Collect.getInstance().getActivityLogger().logAction(this, "onMenuItemSelected", "MENU_PREFERENCES"); Intent i = new Intent(this, PreferencesActivity.class); startActivity(i); return true; } return super.onMenuItemSelected(featureId, item); } @Override protected Dialog onCreateDialog(int id) { switch (id) { case PROGRESS_DIALOG: Collect.getInstance().getActivityLogger().logAction(this, "onCreateDialog.PROGRESS_DIALOG", "show"); mProgressDialog = new ProgressDialog(this); DialogInterface.OnClickListener loadingButtonListener = new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Collect.getInstance().getActivityLogger().logAction(this, "onCreateDialog.PROGRESS_DIALOG", "OK"); dialog.dismiss(); // we use the same progress dialog for both // so whatever isn't null is running if (mDownloadFormListTask != null) { mDownloadFormListTask.setDownloaderListener(null); mDownloadFormListTask.cancel(true); mDownloadFormListTask = null; } if (mDownloadFormsTask != null) { mDownloadFormsTask.setDownloaderListener(null); mDownloadFormsTask.cancel(true); mDownloadFormsTask = null; } } }; mProgressDialog.setTitle(getString(R.string.downloading_data)); mProgressDialog.setMessage(mAlertMsg); mProgressDialog.setIcon(android.R.drawable.ic_dialog_info); mProgressDialog.setIndeterminate(true); mProgressDialog.setCancelable(false); mProgressDialog.setButton(getString(R.string.cancel), loadingButtonListener); return mProgressDialog; case AUTH_DIALOG: Collect.getInstance().getActivityLogger().logAction(this, "onCreateDialog.AUTH_DIALOG", "show"); AlertDialog.Builder b = new AlertDialog.Builder(this); LayoutInflater factory = LayoutInflater.from(this); final View dialogView = factory.inflate(R.layout.server_auth_dialog, null); // Get the server, username, and password from the settings SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(getBaseContext()); String server = settings.getString(PreferencesActivity.KEY_SERVER_URL, getString(R.string.default_server_url)); String formListUrl = getString(R.string.default_odk_formlist); final String url = server + settings.getString(PreferencesActivity.KEY_FORMLIST_URL, formListUrl); Log.i(t, "Trying to get formList from: " + url); EditText username = (EditText) dialogView.findViewById(R.id.username_edit); String storedUsername = settings.getString(PreferencesActivity.KEY_USERNAME, null); username.setText(storedUsername); EditText password = (EditText) dialogView.findViewById(R.id.password_edit); String storedPassword = settings.getString(PreferencesActivity.KEY_PASSWORD, null); password.setText(storedPassword); b.setTitle(getString(R.string.server_requires_auth)); b.setMessage(getString(R.string.server_auth_credentials, url)); b.setView(dialogView); b.setPositiveButton(getString(R.string.ok), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Collect.getInstance().getActivityLogger().logAction(this, "onCreateDialog.AUTH_DIALOG", "OK"); EditText username = (EditText) dialogView.findViewById(R.id.username_edit); EditText password = (EditText) dialogView.findViewById(R.id.password_edit); Uri u = Uri.parse(url); WebUtils.addCredentials(username.getText().toString(), password.getText() .toString(), u.getHost()); downloadFormList(); } }); b.setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Collect.getInstance().getActivityLogger().logAction(this, "onCreateDialog.AUTH_DIALOG", "Cancel"); finish(); } }); b.setCancelable(false); mAlertShowing = false; return b.create(); } return null; } /** * starts the task to download the selected forms, also shows progress dialog */ @SuppressWarnings("unchecked") private void downloadSelectedFiles() { int totalCount = 0; ArrayList<FormDetails> filesToDownload = new ArrayList<FormDetails>(); SparseBooleanArray sba = getListView().getCheckedItemPositions(); for (int i = 0; i < getListView().getCount(); i++) { if (sba.get(i, false)) { HashMap<String, String> item = (HashMap<String, String>) getListAdapter().getItem(i); filesToDownload.add(mFormNamesAndURLs.get(item.get(FORMDETAIL_KEY))); } } totalCount = filesToDownload.size(); Collect.getInstance().getActivityLogger().logAction(this, "downloadSelectedFiles", Integer.toString(totalCount)); if (totalCount > 0) { // show dialog box showDialog(PROGRESS_DIALOG); mDownloadFormsTask = new DownloadFormsTask(); mDownloadFormsTask.setDownloaderListener(this); mDownloadFormsTask.execute(filesToDownload); } else { Toast.makeText(getApplicationContext(), R.string.noselect_error, Toast.LENGTH_SHORT) .show(); } } @Override public Object onRetainNonConfigurationInstance() { if (mDownloadFormsTask != null) { return mDownloadFormsTask; } else { return mDownloadFormListTask; } } @Override protected void onDestroy() { if (mDownloadFormListTask != null) { mDownloadFormListTask.setDownloaderListener(null); } if (mDownloadFormsTask != null) { mDownloadFormsTask.setDownloaderListener(null); } super.onDestroy(); } @Override protected void onResume() { if (mDownloadFormListTask != null) { mDownloadFormListTask.setDownloaderListener(this); } if (mDownloadFormsTask != null) { mDownloadFormsTask.setDownloaderListener(this); } if (mAlertShowing) { createAlertDialog(mAlertTitle, mAlertMsg, mShouldExit); } super.onResume(); } @Override protected void onPause() { if (mAlertDialog != null && mAlertDialog.isShowing()) { mAlertDialog.dismiss(); } super.onPause(); } /** * Called when the form list has finished downloading. results will either contain a set of * <formname, formdetails> tuples, or one tuple of DL.ERROR.MSG and the associated message. * * @param result */ public void formListDownloadingComplete(HashMap<String, FormDetails> result) { dismissDialog(PROGRESS_DIALOG); mDownloadFormListTask.setDownloaderListener(null); mDownloadFormListTask = null; if (result == null) { Log.e(t, "Formlist Downloading returned null. That shouldn't happen"); // Just displayes "error occured" to the user, but this should never happen. createAlertDialog(getString(R.string.load_remote_form_error), getString(R.string.error_occured), EXIT); return; } if (result.containsKey(DownloadFormListTask.DL_AUTH_REQUIRED)) { // need authorization showDialog(AUTH_DIALOG); } else if (result.containsKey(DownloadFormListTask.DL_ERROR_MSG)) { // Download failed String dialogMessage = getString(R.string.list_failed_with_error, result.get(DownloadFormListTask.DL_ERROR_MSG).errorStr); String dialogTitle = getString(R.string.load_remote_form_error); createAlertDialog(dialogTitle, dialogMessage, DO_NOT_EXIT); } else { // Everything worked. Clear the list and add the results. mFormNamesAndURLs = result; mFormList.clear(); ArrayList<String> ids = new ArrayList<String>(mFormNamesAndURLs.keySet()); for (int i = 0; i < result.size(); i++) { String formDetailsKey = ids.get(i); FormDetails details = mFormNamesAndURLs.get(formDetailsKey); HashMap<String, String> item = new HashMap<String, String>(); item.put(FORMNAME, details.formName); item.put(FORMID_DISPLAY, ((details.formVersion == null) ? "" : (getString(R.string.version) + " " + details.formVersion + " ")) + "ID: " + details.formID ); item.put(FORMDETAIL_KEY, formDetailsKey); // Insert the new form in alphabetical order. if (mFormList.size() == 0) { mFormList.add(item); } else { int j; for (j = 0; j < mFormList.size(); j++) { HashMap<String, String> compareMe = mFormList.get(j); String name = compareMe.get(FORMNAME); if (name.compareTo(mFormNamesAndURLs.get(ids.get(i)).formName) > 0) { break; } } mFormList.add(j, item); } } mFormListAdapter.notifyDataSetChanged(); } } /** * Creates an alert dialog with the given tite and message. If shouldExit is set to true, the * activity will exit when the user clicks "ok". * * @param title * @param message * @param shouldExit */ private void createAlertDialog(String title, String message, final boolean shouldExit) { Collect.getInstance().getActivityLogger().logAction(this, "createAlertDialog", "show"); mAlertDialog = new AlertDialog.Builder(this).create(); mAlertDialog.setTitle(title); mAlertDialog.setMessage(message); DialogInterface.OnClickListener quitListener = new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int i) { switch (i) { case DialogInterface.BUTTON_POSITIVE: // ok Collect.getInstance().getActivityLogger().logAction(this, "createAlertDialog", "OK"); // just close the dialog mAlertShowing = false; // successful download, so quit if (shouldExit) { finish(); } break; } } }; mAlertDialog.setCancelable(false); mAlertDialog.setButton(getString(R.string.ok), quitListener); mAlertDialog.setIcon(android.R.drawable.ic_dialog_info); mAlertMsg = message; mAlertTitle = title; mAlertShowing = true; mShouldExit = shouldExit; mAlertDialog.show(); } @Override public void progressUpdate(String currentFile, int progress, int total) { mAlertMsg = getString(R.string.fetching_file, currentFile, progress, total); mProgressDialog.setMessage(mAlertMsg); } @Override public void formsDownloadingComplete(HashMap<FormDetails, String> result) { if (mDownloadFormsTask != null) { mDownloadFormsTask.setDownloaderListener(null); } if (mProgressDialog.isShowing()) { // should always be true here mProgressDialog.dismiss(); } Set<FormDetails> keys = result.keySet(); StringBuilder b = new StringBuilder(); for (FormDetails k : keys) { b.append(k.formName + " (" + ((k.formVersion != null) ? (this.getString(R.string.version) + ": " + k.formVersion + " ") : "") + "ID: " + k.formID + ") - " + result.get(k)); b.append("\n\n"); } createAlertDialog(getString(R.string.download_forms_result), b.toString().trim(), EXIT); } }
Java
/* * Copyright (C) 2009 University of Washington * * 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 org.odk.collect.android.adapters; import org.odk.collect.android.logic.HierarchyElement; import org.odk.collect.android.views.HierarchyElementView; import android.content.Context; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import java.util.ArrayList; import java.util.List; public class HierarchyListAdapter extends BaseAdapter { private Context mContext; private List<HierarchyElement> mItems = new ArrayList<HierarchyElement>(); public HierarchyListAdapter(Context context) { mContext = context; } @Override public int getCount() { return mItems.size(); } @Override public Object getItem(int position) { return mItems.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { HierarchyElementView hev; if (convertView == null) { hev = new HierarchyElementView(mContext, mItems.get(position)); } else { hev = (HierarchyElementView) convertView; hev.setPrimaryText(mItems.get(position).getPrimaryText()); hev.setSecondaryText(mItems.get(position).getSecondaryText()); hev.setIcon(mItems.get(position).getIcon()); hev.setColor(mItems.get(position).getColor()); } if (mItems.get(position).getSecondaryText() == null || mItems.get(position).getSecondaryText().equals("")) { hev.showSecondary(false); } else { hev.showSecondary(true); } return hev; } /** * Sets the list of items for this adapter to use. */ public void setListItems(List<HierarchyElement> it) { mItems = it; } }
Java
/* * Copyright (C) 2009 University of Washington * * 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 org.odk.collect.android.adapters; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import java.util.Locale; import org.odk.collect.android.R; import org.odk.collect.android.logic.DriveListItem; import android.content.Context; import android.graphics.drawable.Drawable; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.CheckBox; import android.widget.ImageView; import android.widget.TextView; public class FileArrayAdapter extends ArrayAdapter<DriveListItem> { private Context c; private int id; private List<DriveListItem> items; public FileArrayAdapter(Context context, int textViewResourceId, List<DriveListItem> objects) { super(context, textViewResourceId, objects); c = context; id = textViewResourceId; items = objects; } public DriveListItem getItem(int i) { return items.get(i); } @Override public View getView(int position, View convertView, ViewGroup parent) { View v = convertView; if (v == null) { LayoutInflater vi = (LayoutInflater) c.getSystemService(Context.LAYOUT_INFLATER_SERVICE); v = vi.inflate(id, null); } /* create a new view of my layout and inflate it in the row */ //convertView = ( RelativeLayout ) inflater.inflate( resource, null ); final DriveListItem o = items.get(position); if (o != null) { String dateModified = null; if (o.getDate() != null) { dateModified = new SimpleDateFormat(getContext().getString( R.string.modified_on_date_at_time), Locale.getDefault()) .format(new Date(o.getDate().getValue())); } TextView t1 = (TextView) v.findViewById(R.id.text1); TextView t2 = (TextView) v.findViewById(R.id.text2); ImageView iv = (ImageView) v.findViewById(R.id.image); CheckBox cb = (CheckBox) v.findViewById(R.id.checkbox); if (o.getType() == 1) { Drawable d = c.getResources().getDrawable(R.drawable.ic_download); iv.setImageDrawable(d); cb.setVisibility(View.VISIBLE); } if (o.getType() == 3) { Drawable d = c.getResources().getDrawable(R.drawable.ic_back); iv.setImageDrawable(d); } if (o.getType() == 2 || o.getType() == 4 || o.getType() == 5) { Drawable d = c.getResources().getDrawable(R.drawable.ic_folder); iv.setImageDrawable(d); } if (t1 != null) t1.setText(o.getName()); if (t2 != null) t2.setText(dateModified); } return v; } }
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 org.odk.collect.android.provider; import android.net.Uri; import android.provider.BaseColumns; /** * Convenience definitions for NotePadProvider */ public final class InstanceProviderAPI { public static final String AUTHORITY = "org.odk.collect.android.provider.odk.instances"; // This class cannot be instantiated private InstanceProviderAPI() {} // status for instances public static final String STATUS_INCOMPLETE = "incomplete"; public static final String STATUS_COMPLETE = "complete"; public static final String STATUS_SUBMITTED = "submitted"; public static final String STATUS_SUBMISSION_FAILED = "submissionFailed"; /** * Notes table */ public static final class InstanceColumns implements BaseColumns { // This class cannot be instantiated private InstanceColumns() {} public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/instances"); public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.odk.instance"; public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.odk.instance"; // These are the only things needed for an insert public static final String DISPLAY_NAME = "displayName"; public static final String SUBMISSION_URI = "submissionUri"; public static final String INSTANCE_FILE_PATH = "instanceFilePath"; public static final String JR_FORM_ID = "jrFormId"; public static final String JR_VERSION = "jrVersion"; //public static final String FORM_ID = "formId"; // these are generated for you (but you can insert something else if you want) public static final String STATUS = "status"; public static final String CAN_EDIT_WHEN_COMPLETE = "canEditWhenComplete"; public static final String LAST_STATUS_CHANGE_DATE = "date"; public static final String DISPLAY_SUBTEXT = "displaySubtext"; //public static final String DISPLAY_SUB_SUBTEXT = "displaySubSubtext"; // public static final String DEFAULT_SORT_ORDER = "modified DESC"; // public static final String TITLE = "title"; // public static final String NOTE = "note"; // public static final String CREATED_DATE = "created"; // public static final String MODIFIED_DATE = "modified"; } }
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 org.odk.collect.android.provider; import org.odk.collect.android.R; import org.odk.collect.android.application.Collect; import org.odk.collect.android.database.ODKSQLiteOpenHelper; import org.odk.collect.android.provider.InstanceProviderAPI.InstanceColumns; import org.odk.collect.android.utilities.MediaUtils; import android.content.ContentProvider; import android.content.ContentUris; import android.content.ContentValues; import android.content.UriMatcher; import android.database.Cursor; import android.database.SQLException; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteQueryBuilder; import android.net.Uri; import android.text.TextUtils; import android.util.Log; import java.io.File; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import java.util.Locale; /** * */ public class InstanceProvider extends ContentProvider { private static final String t = "InstancesProvider"; private static final String DATABASE_NAME = "instances.db"; private static final int DATABASE_VERSION = 3; private static final String INSTANCES_TABLE_NAME = "instances"; private static HashMap<String, String> sInstancesProjectionMap; private static final int INSTANCES = 1; private static final int INSTANCE_ID = 2; private static final UriMatcher sUriMatcher; /** * This class helps open, create, and upgrade the database file. */ private static class DatabaseHelper extends ODKSQLiteOpenHelper { DatabaseHelper(String databaseName) { super(Collect.METADATA_PATH, databaseName, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL("CREATE TABLE " + INSTANCES_TABLE_NAME + " (" + InstanceColumns._ID + " integer primary key, " + InstanceColumns.DISPLAY_NAME + " text not null, " + InstanceColumns.SUBMISSION_URI + " text, " + InstanceColumns.CAN_EDIT_WHEN_COMPLETE + " text, " + InstanceColumns.INSTANCE_FILE_PATH + " text not null, " + InstanceColumns.JR_FORM_ID + " text not null, " + InstanceColumns.JR_VERSION + " text, " + InstanceColumns.STATUS + " text not null, " + InstanceColumns.LAST_STATUS_CHANGE_DATE + " date not null, " + InstanceColumns.DISPLAY_SUBTEXT + " text not null );"); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { int initialVersion = oldVersion; if ( oldVersion == 1 ) { db.execSQL("ALTER TABLE " + INSTANCES_TABLE_NAME + " ADD COLUMN " + InstanceColumns.CAN_EDIT_WHEN_COMPLETE + " text;"); db.execSQL("UPDATE " + INSTANCES_TABLE_NAME + " SET " + InstanceColumns.CAN_EDIT_WHEN_COMPLETE + " = '" + Boolean.toString(true) + "' WHERE " + InstanceColumns.STATUS + " IS NOT NULL AND " + InstanceColumns.STATUS + " != '" + InstanceProviderAPI.STATUS_INCOMPLETE + "'"); oldVersion = 2; } if ( oldVersion == 2 ) { db.execSQL("ALTER TABLE " + INSTANCES_TABLE_NAME + " ADD COLUMN " + InstanceColumns.JR_VERSION + " text;"); } Log.w(t, "Successfully upgraded database from version " + initialVersion + " to " + newVersion + ", without destroying all the old data"); } } private DatabaseHelper mDbHelper; private DatabaseHelper getDbHelper() { // wrapper to test and reset/set the dbHelper based upon the attachment state of the device. try { Collect.createODKDirs(); } catch (RuntimeException e) { mDbHelper = null; return null; } if (mDbHelper != null) { return mDbHelper; } mDbHelper = new DatabaseHelper(DATABASE_NAME); return mDbHelper; } @Override public boolean onCreate() { // must be at the beginning of any activity that can be called from an external intent DatabaseHelper h = getDbHelper(); if ( h == null ) { return false; } return true; } @Override public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) { SQLiteQueryBuilder qb = new SQLiteQueryBuilder(); qb.setTables(INSTANCES_TABLE_NAME); switch (sUriMatcher.match(uri)) { case INSTANCES: qb.setProjectionMap(sInstancesProjectionMap); break; case INSTANCE_ID: qb.setProjectionMap(sInstancesProjectionMap); qb.appendWhere(InstanceColumns._ID + "=" + uri.getPathSegments().get(1)); break; default: throw new IllegalArgumentException("Unknown URI " + uri); } // Get the database and run the query SQLiteDatabase db = getDbHelper().getReadableDatabase(); Cursor c = qb.query(db, projection, selection, selectionArgs, null, null, sortOrder); // Tell the cursor what uri to watch, so it knows when its source data changes c.setNotificationUri(getContext().getContentResolver(), uri); return c; } @Override public String getType(Uri uri) { switch (sUriMatcher.match(uri)) { case INSTANCES: return InstanceColumns.CONTENT_TYPE; case INSTANCE_ID: return InstanceColumns.CONTENT_ITEM_TYPE; default: throw new IllegalArgumentException("Unknown URI " + uri); } } @Override public Uri insert(Uri uri, ContentValues initialValues) { // Validate the requested uri if (sUriMatcher.match(uri) != INSTANCES) { throw new IllegalArgumentException("Unknown URI " + uri); } ContentValues values; if (initialValues != null) { values = new ContentValues(initialValues); } else { values = new ContentValues(); } Long now = Long.valueOf(System.currentTimeMillis()); // Make sure that the fields are all set if (values.containsKey(InstanceColumns.LAST_STATUS_CHANGE_DATE) == false) { values.put(InstanceColumns.LAST_STATUS_CHANGE_DATE, now); } if (values.containsKey(InstanceColumns.DISPLAY_SUBTEXT) == false) { Date today = new Date(); String text = getDisplaySubtext(InstanceProviderAPI.STATUS_INCOMPLETE, today); values.put(InstanceColumns.DISPLAY_SUBTEXT, text); } if (values.containsKey(InstanceColumns.STATUS) == false) { values.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_INCOMPLETE); } SQLiteDatabase db = getDbHelper().getWritableDatabase(); long rowId = db.insert(INSTANCES_TABLE_NAME, null, values); if (rowId > 0) { Uri instanceUri = ContentUris.withAppendedId(InstanceColumns.CONTENT_URI, rowId); getContext().getContentResolver().notifyChange(instanceUri, null); Collect.getInstance().getActivityLogger().logActionParam(this, "insert", instanceUri.toString(), values.getAsString(InstanceColumns.INSTANCE_FILE_PATH)); return instanceUri; } throw new SQLException("Failed to insert row into " + uri); } private String getDisplaySubtext(String state, Date date) { if (state == null) { return new SimpleDateFormat(getContext().getString(R.string.added_on_date_at_time), Locale.getDefault()).format(date); } else if (InstanceProviderAPI.STATUS_INCOMPLETE.equalsIgnoreCase(state)) { return new SimpleDateFormat(getContext().getString(R.string.saved_on_date_at_time), Locale.getDefault()).format(date); } else if (InstanceProviderAPI.STATUS_COMPLETE.equalsIgnoreCase(state)) { return new SimpleDateFormat(getContext().getString(R.string.finalized_on_date_at_time), Locale.getDefault()).format(date); } else if (InstanceProviderAPI.STATUS_SUBMITTED.equalsIgnoreCase(state)) { return new SimpleDateFormat(getContext().getString(R.string.sent_on_date_at_time), Locale.getDefault()).format(date); } else if (InstanceProviderAPI.STATUS_SUBMISSION_FAILED.equalsIgnoreCase(state)) { return new SimpleDateFormat(getContext().getString(R.string.sending_failed_on_date_at_time), Locale.getDefault()).format(date); } else { return new SimpleDateFormat(getContext().getString(R.string.added_on_date_at_time), Locale.getDefault()).format(date); } } private void deleteAllFilesInDirectory(File directory) { if (directory.exists()) { // do not delete the directory if it might be an // ODK Tables instance data directory. Let ODK Tables // manage the lifetimes of its filled-in form data // media attachments. if (directory.isDirectory() && !Collect.isODKTablesInstanceDataDirectory(directory)) { // delete any media entries for files in this directory... int images = MediaUtils.deleteImagesInFolderFromMediaProvider(directory); int audio = MediaUtils.deleteAudioInFolderFromMediaProvider(directory); int video = MediaUtils.deleteVideoInFolderFromMediaProvider(directory); Log.i(t, "removed from content providers: " + images + " image files, " + audio + " audio files," + " and " + video + " video files."); // delete all the files in the directory File[] files = directory.listFiles(); for (File f : files) { // should make this recursive if we get worried about // the media directory containing directories f.delete(); } } directory.delete(); } } /** * This method removes the entry from the content provider, and also removes any associated files. * files: form.xml, [formmd5].formdef, formname-media {directory} */ @Override public int delete(Uri uri, String where, String[] whereArgs) { SQLiteDatabase db = getDbHelper().getWritableDatabase(); int count; switch (sUriMatcher.match(uri)) { case INSTANCES: Cursor del = null; try { del = this.query(uri, null, where, whereArgs, null); if (del.getCount() > 0) { del.moveToFirst(); do { String instanceFile = del.getString(del.getColumnIndex(InstanceColumns.INSTANCE_FILE_PATH)); Collect.getInstance().getActivityLogger().logAction(this, "delete", instanceFile); File instanceDir = (new File(instanceFile)).getParentFile(); deleteAllFilesInDirectory(instanceDir); } while (del.moveToNext()); } } finally { if ( del != null ) { del.close(); } } count = db.delete(INSTANCES_TABLE_NAME, where, whereArgs); break; case INSTANCE_ID: String instanceId = uri.getPathSegments().get(1); Cursor c = null; try { c = this.query(uri, null, where, whereArgs, null); if (c.getCount() > 0) { c.moveToFirst(); do { String instanceFile = c.getString(c.getColumnIndex(InstanceColumns.INSTANCE_FILE_PATH)); Collect.getInstance().getActivityLogger().logAction(this, "delete", instanceFile); File instanceDir = (new File(instanceFile)).getParentFile(); deleteAllFilesInDirectory(instanceDir); } while (c.moveToNext()); } } finally { if ( c != null ) { c.close(); } } count = db.delete(INSTANCES_TABLE_NAME, InstanceColumns._ID + "=" + instanceId + (!TextUtils.isEmpty(where) ? " AND (" + where + ')' : ""), whereArgs); break; default: throw new IllegalArgumentException("Unknown URI " + uri); } getContext().getContentResolver().notifyChange(uri, null); return count; } @Override public int update(Uri uri, ContentValues values, String where, String[] whereArgs) { SQLiteDatabase db = getDbHelper().getWritableDatabase(); Long now = Long.valueOf(System.currentTimeMillis()); // Make sure that the fields are all set if (values.containsKey(InstanceColumns.LAST_STATUS_CHANGE_DATE) == false) { values.put(InstanceColumns.LAST_STATUS_CHANGE_DATE, now); } int count; String status = null; switch (sUriMatcher.match(uri)) { case INSTANCES: if (values.containsKey(InstanceColumns.STATUS)) { status = values.getAsString(InstanceColumns.STATUS); if (values.containsKey(InstanceColumns.DISPLAY_SUBTEXT) == false) { Date today = new Date(); String text = getDisplaySubtext(status, today); values.put(InstanceColumns.DISPLAY_SUBTEXT, text); } } count = db.update(INSTANCES_TABLE_NAME, values, where, whereArgs); break; case INSTANCE_ID: String instanceId = uri.getPathSegments().get(1); if (values.containsKey(InstanceColumns.STATUS)) { status = values.getAsString(InstanceColumns.STATUS); if (values.containsKey(InstanceColumns.DISPLAY_SUBTEXT) == false) { Date today = new Date(); String text = getDisplaySubtext(status, today); values.put(InstanceColumns.DISPLAY_SUBTEXT, text); } } count = db.update(INSTANCES_TABLE_NAME, values, InstanceColumns._ID + "=" + instanceId + (!TextUtils.isEmpty(where) ? " AND (" + where + ')' : ""), whereArgs); break; default: throw new IllegalArgumentException("Unknown URI " + uri); } getContext().getContentResolver().notifyChange(uri, null); return count; } static { sUriMatcher = new UriMatcher(UriMatcher.NO_MATCH); sUriMatcher.addURI(InstanceProviderAPI.AUTHORITY, "instances", INSTANCES); sUriMatcher.addURI(InstanceProviderAPI.AUTHORITY, "instances/#", INSTANCE_ID); sInstancesProjectionMap = new HashMap<String, String>(); sInstancesProjectionMap.put(InstanceColumns._ID, InstanceColumns._ID); sInstancesProjectionMap.put(InstanceColumns.DISPLAY_NAME, InstanceColumns.DISPLAY_NAME); sInstancesProjectionMap.put(InstanceColumns.SUBMISSION_URI, InstanceColumns.SUBMISSION_URI); sInstancesProjectionMap.put(InstanceColumns.CAN_EDIT_WHEN_COMPLETE, InstanceColumns.CAN_EDIT_WHEN_COMPLETE); sInstancesProjectionMap.put(InstanceColumns.INSTANCE_FILE_PATH, InstanceColumns.INSTANCE_FILE_PATH); sInstancesProjectionMap.put(InstanceColumns.JR_FORM_ID, InstanceColumns.JR_FORM_ID); sInstancesProjectionMap.put(InstanceColumns.JR_VERSION, InstanceColumns.JR_VERSION); sInstancesProjectionMap.put(InstanceColumns.STATUS, InstanceColumns.STATUS); sInstancesProjectionMap.put(InstanceColumns.LAST_STATUS_CHANGE_DATE, InstanceColumns.LAST_STATUS_CHANGE_DATE); sInstancesProjectionMap.put(InstanceColumns.DISPLAY_SUBTEXT, InstanceColumns.DISPLAY_SUBTEXT); } }
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 org.odk.collect.android.provider; import android.net.Uri; import android.provider.BaseColumns; /** * Convenience definitions for NotePadProvider */ public final class FormsProviderAPI { public static final String AUTHORITY = "org.odk.collect.android.provider.odk.forms"; // This class cannot be instantiated private FormsProviderAPI() {} /** * Notes table */ public static final class FormsColumns implements BaseColumns { // This class cannot be instantiated private FormsColumns() {} public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/forms"); public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.odk.form"; public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.odk.form"; // These are the only things needed for an insert public static final String DISPLAY_NAME = "displayName"; public static final String DESCRIPTION = "description"; // can be null public static final String JR_FORM_ID = "jrFormId"; public static final String JR_VERSION = "jrVersion"; // can be null public static final String FORM_FILE_PATH = "formFilePath"; public static final String SUBMISSION_URI = "submissionUri"; // can be null public static final String BASE64_RSA_PUBLIC_KEY = "base64RsaPublicKey"; // can be null // these are generated for you (but you can insert something else if you want) public static final String DISPLAY_SUBTEXT = "displaySubtext"; public static final String MD5_HASH = "md5Hash"; public static final String DATE = "date"; public static final String JRCACHE_FILE_PATH = "jrcacheFilePath"; public static final String FORM_MEDIA_PATH = "formMediaPath"; // this is null on create, and can only be set on an update. public static final String LANGUAGE = "language"; } }
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 org.odk.collect.android.provider; import java.io.File; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import java.util.Locale; import org.odk.collect.android.R; import org.odk.collect.android.application.Collect; import org.odk.collect.android.database.ItemsetDbAdapter; import org.odk.collect.android.database.ODKSQLiteOpenHelper; import org.odk.collect.android.provider.FormsProviderAPI.FormsColumns; import org.odk.collect.android.utilities.FileUtils; import org.odk.collect.android.utilities.MediaUtils; import android.content.ContentProvider; import android.content.ContentUris; import android.content.ContentValues; import android.content.UriMatcher; import android.database.Cursor; import android.database.SQLException; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteQueryBuilder; import android.net.Uri; import android.text.TextUtils; import android.util.Log; /** * */ public class FormsProvider extends ContentProvider { private static final String t = "FormsProvider"; private static final String DATABASE_NAME = "forms.db"; private static final int DATABASE_VERSION = 4; private static final String FORMS_TABLE_NAME = "forms"; private static HashMap<String, String> sFormsProjectionMap; private static final int FORMS = 1; private static final int FORM_ID = 2; private static final UriMatcher sUriMatcher; /** * This class helps open, create, and upgrade the database file. */ private static class DatabaseHelper extends ODKSQLiteOpenHelper { // These exist in database versions 2 and 3, but not in 4... private static final String TEMP_FORMS_TABLE_NAME = "forms_v4"; private static final String MODEL_VERSION = "modelVersion"; DatabaseHelper(String databaseName) { super(Collect.METADATA_PATH, databaseName, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase db) { onCreateNamed(db, FORMS_TABLE_NAME); } private void onCreateNamed(SQLiteDatabase db, String tableName) { db.execSQL("CREATE TABLE " + tableName + " (" + FormsColumns._ID + " integer primary key, " + FormsColumns.DISPLAY_NAME + " text not null, " + FormsColumns.DISPLAY_SUBTEXT + " text not null, " + FormsColumns.DESCRIPTION + " text, " + FormsColumns.JR_FORM_ID + " text not null, " + FormsColumns.JR_VERSION + " text, " + FormsColumns.MD5_HASH + " text not null, " + FormsColumns.DATE + " integer not null, " // milliseconds + FormsColumns.FORM_MEDIA_PATH + " text not null, " + FormsColumns.FORM_FILE_PATH + " text not null, " + FormsColumns.LANGUAGE + " text, " + FormsColumns.SUBMISSION_URI + " text, " + FormsColumns.BASE64_RSA_PUBLIC_KEY + " text, " + FormsColumns.JRCACHE_FILE_PATH + " text not null );"); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { int initialVersion = oldVersion; if (oldVersion < 2) { Log.w(t, "Upgrading database from version " + oldVersion + " to " + newVersion + ", which will destroy all old data"); db.execSQL("DROP TABLE IF EXISTS " + FORMS_TABLE_NAME); onCreate(db); return; } else { // adding BASE64_RSA_PUBLIC_KEY and changing type and name of // integer MODEL_VERSION to text VERSION db.execSQL("DROP TABLE IF EXISTS " + TEMP_FORMS_TABLE_NAME); onCreateNamed(db, TEMP_FORMS_TABLE_NAME); db.execSQL("INSERT INTO " + TEMP_FORMS_TABLE_NAME + " (" + FormsColumns._ID + ", " + FormsColumns.DISPLAY_NAME + ", " + FormsColumns.DISPLAY_SUBTEXT + ", " + FormsColumns.DESCRIPTION + ", " + FormsColumns.JR_FORM_ID + ", " + FormsColumns.MD5_HASH + ", " + FormsColumns.DATE + ", " // milliseconds + FormsColumns.FORM_MEDIA_PATH + ", " + FormsColumns.FORM_FILE_PATH + ", " + FormsColumns.LANGUAGE + ", " + FormsColumns.SUBMISSION_URI + ", " + FormsColumns.JR_VERSION + ", " + ((oldVersion != 3) ? "" : (FormsColumns.BASE64_RSA_PUBLIC_KEY + ", ")) + FormsColumns.JRCACHE_FILE_PATH + ") SELECT " + FormsColumns._ID + ", " + FormsColumns.DISPLAY_NAME + ", " + FormsColumns.DISPLAY_SUBTEXT + ", " + FormsColumns.DESCRIPTION + ", " + FormsColumns.JR_FORM_ID + ", " + FormsColumns.MD5_HASH + ", " + FormsColumns.DATE + ", " // milliseconds + FormsColumns.FORM_MEDIA_PATH + ", " + FormsColumns.FORM_FILE_PATH + ", " + FormsColumns.LANGUAGE + ", " + FormsColumns.SUBMISSION_URI + ", " + "CASE WHEN " + MODEL_VERSION + " IS NOT NULL THEN " + "CAST(" + MODEL_VERSION + " AS TEXT) ELSE NULL END, " + ((oldVersion != 3) ? "" : (FormsColumns.BASE64_RSA_PUBLIC_KEY + ", ")) + FormsColumns.JRCACHE_FILE_PATH + " FROM " + FORMS_TABLE_NAME); // risky failures here... db.execSQL("DROP TABLE IF EXISTS " + FORMS_TABLE_NAME); onCreateNamed(db, FORMS_TABLE_NAME); db.execSQL("INSERT INTO " + FORMS_TABLE_NAME + " (" + FormsColumns._ID + ", " + FormsColumns.DISPLAY_NAME + ", " + FormsColumns.DISPLAY_SUBTEXT + ", " + FormsColumns.DESCRIPTION + ", " + FormsColumns.JR_FORM_ID + ", " + FormsColumns.MD5_HASH + ", " + FormsColumns.DATE + ", " // milliseconds + FormsColumns.FORM_MEDIA_PATH + ", " + FormsColumns.FORM_FILE_PATH + ", " + FormsColumns.LANGUAGE + ", " + FormsColumns.SUBMISSION_URI + ", " + FormsColumns.JR_VERSION + ", " + FormsColumns.BASE64_RSA_PUBLIC_KEY + ", " + FormsColumns.JRCACHE_FILE_PATH + ") SELECT " + FormsColumns._ID + ", " + FormsColumns.DISPLAY_NAME + ", " + FormsColumns.DISPLAY_SUBTEXT + ", " + FormsColumns.DESCRIPTION + ", " + FormsColumns.JR_FORM_ID + ", " + FormsColumns.MD5_HASH + ", " + FormsColumns.DATE + ", " // milliseconds + FormsColumns.FORM_MEDIA_PATH + ", " + FormsColumns.FORM_FILE_PATH + ", " + FormsColumns.LANGUAGE + ", " + FormsColumns.SUBMISSION_URI + ", " + FormsColumns.JR_VERSION + ", " + FormsColumns.BASE64_RSA_PUBLIC_KEY + ", " + FormsColumns.JRCACHE_FILE_PATH + " FROM " + TEMP_FORMS_TABLE_NAME); db.execSQL("DROP TABLE IF EXISTS " + TEMP_FORMS_TABLE_NAME); Log.w(t, "Successfully upgraded database from version " + initialVersion + " to " + newVersion + ", without destroying all the old data"); } } } private DatabaseHelper mDbHelper; private DatabaseHelper getDbHelper() { // wrapper to test and reset/set the dbHelper based upon the attachment state of the device. try { Collect.createODKDirs(); } catch (RuntimeException e) { mDbHelper = null; return null; } if (mDbHelper != null) { return mDbHelper; } mDbHelper = new DatabaseHelper(DATABASE_NAME); return mDbHelper; } @Override public boolean onCreate() { // must be at the beginning of any activity that can be called from an external intent DatabaseHelper h = getDbHelper(); if ( h == null ) { return false; } return true; } @Override public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) { SQLiteQueryBuilder qb = new SQLiteQueryBuilder(); qb.setTables(FORMS_TABLE_NAME); switch (sUriMatcher.match(uri)) { case FORMS: qb.setProjectionMap(sFormsProjectionMap); break; case FORM_ID: qb.setProjectionMap(sFormsProjectionMap); qb.appendWhere(FormsColumns._ID + "=" + uri.getPathSegments().get(1)); break; default: throw new IllegalArgumentException("Unknown URI " + uri); } // Get the database and run the query SQLiteDatabase db = getDbHelper().getReadableDatabase(); Cursor c = qb.query(db, projection, selection, selectionArgs, null, null, sortOrder); // Tell the cursor what uri to watch, so it knows when its source data // changes c.setNotificationUri(getContext().getContentResolver(), uri); return c; } @Override public String getType(Uri uri) { switch (sUriMatcher.match(uri)) { case FORMS: return FormsColumns.CONTENT_TYPE; case FORM_ID: return FormsColumns.CONTENT_ITEM_TYPE; default: throw new IllegalArgumentException("Unknown URI " + uri); } } @Override public synchronized Uri insert(Uri uri, ContentValues initialValues) { // Validate the requested uri if (sUriMatcher.match(uri) != FORMS) { throw new IllegalArgumentException("Unknown URI " + uri); } ContentValues values; if (initialValues != null) { values = new ContentValues(initialValues); } else { values = new ContentValues(); } if (!values.containsKey(FormsColumns.FORM_FILE_PATH)) { throw new IllegalArgumentException(FormsColumns.FORM_FILE_PATH + " must be specified."); } // Normalize the file path. // (don't trust the requester). String filePath = values.getAsString(FormsColumns.FORM_FILE_PATH); File form = new File(filePath); filePath = form.getAbsolutePath(); // normalized values.put(FormsColumns.FORM_FILE_PATH, filePath); Long now = Long.valueOf(System.currentTimeMillis()); // Make sure that the necessary fields are all set if (values.containsKey(FormsColumns.DATE) == false) { values.put(FormsColumns.DATE, now); } if (values.containsKey(FormsColumns.DISPLAY_SUBTEXT) == false) { Date today = new Date(); String ts = new SimpleDateFormat(getContext().getString( R.string.added_on_date_at_time), Locale.getDefault()) .format(today); values.put(FormsColumns.DISPLAY_SUBTEXT, ts); } if (values.containsKey(FormsColumns.DISPLAY_NAME) == false) { values.put(FormsColumns.DISPLAY_NAME, form.getName()); } // don't let users put in a manual md5 hash if (values.containsKey(FormsColumns.MD5_HASH)) { values.remove(FormsColumns.MD5_HASH); } String md5 = FileUtils.getMd5Hash(form); values.put(FormsColumns.MD5_HASH, md5); if (values.containsKey(FormsColumns.JRCACHE_FILE_PATH) == false) { String cachePath = Collect.CACHE_PATH + File.separator + md5 + ".formdef"; values.put(FormsColumns.JRCACHE_FILE_PATH, cachePath); } if (values.containsKey(FormsColumns.FORM_MEDIA_PATH) == false) { String pathNoExtension = filePath.substring(0, filePath.lastIndexOf(".")); String mediaPath = pathNoExtension + "-media"; values.put(FormsColumns.FORM_MEDIA_PATH, mediaPath); } SQLiteDatabase db = getDbHelper().getWritableDatabase(); // first try to see if a record with this filename already exists... String[] projection = { FormsColumns._ID, FormsColumns.FORM_FILE_PATH }; String[] selectionArgs = { filePath }; String selection = FormsColumns.FORM_FILE_PATH + "=?"; Cursor c = null; try { c = db.query(FORMS_TABLE_NAME, projection, selection, selectionArgs, null, null, null); if (c.getCount() > 0) { // already exists throw new SQLException("FAILED Insert into " + uri + " -- row already exists for form definition file: " + filePath); } } finally { if (c != null) { c.close(); } } long rowId = db.insert(FORMS_TABLE_NAME, null, values); if (rowId > 0) { Uri formUri = ContentUris.withAppendedId(FormsColumns.CONTENT_URI, rowId); getContext().getContentResolver().notifyChange(formUri, null); Collect.getInstance() .getActivityLogger() .logActionParam(this, "insert", formUri.toString(), values.getAsString(FormsColumns.FORM_FILE_PATH)); return formUri; } throw new SQLException("Failed to insert row into " + uri); } private void deleteFileOrDir(String fileName) { File file = new File(fileName); if (file.exists()) { if (file.isDirectory()) { // delete any media entries for files in this directory... int images = MediaUtils .deleteImagesInFolderFromMediaProvider(file); int audio = MediaUtils .deleteAudioInFolderFromMediaProvider(file); int video = MediaUtils .deleteVideoInFolderFromMediaProvider(file); Log.i(t, "removed from content providers: " + images + " image files, " + audio + " audio files," + " and " + video + " video files."); // delete all the containing files File[] files = file.listFiles(); for (File f : files) { // should make this recursive if we get worried about // the media directory containing directories Log.i(t, "attempting to delete file: " + f.getAbsolutePath()); f.delete(); } } file.delete(); Log.i(t, "attempting to delete file: " + file.getAbsolutePath()); } } /** * This method removes the entry from the content provider, and also removes * any associated files. files: form.xml, [formmd5].formdef, formname-media * {directory} */ @Override public int delete(Uri uri, String where, String[] whereArgs) { SQLiteDatabase db = getDbHelper().getWritableDatabase(); int count; switch (sUriMatcher.match(uri)) { case FORMS: Cursor del = null; try { del = this.query(uri, null, where, whereArgs, null); if (del.getCount() > 0) { del.moveToFirst(); do { deleteFileOrDir(del .getString(del .getColumnIndex(FormsColumns.JRCACHE_FILE_PATH))); String formFilePath = del.getString(del .getColumnIndex(FormsColumns.FORM_FILE_PATH)); Collect.getInstance().getActivityLogger() .logAction(this, "delete", formFilePath); deleteFileOrDir(formFilePath); deleteFileOrDir(del.getString(del .getColumnIndex(FormsColumns.FORM_MEDIA_PATH))); } while (del.moveToNext()); } } finally { if (del != null) { del.close(); } } count = db.delete(FORMS_TABLE_NAME, where, whereArgs); break; case FORM_ID: String formId = uri.getPathSegments().get(1); Cursor c = null; try { c = this.query(uri, null, where, whereArgs, null); // This should only ever return 1 record. if (c.getCount() > 0) { c.moveToFirst(); do { deleteFileOrDir(c.getString(c .getColumnIndex(FormsColumns.JRCACHE_FILE_PATH))); String formFilePath = c.getString(c .getColumnIndex(FormsColumns.FORM_FILE_PATH)); Collect.getInstance().getActivityLogger() .logAction(this, "delete", formFilePath); deleteFileOrDir(formFilePath); deleteFileOrDir(c.getString(c .getColumnIndex(FormsColumns.FORM_MEDIA_PATH))); try { // get rid of the old tables ItemsetDbAdapter ida = new ItemsetDbAdapter(); ida.open(); ida.delete(c.getString(c .getColumnIndex(FormsColumns.FORM_MEDIA_PATH)) + "/itemsets.csv"); ida.close(); } catch (Exception e) { // if something else is accessing the provider this may not exist // so catch it and move on. } } while (c.moveToNext()); } } finally { if (c != null) { c.close(); } } count = db.delete( FORMS_TABLE_NAME, FormsColumns._ID + "=" + formId + (!TextUtils.isEmpty(where) ? " AND (" + where + ')' : ""), whereArgs); break; default: throw new IllegalArgumentException("Unknown URI " + uri); } getContext().getContentResolver().notifyChange(uri, null); return count; } @Override public int update(Uri uri, ContentValues values, String where, String[] whereArgs) { SQLiteDatabase db = getDbHelper().getWritableDatabase(); int count = 0; switch (sUriMatcher.match(uri)) { case FORMS: // don't let users manually update md5 if (values.containsKey(FormsColumns.MD5_HASH)) { values.remove(FormsColumns.MD5_HASH); } // if values contains path, then all filepaths and md5s will get // updated // this probably isn't a great thing to do. if (values.containsKey(FormsColumns.FORM_FILE_PATH)) { String formFile = values .getAsString(FormsColumns.FORM_FILE_PATH); values.put(FormsColumns.MD5_HASH, FileUtils.getMd5Hash(new File(formFile))); } Cursor c = null; try { c = this.query(uri, null, where, whereArgs, null); if (c.getCount() > 0) { c.moveToPosition(-1); while (c.moveToNext()) { // before updating the paths, delete all the files if (values.containsKey(FormsColumns.FORM_FILE_PATH)) { String newFile = values .getAsString(FormsColumns.FORM_FILE_PATH); String delFile = c .getString(c .getColumnIndex(FormsColumns.FORM_FILE_PATH)); if (newFile.equalsIgnoreCase(delFile)) { // same file, so don't delete anything } else { // different files, delete the old one deleteFileOrDir(delFile); } // either way, delete the old cache because we'll // calculate a new one. deleteFileOrDir(c .getString(c .getColumnIndex(FormsColumns.JRCACHE_FILE_PATH))); } } } } finally { if (c != null) { c.close(); } } // Make sure that the necessary fields are all set if (values.containsKey(FormsColumns.DATE) == true) { Date today = new Date(); String ts = new SimpleDateFormat(getContext().getString( R.string.added_on_date_at_time), Locale.getDefault()) .format(today); values.put(FormsColumns.DISPLAY_SUBTEXT, ts); } count = db.update(FORMS_TABLE_NAME, values, where, whereArgs); break; case FORM_ID: String formId = uri.getPathSegments().get(1); // Whenever file paths are updated, delete the old files. Cursor update = null; try { update = this.query(uri, null, where, whereArgs, null); // This should only ever return 1 record. if (update.getCount() > 0) { update.moveToFirst(); // don't let users manually update md5 if (values.containsKey(FormsColumns.MD5_HASH)) { values.remove(FormsColumns.MD5_HASH); } // the order here is important (jrcache needs to be before // form file) // because we update the jrcache file if there's a new form // file if (values.containsKey(FormsColumns.JRCACHE_FILE_PATH)) { deleteFileOrDir(update .getString(update .getColumnIndex(FormsColumns.JRCACHE_FILE_PATH))); } if (values.containsKey(FormsColumns.FORM_FILE_PATH)) { String formFile = values .getAsString(FormsColumns.FORM_FILE_PATH); String oldFile = update.getString(update .getColumnIndex(FormsColumns.FORM_FILE_PATH)); if (formFile != null && formFile.equalsIgnoreCase(oldFile)) { // Files are the same, so we may have just copied // over something we had // already } else { // New file name. This probably won't ever happen, // though. deleteFileOrDir(oldFile); } // we're updating our file, so update the md5 // and get rid of the cache (doesn't harm anything) deleteFileOrDir(update .getString(update .getColumnIndex(FormsColumns.JRCACHE_FILE_PATH))); String newMd5 = FileUtils .getMd5Hash(new File(formFile)); values.put(FormsColumns.MD5_HASH, newMd5); values.put(FormsColumns.JRCACHE_FILE_PATH, Collect.CACHE_PATH + File.separator + newMd5 + ".formdef"); } // Make sure that the necessary fields are all set if (values.containsKey(FormsColumns.DATE) == true) { Date today = new Date(); String ts = new SimpleDateFormat(getContext() .getString(R.string.added_on_date_at_time), Locale.getDefault()).format(today); values.put(FormsColumns.DISPLAY_SUBTEXT, ts); } count = db.update( FORMS_TABLE_NAME, values, FormsColumns._ID + "=" + formId + (!TextUtils.isEmpty(where) ? " AND (" + where + ')' : ""), whereArgs); } else { Log.e(t, "Attempting to update row that does not exist"); } } finally { if (update != null) { update.close(); } } break; default: throw new IllegalArgumentException("Unknown URI " + uri); } getContext().getContentResolver().notifyChange(uri, null); return count; } static { sUriMatcher = new UriMatcher(UriMatcher.NO_MATCH); sUriMatcher.addURI(FormsProviderAPI.AUTHORITY, "forms", FORMS); sUriMatcher.addURI(FormsProviderAPI.AUTHORITY, "forms/#", FORM_ID); sFormsProjectionMap = new HashMap<String, String>(); sFormsProjectionMap.put(FormsColumns._ID, FormsColumns._ID); sFormsProjectionMap.put(FormsColumns.DISPLAY_NAME, FormsColumns.DISPLAY_NAME); sFormsProjectionMap.put(FormsColumns.DISPLAY_SUBTEXT, FormsColumns.DISPLAY_SUBTEXT); sFormsProjectionMap.put(FormsColumns.DESCRIPTION, FormsColumns.DESCRIPTION); sFormsProjectionMap.put(FormsColumns.JR_FORM_ID, FormsColumns.JR_FORM_ID); sFormsProjectionMap.put(FormsColumns.JR_VERSION, FormsColumns.JR_VERSION); sFormsProjectionMap.put(FormsColumns.SUBMISSION_URI, FormsColumns.SUBMISSION_URI); sFormsProjectionMap.put(FormsColumns.BASE64_RSA_PUBLIC_KEY, FormsColumns.BASE64_RSA_PUBLIC_KEY); sFormsProjectionMap.put(FormsColumns.MD5_HASH, FormsColumns.MD5_HASH); sFormsProjectionMap.put(FormsColumns.DATE, FormsColumns.DATE); sFormsProjectionMap.put(FormsColumns.FORM_MEDIA_PATH, FormsColumns.FORM_MEDIA_PATH); sFormsProjectionMap.put(FormsColumns.FORM_FILE_PATH, FormsColumns.FORM_FILE_PATH); sFormsProjectionMap.put(FormsColumns.JRCACHE_FILE_PATH, FormsColumns.JRCACHE_FILE_PATH); sFormsProjectionMap.put(FormsColumns.LANGUAGE, FormsColumns.LANGUAGE); } }
Java
/* * Copyright (C) 2011 University of Washington * * 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 org.odk.collect.android.views; import java.io.Serializable; import java.util.*; import android.app.Activity; import android.content.ActivityNotFoundException; import android.content.Intent; import android.os.Bundle; import android.widget.*; import org.javarosa.core.model.Constants; import org.javarosa.core.model.FormIndex; import org.javarosa.core.model.IFormElement; import org.javarosa.core.model.QuestionDef; import org.javarosa.core.model.data.IAnswerData; import org.javarosa.core.model.instance.TreeReference; import org.javarosa.form.api.FormEntryCaption; import org.javarosa.form.api.FormEntryPrompt; import org.odk.collect.android.R; import org.odk.collect.android.activities.FormEntryActivity; import org.odk.collect.android.application.Collect; import org.odk.collect.android.exception.ExternalParamsException; import org.odk.collect.android.exception.JavaRosaException; import org.odk.collect.android.external.ExternalAppsUtils; import org.odk.collect.android.logic.FormController; import org.odk.collect.android.widgets.IBinaryWidget; import org.odk.collect.android.widgets.QuestionWidget; import org.odk.collect.android.widgets.WidgetFactory; import android.content.Context; import android.os.Handler; import android.util.Log; import android.util.TypedValue; import android.view.Gravity; import android.view.MotionEvent; import android.view.View; import android.view.View.OnLongClickListener; /** * This class is * * @author carlhartung */ public class ODKView extends ScrollView implements OnLongClickListener { // starter random number for view IDs private final static int VIEW_ID = 12345; private final static String t = "ODKView"; private LinearLayout mView; private LinearLayout.LayoutParams mLayout; private ArrayList<QuestionWidget> widgets; private Handler h = null; public final static String FIELD_LIST = "field-list"; public ODKView(Context context, final FormEntryPrompt[] questionPrompts, FormEntryCaption[] groups, boolean advancingPage) { super(context); widgets = new ArrayList<QuestionWidget>(); mView = new LinearLayout(getContext()); mView.setOrientation(LinearLayout.VERTICAL); mView.setGravity(Gravity.TOP); mView.setPadding(0, 7, 0, 0); mLayout = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT); mLayout.setMargins(10, 0, 10, 0); // display which group you are in as well as the question addGroupText(groups); // when the grouped fields are populated by an external app, this will get true. boolean readOnlyOverride = false; // get the group we are showing -- it will be the last of the groups in the groups list if (groups != null && groups.length > 0) { final FormEntryCaption c = groups[groups.length - 1]; final String intentString = c.getFormElement().getAdditionalAttribute(null, "intent"); if (intentString != null && intentString.length() != 0) { readOnlyOverride = true; final String buttonText; final String errorString; String v = c.getSpecialFormQuestionText("buttonText"); buttonText = (v != null) ? v : context.getString(R.string.launch_app); v = c.getSpecialFormQuestionText("noAppErrorString"); errorString = (v != null) ? v : context.getString(R.string.no_app); TableLayout.LayoutParams params = new TableLayout.LayoutParams(); params.setMargins(7, 5, 7, 5); // set button formatting Button mLaunchIntentButton = new Button(getContext()); mLaunchIntentButton.setId(QuestionWidget.newUniqueId()); mLaunchIntentButton.setText(buttonText); mLaunchIntentButton.setTextSize(TypedValue.COMPLEX_UNIT_DIP, Collect.getQuestionFontsize() + 2); mLaunchIntentButton.setPadding(20, 20, 20, 20); mLaunchIntentButton.setLayoutParams(params); mLaunchIntentButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String intentName = ExternalAppsUtils.extractIntentName(intentString); Map<String, String> parameters = ExternalAppsUtils.extractParameters(intentString); Intent i = new Intent(intentName); try { ExternalAppsUtils.populateParameters(i, parameters, c.getIndex().getReference()); for (FormEntryPrompt p : questionPrompts) { IFormElement formElement = p.getFormElement(); if (formElement instanceof QuestionDef) { TreeReference reference = (TreeReference) formElement.getBind().getReference(); IAnswerData answerValue = p.getAnswerValue(); Object value = answerValue == null ? null : answerValue.getValue(); switch (p.getDataType()) { case Constants.DATATYPE_TEXT: case Constants.DATATYPE_INTEGER: case Constants.DATATYPE_DECIMAL: i.putExtra(reference.getNameLast(), (Serializable) value); break; } } } ((Activity) getContext()).startActivityForResult(i, FormEntryActivity.EX_GROUP_CAPTURE); } catch (ExternalParamsException e) { Log.e("ExternalParamsException", e.getMessage(), e); Toast.makeText(getContext(), e.getMessage(), Toast.LENGTH_SHORT) .show(); } catch (ActivityNotFoundException e) { Log.e("ActivityNotFoundException", e.getMessage(), e); Toast.makeText(getContext(), errorString, Toast.LENGTH_SHORT) .show(); } } }); View divider = new View(getContext()); divider.setBackgroundResource(android.R.drawable.divider_horizontal_bright); divider.setMinimumHeight(3); mView.addView(divider); mView.addView(mLaunchIntentButton, mLayout); } } boolean first = true; int id = 0; for (FormEntryPrompt p : questionPrompts) { if (!first) { View divider = new View(getContext()); divider.setBackgroundResource(android.R.drawable.divider_horizontal_bright); divider.setMinimumHeight(3); mView.addView(divider); } else { first = false; } // if question or answer type is not supported, use text widget QuestionWidget qw = WidgetFactory.createWidgetFromPrompt(p, getContext(), readOnlyOverride); qw.setLongClickable(true); qw.setOnLongClickListener(this); qw.setId(VIEW_ID + id++); widgets.add(qw); mView.addView(qw, mLayout); } addView(mView); // see if there is an autoplay option. // Only execute it during forward swipes through the form if ( advancingPage && widgets.size() == 1 ) { final String playOption = widgets.get(0).getPrompt().getFormElement().getAdditionalAttribute(null, "autoplay"); if ( playOption != null ) { h = new Handler(); h.postDelayed(new Runnable() { @Override public void run() { if ( playOption.equalsIgnoreCase("audio") ) { widgets.get(0).playAudio(); } else if ( playOption.equalsIgnoreCase("video") ) { widgets.get(0).playVideo(); } } }, 150); } } } /** * http://code.google.com/p/android/issues/detail?id=8488 */ public void recycleDrawables() { this.destroyDrawingCache(); mView.destroyDrawingCache(); for ( QuestionWidget q : widgets ) { q.recycleDrawables(); } } protected void onScrollChanged(int l, int t, int oldl, int oldt) { Collect.getInstance().getActivityLogger().logScrollAction(this, t - oldt); } /** * @return a HashMap of answers entered by the user for this set of widgets */ public LinkedHashMap<FormIndex, IAnswerData> getAnswers() { LinkedHashMap<FormIndex, IAnswerData> answers = new LinkedHashMap<FormIndex, IAnswerData>(); Iterator<QuestionWidget> i = widgets.iterator(); while (i.hasNext()) { /* * The FormEntryPrompt has the FormIndex, which is where the answer gets stored. The * QuestionWidget has the answer the user has entered. */ QuestionWidget q = i.next(); FormEntryPrompt p = q.getPrompt(); answers.put(p.getIndex(), q.getAnswer()); } return answers; } /** * // * Add a TextView containing the hierarchy of groups to which the question belongs. // */ private void addGroupText(FormEntryCaption[] groups) { StringBuilder s = new StringBuilder(""); String t = ""; int i; // list all groups in one string for (FormEntryCaption g : groups) { i = g.getMultiplicity() + 1; t = g.getLongText(); if (t != null) { s.append(t); if (g.repeats() && i > 0) { s.append(" (" + i + ")"); } s.append(" > "); } } // build view if (s.length() > 0) { TextView tv = new TextView(getContext()); tv.setText(s.substring(0, s.length() - 3)); int questionFontsize = Collect.getQuestionFontsize(); tv.setTextSize(TypedValue.COMPLEX_UNIT_DIP, questionFontsize - 4); tv.setPadding(0, 0, 0, 5); mView.addView(tv, mLayout); } } public void setFocus(Context context) { if (widgets.size() > 0) { widgets.get(0).setFocus(context); } } /** * Called when another activity returns information to answer this question. * * @param answer */ public void setBinaryData(Object answer) { boolean set = false; for (QuestionWidget q : widgets) { if (q instanceof IBinaryWidget) { if (((IBinaryWidget) q).isWaitingForBinaryData()) { try { ((IBinaryWidget) q).setBinaryData(answer); } catch (Exception e) { Log.e(t, e.getMessage(), e); Toast.makeText(getContext(), getContext().getString(R.string.error_attaching_binary_file, e.getMessage()), Toast.LENGTH_LONG).show(); } set = true; break; } } } if (!set) { Log.w(t, "Attempting to return data to a widget or set of widgets not looking for data"); } } public void setDataForFields(Bundle bundle) throws JavaRosaException { if (bundle == null) { return; } FormController formController = Collect.getInstance().getFormController(); Set<String> keys = bundle.keySet(); for (String key : keys) { for (QuestionWidget questionWidget : widgets) { FormEntryPrompt prompt = questionWidget.getPrompt(); TreeReference treeReference = (TreeReference) prompt.getFormElement().getBind().getReference(); if (treeReference.getNameLast().equals(key)) { switch (prompt.getDataType()) { case Constants.DATATYPE_TEXT: formController.saveAnswer(prompt.getIndex(), ExternalAppsUtils.asStringData(bundle.get(key))); break; case Constants.DATATYPE_INTEGER: formController.saveAnswer(prompt.getIndex(), ExternalAppsUtils.asIntegerData(bundle.get(key))); break; case Constants.DATATYPE_DECIMAL: formController.saveAnswer(prompt.getIndex(), ExternalAppsUtils.asDecimalData(bundle.get(key))); break; default: throw new RuntimeException(getContext().getString(R.string.ext_assign_value_error, treeReference.toString(false))); } break; } } } } public void cancelWaitingForBinaryData() { int count = 0; for (QuestionWidget q : widgets) { if (q instanceof IBinaryWidget) { if (((IBinaryWidget) q).isWaitingForBinaryData()) { ((IBinaryWidget) q).cancelWaitingForBinaryData(); ++count; } } } if (count != 1) { Log.w(t, "Attempting to cancel waiting for binary data to a widget or set of widgets not looking for data"); } } public boolean suppressFlingGesture(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { for (QuestionWidget q : widgets) { if ( q.suppressFlingGesture(e1, e2, velocityX, velocityY) ) { return true; } } return false; } /** * @return true if the answer was cleared, false otherwise. */ public boolean clearAnswer() { // If there's only one widget, clear the answer. // If there are more, then force a long-press to clear the answer. if (widgets.size() == 1 && !widgets.get(0).getPrompt().isReadOnly()) { widgets.get(0).clearAnswer(); return true; } else { return false; } } public ArrayList<QuestionWidget> getWidgets() { return widgets; } @Override public void setOnFocusChangeListener(OnFocusChangeListener l) { for (int i = 0; i < widgets.size(); i++) { QuestionWidget qw = widgets.get(i); qw.setOnFocusChangeListener(l); } } @Override public boolean onLongClick(View v) { return false; } @Override public void cancelLongPress() { super.cancelLongPress(); for (QuestionWidget qw : widgets) { qw.cancelLongPress(); } } }
Java
/* * Copyright (C) 2011 University of Washington * * 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 org.odk.collect.android.views; import java.io.File; import java.io.IOException; import org.javarosa.core.model.FormIndex; import org.javarosa.core.reference.InvalidReferenceException; import org.javarosa.core.reference.ReferenceManager; import org.odk.collect.android.R; import org.odk.collect.android.application.Collect; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.media.MediaPlayer; import android.media.MediaPlayer.OnCompletionListener; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.ImageButton; import android.widget.Toast; /** * @author ctsims * @author carlhartung */ public class AudioButton extends ImageButton implements OnClickListener { private final static String t = "AudioButton"; /** * Useful class for handling the playing and stopping of audio prompts. * This is used here, and also in the GridMultiWidget and GridWidget * to play prompts as items are selected. * * @author mitchellsundt@gmail.com * */ public static class AudioHandler { private FormIndex index; private String selectionDesignator; private String URI; private MediaPlayer player; public AudioHandler(FormIndex index, String selectionDesignator, String URI) { this.index = index; this.selectionDesignator = selectionDesignator; this.URI = URI; player = null; } public void playAudio(Context c) { Collect.getInstance().getActivityLogger().logInstanceAction(this, "onClick.playAudioPrompt", selectionDesignator, index); if (URI == null) { // No audio file specified Log.e(t, "No audio file was specified"); Toast.makeText(c, c.getString(R.string.audio_file_error), Toast.LENGTH_LONG).show(); return; } String audioFilename = ""; try { audioFilename = ReferenceManager._().DeriveReference(URI).getLocalURI(); } catch (InvalidReferenceException e) { Log.e(t, "Invalid reference exception"); e.printStackTrace(); } File audioFile = new File(audioFilename); if (!audioFile.exists()) { // We should have an audio clip, but the file doesn't exist. String errorMsg = c.getString(R.string.file_missing, audioFile); Log.e(t, errorMsg); Toast.makeText(c, errorMsg, Toast.LENGTH_LONG).show(); return; } // In case we're currently playing sounds. stopPlaying(); player = new MediaPlayer(); try { player.setDataSource(audioFilename); player.prepare(); player.start(); player.setOnCompletionListener(new OnCompletionListener() { @Override public void onCompletion(MediaPlayer mediaPlayer) { mediaPlayer.release(); } }); } catch (IOException e) { String errorMsg = c.getString(R.string.audio_file_invalid); Log.e(t, errorMsg); Toast.makeText(c, errorMsg, Toast.LENGTH_LONG).show(); e.printStackTrace(); } } public void stopPlaying() { if (player != null) { player.release(); } } } AudioHandler handler; public AudioButton(Context context, FormIndex index, String selectionDesignator, String URI) { super(context); this.setOnClickListener(this); handler = new AudioHandler( index, selectionDesignator, URI); Bitmap b = BitmapFactory.decodeResource(context.getResources(), android.R.drawable.ic_lock_silent_mode_off); this.setImageBitmap(b); } public void playAudio() { handler.playAudio(getContext()); } @Override public void onClick(View v) { playAudio(); } public void stopPlaying() { handler.stopPlaying(); } }
Java
/* * Copyright (C) 2011 University of Washington * * 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 org.odk.collect.android.views; import java.io.File; import android.widget.*; import org.javarosa.core.model.FormIndex; import org.javarosa.core.reference.InvalidReferenceException; import org.javarosa.core.reference.ReferenceManager; import org.odk.collect.android.R; import org.odk.collect.android.application.Collect; import org.odk.collect.android.utilities.FileUtils; import org.odk.collect.android.widgets.QuestionWidget; import android.app.Activity; import android.content.ActivityNotFoundException; import android.content.Context; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Color; import android.net.Uri; import android.util.Log; import android.view.Display; import android.view.View; import android.view.WindowManager; import android.widget.ImageView.ScaleType; /** * This layout is used anywhere we can have image/audio/video/text. TODO: It would probably be nice * to put this in a layout.xml file of some sort at some point. * * @author carlhartung */ public class MediaLayout extends RelativeLayout { private static final String t = "AVTLayout"; private String mSelectionDesignator; private FormIndex mIndex; private TextView mView_Text; private AudioButton mAudioButton; private ImageButton mVideoButton; private ImageView mImageView; private TextView mMissingImage; private String mVideoURI = null; public MediaLayout(Context c) { super(c); mView_Text = null; mAudioButton = null; mImageView = null; mMissingImage = null; mVideoButton = null; mIndex = null; } public void playAudio() { if ( mAudioButton != null ) { mAudioButton.playAudio(); } } public void playVideo() { if ( mVideoURI != null ) { String videoFilename = ""; try { videoFilename = ReferenceManager._().DeriveReference(mVideoURI).getLocalURI(); } catch (InvalidReferenceException e) { Log.e(t, "Invalid reference exception"); e.printStackTrace(); } File videoFile = new File(videoFilename); if (!videoFile.exists()) { // We should have a video clip, but the file doesn't exist. String errorMsg = getContext().getString(R.string.file_missing, videoFilename); Log.e(t, errorMsg); Toast.makeText(getContext(), errorMsg, Toast.LENGTH_LONG).show(); return; } Intent i = new Intent("android.intent.action.VIEW"); i.setDataAndType(Uri.fromFile(videoFile), "video/*"); try { ((Activity) getContext()).startActivity(i); } catch (ActivityNotFoundException e) { Toast.makeText(getContext(), getContext().getString(R.string.activity_not_found, "view video"), Toast.LENGTH_SHORT).show(); } } } public void setAVT(FormIndex index, String selectionDesignator, TextView text, String audioURI, String imageURI, String videoURI, final String bigImageURI) { mSelectionDesignator = selectionDesignator; mIndex = index; mView_Text = text; mView_Text.setId(QuestionWidget.newUniqueId()); mVideoURI = videoURI; // Layout configurations for our elements in the relative layout RelativeLayout.LayoutParams textParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); RelativeLayout.LayoutParams audioParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); RelativeLayout.LayoutParams imageParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); RelativeLayout.LayoutParams videoParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); // First set up the audio button if (audioURI != null) { // An audio file is specified mAudioButton = new AudioButton(getContext(), mIndex, mSelectionDesignator, audioURI); mAudioButton.setId(QuestionWidget.newUniqueId()); // random ID to be used by the // relative layout. } else { // No audio file specified, so ignore. } // Then set up the video button if (videoURI != null) { // An video file is specified mVideoButton = new ImageButton(getContext()); Bitmap b = BitmapFactory.decodeResource(getContext().getResources(), android.R.drawable.ic_media_play); mVideoButton.setImageBitmap(b); mVideoButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Collect.getInstance().getActivityLogger().logInstanceAction(this, "onClick", "playVideoPrompt"+mSelectionDesignator, mIndex); MediaLayout.this.playVideo(); } }); mVideoButton.setId(QuestionWidget.newUniqueId()); } else { // No video file specified, so ignore. } // Now set up the image view String errorMsg = null; final int imageId = QuestionWidget.newUniqueId(); if (imageURI != null) { try { String imageFilename = ReferenceManager._().DeriveReference(imageURI).getLocalURI(); final File imageFile = new File(imageFilename); if (imageFile.exists()) { Display display = ((WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE)) .getDefaultDisplay(); int screenWidth = display.getWidth(); int screenHeight = display.getHeight(); Bitmap b = FileUtils.getBitmapScaledToDisplay(imageFile, screenHeight, screenWidth); if (b != null) { mImageView = new ImageView(getContext()); mImageView.setPadding(2, 2, 2, 2); mImageView.setBackgroundColor(Color.WHITE); mImageView.setImageBitmap(b); mImageView.setId(imageId); if (bigImageURI != null) { mImageView.setOnClickListener(new OnClickListener() { String bigImageFilename = ReferenceManager._() .DeriveReference(bigImageURI).getLocalURI(); File bigImage = new File(bigImageFilename); @Override public void onClick(View v) { Collect.getInstance().getActivityLogger().logInstanceAction(this, "onClick", "showImagePromptBigImage"+mSelectionDesignator, mIndex); Intent i = new Intent("android.intent.action.VIEW"); i.setDataAndType(Uri.fromFile(bigImage), "image/*"); try { getContext().startActivity(i); } catch (ActivityNotFoundException e) { Toast.makeText( getContext(), getContext().getString(R.string.activity_not_found, "view image"), Toast.LENGTH_SHORT).show(); } } }); } } else { // Loading the image failed, so it's likely a bad file. errorMsg = getContext().getString(R.string.file_invalid, imageFile); } } else { // We should have an image, but the file doesn't exist. errorMsg = getContext().getString(R.string.file_missing, imageFile); } if (errorMsg != null) { // errorMsg is only set when an error has occurred Log.e(t, errorMsg); mMissingImage = new TextView(getContext()); mMissingImage.setText(errorMsg); mMissingImage.setPadding(10, 10, 10, 10); mMissingImage.setId(imageId); } } catch (InvalidReferenceException e) { Log.e(t, "image invalid reference exception"); e.printStackTrace(); } } else { // There's no imageURI listed, so just ignore it. } // e.g., for TextView that flag will be true boolean isNotAMultipleChoiceField = !RadioButton.class.isAssignableFrom(text.getClass()) && !CheckBox.class.isAssignableFrom(text.getClass()); // Determine the layout constraints... // Assumes LTR, TTB reading bias! if (mView_Text.getText().length() == 0 && (mImageView != null || mMissingImage != null)) { // No text; has image. The image is treated as question/choice icon. // The Text view may just have a radio button or checkbox. It // needs to remain in the layout even though it is blank. // // The image view, as created above, will dynamically resize and // center itself. We want it to resize but left-align itself // in the resized area and we want a white background, as otherwise // it will show a grey bar to the right of the image icon. if (mImageView != null) { mImageView.setScaleType(ScaleType.FIT_START); } // // In this case, we have: // Text upper left; image upper, left edge aligned with text right edge; // audio upper right; video below audio on right. textParams.addRule(RelativeLayout.ALIGN_PARENT_TOP); textParams.addRule(RelativeLayout.ALIGN_PARENT_LEFT); if (isNotAMultipleChoiceField) { imageParams.addRule(RelativeLayout.CENTER_HORIZONTAL); } else { imageParams.addRule(RelativeLayout.RIGHT_OF, mView_Text.getId()); } imageParams.addRule(RelativeLayout.ALIGN_PARENT_TOP); if (mAudioButton != null && mVideoButton == null) { audioParams.addRule(RelativeLayout.ALIGN_PARENT_TOP); audioParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT); imageParams.addRule(RelativeLayout.LEFT_OF, mAudioButton.getId()); } else if (mAudioButton == null && mVideoButton != null) { videoParams.addRule(RelativeLayout.ALIGN_PARENT_TOP); videoParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT); imageParams.addRule(RelativeLayout.LEFT_OF, mVideoButton.getId()); } else if (mAudioButton != null && mVideoButton != null) { audioParams.addRule(RelativeLayout.ALIGN_PARENT_TOP); audioParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT); imageParams.addRule(RelativeLayout.LEFT_OF, mAudioButton.getId()); videoParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT); videoParams.addRule(RelativeLayout.BELOW, mAudioButton.getId()); imageParams.addRule(RelativeLayout.LEFT_OF, mVideoButton.getId()); } else { // the image will implicitly scale down to fit within parent... // no need to bound it by the width of the parent... if (!isNotAMultipleChoiceField) { imageParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT); } } imageParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM); } else { // We have a non-blank text label -- image is below the text. // In this case, we want the image to be centered... if (mImageView != null) { mImageView.setScaleType(ScaleType.FIT_START); } // // Text upper left; audio upper right; video below audio on right. // image below text, audio and video buttons; left-aligned with text. textParams.addRule(RelativeLayout.ALIGN_PARENT_LEFT); textParams.addRule(RelativeLayout.ALIGN_PARENT_TOP); if (mAudioButton != null && mVideoButton == null) { audioParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT); textParams.addRule(RelativeLayout.LEFT_OF, mAudioButton.getId()); } else if (mAudioButton == null && mVideoButton != null) { videoParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT); textParams.addRule(RelativeLayout.LEFT_OF, mVideoButton.getId()); } else if (mAudioButton != null && mVideoButton != null) { audioParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT); textParams.addRule(RelativeLayout.LEFT_OF, mAudioButton.getId()); videoParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT); videoParams.addRule(RelativeLayout.BELOW, mAudioButton.getId()); } else { textParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT); } if (mImageView != null || mMissingImage != null) { imageParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM); imageParams.addRule(RelativeLayout.CENTER_HORIZONTAL); imageParams.addRule(RelativeLayout.BELOW, mView_Text.getId()); } else { textParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM); } } addView(mView_Text, textParams); if (mAudioButton != null) addView(mAudioButton, audioParams); if (mVideoButton != null) addView(mVideoButton, videoParams); if (mImageView != null) addView(mImageView, imageParams); else if (mMissingImage != null) addView(mMissingImage, imageParams); } /** * This adds a divider at the bottom of this layout. Used to separate fields in lists. * * @param v */ public void addDivider(ImageView v) { RelativeLayout.LayoutParams dividerParams = new RelativeLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT); if (mImageView != null) { dividerParams.addRule(RelativeLayout.BELOW, mImageView.getId()); } else if (mMissingImage != null) { dividerParams.addRule(RelativeLayout.BELOW, mMissingImage.getId()); } else if (mVideoButton != null) { dividerParams.addRule(RelativeLayout.BELOW, mVideoButton.getId()); } else if (mAudioButton != null) { dividerParams.addRule(RelativeLayout.BELOW, mAudioButton.getId()); } else if (mView_Text != null) { // No picture dividerParams.addRule(RelativeLayout.BELOW, mView_Text.getId()); } else { Log.e(t, "Tried to add divider to uninitialized ATVWidget"); return; } addView(v, dividerParams); } @Override protected void onWindowVisibilityChanged(int visibility) { super.onWindowVisibilityChanged(visibility); if (visibility != View.VISIBLE) { if (mAudioButton != null) { mAudioButton.stopPlaying(); } } } }
Java
package org.odk.collect.android.views; import android.content.Context; import android.content.DialogInterface; import android.os.Bundle; import android.preference.ListPreference; import android.util.AttributeSet; public class DynamicListPreference extends ListPreference { // control whether dialog should show or not private boolean showDialog = false; public DynamicListPreference(Context context, AttributeSet attrs) { super(context, attrs); } public DynamicListPreference(Context context) { super(context); } public DynamicListPreference(Context context, boolean show) { super(context); showDialog = show; } // This is just to simulate that the user 'clicked' on the preference. public void show() { showDialog(null); } public boolean shouldShow() { return showDialog; } @Override protected void showDialog(Bundle state) { if (showDialog) { super.showDialog(state); } else { // we don't want the dialog to show sometimes // like immediately after click, so we don't until we've generated // the // list choices return; } } public void setShowDialog(boolean show) { showDialog = show; } @Override public void onClick(DialogInterface dialog, int which) { super.onClick(dialog, which); // causes list to refresh next time dialog is requested if (which == DialogInterface.BUTTON_NEGATIVE) { setShowDialog(false); } } }
Java
/* * Copyright (C) 2013 University of Washington * * http://creativecommons.org/licenses/by-sa/3.0/ -- code is based upon an answer on Stack Overflow: * http://stackoverflow.com/questions/8481844/gridview-height-gets-cut * * 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 org.odk.collect.android.views; import android.content.Context; import android.util.AttributeSet; import android.view.ViewGroup; import android.widget.GridView; /** * From Stack Overflow: http://stackoverflow.com/questions/8481844/gridview-height-gets-cut * Changed to always be expanded, since widgets are always embedded in a scroll view. * * @author tacone based on answer by Neil Traft * @author mitchellsundt@gmail.com * */ public class ExpandedHeightGridView extends GridView { public ExpandedHeightGridView(Context context) { super(context); } public ExpandedHeightGridView(Context context, AttributeSet attrs) { super(context, attrs); } public ExpandedHeightGridView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } @Override public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { // HACK! TAKE THAT ANDROID! // Calculate entire height by providing a very large height hint. // But do not use the highest 2 bits of this integer; those are // reserved for the MeasureSpec mode. int expandSpec = MeasureSpec.makeMeasureSpec( Integer.MAX_VALUE >> 2, MeasureSpec.AT_MOST); super.onMeasure(widthMeasureSpec, expandSpec); ViewGroup.LayoutParams params = getLayoutParams(); params.height = getMeasuredHeight(); } }
Java
/* * Copyright (C) 2009 University of Washington * * 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 org.odk.collect.android.views; import org.odk.collect.android.R; import android.content.Context; import android.util.AttributeSet; import android.widget.CheckBox; import android.widget.Checkable; import android.widget.RelativeLayout; public class TwoItemMultipleChoiceView extends RelativeLayout implements Checkable { public TwoItemMultipleChoiceView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } public TwoItemMultipleChoiceView(Context context, AttributeSet attrs) { super(context, attrs); } public TwoItemMultipleChoiceView(Context context) { super(context); } @Override public boolean isChecked() { CheckBox c = (CheckBox) findViewById(R.id.checkbox); return c.isChecked(); } @Override public void setChecked(boolean checked) { CheckBox c = (CheckBox) findViewById(R.id.checkbox); c.setChecked(checked); } @Override public void toggle() { CheckBox c = (CheckBox) findViewById(R.id.checkbox); c.setChecked(!c.isChecked()); } }
Java
/* * Copyright (C) 2009 University of Washington * * 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 org.odk.collect.android.views; import org.odk.collect.android.logic.HierarchyElement; import android.content.Context; import android.graphics.drawable.Drawable; import android.view.Gravity; import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.TextView; public class HierarchyElementView extends RelativeLayout { private TextView mPrimaryTextView; private TextView mSecondaryTextView; private ImageView mIcon; public HierarchyElementView(Context context, HierarchyElement it) { super(context); setColor(it.getColor()); mIcon = new ImageView(context); mIcon.setImageDrawable(it.getIcon()); mIcon.setId(1); mIcon.setPadding(0, 0, dipToPx(4), 0); addView(mIcon, new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); mPrimaryTextView = new TextView(context); mPrimaryTextView.setTextAppearance(context, android.R.style.TextAppearance_Large); mPrimaryTextView.setText(it.getPrimaryText()); mPrimaryTextView.setId(2); mPrimaryTextView.setGravity(Gravity.CENTER_VERTICAL); LayoutParams l = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); l.addRule(RelativeLayout.RIGHT_OF, mIcon.getId()); addView(mPrimaryTextView, l); mSecondaryTextView = new TextView(context); mSecondaryTextView.setText(it.getSecondaryText()); mSecondaryTextView.setTextAppearance(context, android.R.style.TextAppearance_Small); mSecondaryTextView.setGravity(Gravity.CENTER_VERTICAL); LayoutParams lp = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); lp.addRule(RelativeLayout.BELOW, mPrimaryTextView.getId()); lp.addRule(RelativeLayout.RIGHT_OF, mIcon.getId()); addView(mSecondaryTextView, lp); setPadding(dipToPx(8), dipToPx(4), dipToPx(8), dipToPx(8)); } public void setPrimaryText(String text) { mPrimaryTextView.setText(text); } public void setSecondaryText(String text) { mSecondaryTextView.setText(text); } public void setIcon(Drawable icon) { mIcon.setImageDrawable(icon); } public void setColor(int color) { setBackgroundColor(color); } public void showSecondary(boolean bool) { if (bool) { mSecondaryTextView.setVisibility(VISIBLE); setMinimumHeight(dipToPx(64)); } else { mSecondaryTextView.setVisibility(GONE); setMinimumHeight(dipToPx(32)); } } public int dipToPx(int dip) { return (int) (dip * getResources().getDisplayMetrics().density + 0.5f); } }
Java
/* * Copyright (C) 2009 University of Washington * * 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 org.odk.collect.android.views; import org.odk.collect.android.R; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.util.AttributeSet; import android.util.Log; import android.view.View; import android.view.animation.Animation; import android.view.animation.AnimationUtils; /** * Builds view for arrow animation * * @author Carl Hartung (carlhartung@gmail.com) */ public class ArrowAnimationView extends View { private final static String t = "ArrowAnimationView"; private Animation mAnimation; private Bitmap mArrow; private int mImgXOffset; public ArrowAnimationView(Context context, AttributeSet attrs) { super(context, attrs); Log.i(t, "called constructor"); init(); } public ArrowAnimationView(Context context) { super(context); init(); } private void init() { mArrow = BitmapFactory.decodeResource(getResources(), R.drawable.left_arrow); mImgXOffset = mArrow.getWidth() / 2; } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); if (mAnimation == null) { createAnim(canvas); } int centerX = canvas.getWidth() / 2; canvas.drawBitmap(mArrow, centerX - mImgXOffset, (float) mArrow.getHeight() / 4, null); } private void createAnim(Canvas canvas) { mAnimation = AnimationUtils.loadAnimation(getContext(), R.anim.start_arrow); startAnimation(mAnimation); } }
Java
/* * Copyright (C) 2014 University of Washington * * Originally developed by Dobility, Inc. (as part of SurveyCTO) * * 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 org.odk.collect.android.utilities; import android.util.Log; import org.apache.commons.io.IOUtils; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; /** * Author: Meletis Margaritis * Date: 2/12/14 * Time: 1:48 PM */ public final class ZipUtils { final static String t = "ZipUtils"; public static void unzip(File[] zipFiles) { for (File zipFile : zipFiles) { ZipInputStream zipInputStream = null; try { zipInputStream = new ZipInputStream(new FileInputStream(zipFile)); ZipEntry zipEntry; while ((zipEntry = zipInputStream.getNextEntry()) != null) { doExtractInTheSameFolder(zipFile, zipInputStream, zipEntry); } } catch (Exception e) { Log.e(t, e.getMessage(), e); } finally { IOUtils.closeQuietly(zipInputStream); } } } public static File extractFirstZipEntry(File zipFile, boolean deleteAfterUnzip) throws IOException { ZipInputStream zipInputStream = null; File targetFile = null; try { zipInputStream = new ZipInputStream(new FileInputStream(zipFile)); ZipEntry zipEntry = zipInputStream.getNextEntry(); if (zipEntry != null) { targetFile = doExtractInTheSameFolder(zipFile, zipInputStream, zipEntry); } } finally { IOUtils.closeQuietly(zipInputStream); } if (deleteAfterUnzip && targetFile != null && targetFile.exists()) { FileUtils.deleteAndReport(zipFile); } return targetFile; } private static File doExtractInTheSameFolder(File zipFile, ZipInputStream zipInputStream, ZipEntry zipEntry) throws IOException { File targetFile; String fileName = zipEntry.getName(); Log.w(t, "Found zipEntry with name: " + fileName); if (fileName.contains("/") || fileName.contains("\\")) { // that means that this is a directory of a file inside a directory, so ignore it Log.w(t, "Ignored: " + fileName); return null; } // extract the new file targetFile = new File(zipFile.getParentFile(), fileName); FileOutputStream fileOutputStream = null; try { fileOutputStream = new FileOutputStream(targetFile); IOUtils.copy(zipInputStream, fileOutputStream); } finally { IOUtils.closeQuietly(fileOutputStream); } Log.w(t, "Extracted file \"" + fileName + "\" out of " + zipFile.getName()); return targetFile; } }
Java
/* * Copyright (C) 2012 University of Washington * * 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 org.odk.collect.android.utilities; import org.odk.collect.android.R; import android.content.Context; import android.database.Cursor; import android.view.View; import android.widget.SimpleCursorAdapter; import android.widget.TextView; /** * Implementation of cursor adapter that displays the version of a form if a form has a version. * * @author mitchellsundt@gmail.com * */ public class VersionHidingCursorAdapter extends SimpleCursorAdapter { private final Context ctxt; private final String versionColumnName; private final ViewBinder originalBinder; public VersionHidingCursorAdapter(String versionColumnName, Context context, int layout, Cursor c, String[] from, int[] to) { super(context, layout, c, from, to); this.versionColumnName = versionColumnName; ctxt = context; originalBinder = getViewBinder(); setViewBinder( new ViewBinder(){ @Override public boolean setViewValue(View view, Cursor cursor, int columnIndex) { String columnName = cursor.getColumnName(columnIndex); if ( !columnName.equals(VersionHidingCursorAdapter.this.versionColumnName) ) { if ( originalBinder != null ) { return originalBinder.setViewValue(view, cursor, columnIndex); } return false; } else { String version = cursor.getString(columnIndex); TextView v = (TextView) view; if ( version != null ) { v.setText(ctxt.getString(R.string.version) + " " + version); v.setVisibility(View.VISIBLE); } else { v.setText(null); v.setVisibility(View.GONE); } } return true; }} ); } }
Java
/* * Copyright (C) 2009 University of Washington * * 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 org.odk.collect.android.utilities; import org.apache.commons.io.IOUtils; import org.javarosa.xform.parse.XFormParser; import org.kxml2.kdom.Document; import org.kxml2.kdom.Element; import org.kxml2.kdom.Node; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.util.Log; import org.odk.collect.android.R; import org.odk.collect.android.application.Collect; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.math.BigInteger; import java.nio.channels.FileChannel; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.HashMap; /** * Static methods used for common file operations. * * @author Carl Hartung (carlhartung@gmail.com) */ public class FileUtils { private final static String t = "FileUtils"; // Used to validate and display valid form names. public static final String VALID_FILENAME = "[ _\\-A-Za-z0-9]*.x[ht]*ml"; public static final String FORMID = "formid"; public static final String VERSION = "version"; // arbitrary string in OpenRosa 1.0 public static final String TITLE = "title"; public static final String SUBMISSIONURI = "submission"; public static final String BASE64_RSA_PUBLIC_KEY = "base64RsaPublicKey"; public static boolean createFolder(String path) { boolean made = true; File dir = new File(path); if (!dir.exists()) { made = dir.mkdirs(); } return made; } public static byte[] getFileAsBytes(File file) { byte[] bytes = null; InputStream is = null; try { is = new FileInputStream(file); // Get the size of the file long length = file.length(); if (length > Integer.MAX_VALUE) { Log.e(t, "File " + file.getName() + "is too large"); return null; } // Create the byte array to hold the data bytes = new byte[(int) length]; // Read in the bytes int offset = 0; int read = 0; try { while (offset < bytes.length && read >= 0) { read = is.read(bytes, offset, bytes.length - offset); offset += read; } } catch (IOException e) { Log.e(t, "Cannot read " + file.getName()); e.printStackTrace(); return null; } // Ensure all the bytes have been read in if (offset < bytes.length) { try { throw new IOException("Could not completely read file " + file.getName()); } catch (IOException e) { e.printStackTrace(); return null; } } return bytes; } catch (FileNotFoundException e) { Log.e(t, "Cannot find " + file.getName()); e.printStackTrace(); return null; } finally { // Close the input stream try { is.close(); } catch (IOException e) { Log.e(t, "Cannot close input stream for " + file.getName()); e.printStackTrace(); return null; } } } public static String getMd5Hash(File file) { try { // CTS (6/15/2010) : stream file through digest instead of handing it the byte[] MessageDigest md = MessageDigest.getInstance("MD5"); int chunkSize = 256; byte[] chunk = new byte[chunkSize]; // Get the size of the file long lLength = file.length(); if (lLength > Integer.MAX_VALUE) { Log.e(t, "File " + file.getName() + "is too large"); return null; } int length = (int) lLength; InputStream is = null; is = new FileInputStream(file); int l = 0; for (l = 0; l + chunkSize < length; l += chunkSize) { is.read(chunk, 0, chunkSize); md.update(chunk, 0, chunkSize); } int remaining = length - l; if (remaining > 0) { is.read(chunk, 0, remaining); md.update(chunk, 0, remaining); } byte[] messageDigest = md.digest(); BigInteger number = new BigInteger(1, messageDigest); String md5 = number.toString(16); while (md5.length() < 32) md5 = "0" + md5; is.close(); return md5; } catch (NoSuchAlgorithmException e) { Log.e("MD5", e.getMessage()); return null; } catch (FileNotFoundException e) { Log.e("No Cache File", e.getMessage()); return null; } catch (IOException e) { Log.e("Problem reading from file", e.getMessage()); return null; } } public static Bitmap getBitmapScaledToDisplay(File f, int screenHeight, int screenWidth) { // Determine image size of f BitmapFactory.Options o = new BitmapFactory.Options(); o.inJustDecodeBounds = true; BitmapFactory.decodeFile(f.getAbsolutePath(), o); int heightScale = o.outHeight / screenHeight; int widthScale = o.outWidth / screenWidth; // Powers of 2 work faster, sometimes, according to the doc. // We're just doing closest size that still fills the screen. int scale = Math.max(widthScale, heightScale); // get bitmap with scale ( < 1 is the same as 1) BitmapFactory.Options options = new BitmapFactory.Options(); options.inInputShareable = true; options.inPurgeable = true; options.inSampleSize = scale; Bitmap b = BitmapFactory.decodeFile(f.getAbsolutePath(), options); if (b != null) { Log.i(t, "Screen is " + screenHeight + "x" + screenWidth + ". Image has been scaled down by " + scale + " to " + b.getHeight() + "x" + b.getWidth()); } return b; } public static String copyFile(File sourceFile, File destFile) { if (sourceFile.exists()) { String errorMessage = actualCopy(sourceFile, destFile); if (errorMessage != null) { try { Thread.sleep(500); Log.e(t, "Retrying to copy the file after 500ms: " + sourceFile.getAbsolutePath()); errorMessage = actualCopy(sourceFile, destFile); } catch (InterruptedException e) { Log.e(t, e.getMessage(), e); } } return errorMessage; } else { String msg = "Source file does not exist: " + sourceFile.getAbsolutePath(); Log.e(t, msg); return msg; } } private static String actualCopy(File sourceFile, File destFile) { FileInputStream fileInputStream = null; FileOutputStream fileOutputStream = null; FileChannel src = null; FileChannel dst = null; try { fileInputStream = new FileInputStream(sourceFile); src = fileInputStream.getChannel(); fileOutputStream = new FileOutputStream(destFile); dst = fileOutputStream.getChannel(); dst.transferFrom(src, 0, src.size()); dst.force(true); return null; } catch (FileNotFoundException e) { Log.e(t, "FileNotFoundException while copying file", e); return e.getMessage(); } catch (IOException e) { Log.e(t, "IOException while copying file", e); return e.getMessage(); } catch (Exception e) { Log.e(t, "Exception while copying file", e); return e.getMessage(); } finally { IOUtils.closeQuietly(fileInputStream); IOUtils.closeQuietly(fileOutputStream); IOUtils.closeQuietly(src); IOUtils.closeQuietly(dst); } } public static HashMap<String, String> parseXML(File xmlFile) { HashMap<String, String> fields = new HashMap<String, String>(); InputStream is; try { is = new FileInputStream(xmlFile); } catch (FileNotFoundException e1) { throw new IllegalStateException(e1); } InputStreamReader isr; try { isr = new InputStreamReader(is, "UTF-8"); } catch (UnsupportedEncodingException uee) { Log.w(t, "UTF 8 encoding unavailable, trying default encoding"); isr = new InputStreamReader(is); } if (isr != null) { Document doc; try { doc = XFormParser.getXMLDocument(isr); } catch (IOException e) { e.printStackTrace(); throw new IllegalStateException("Unable to parse XML document", e); } finally { try { isr.close(); } catch (IOException e) { Log.w(t, xmlFile.getAbsolutePath() + " Error closing form reader"); e.printStackTrace(); } } String xforms = "http://www.w3.org/2002/xforms"; String html = doc.getRootElement().getNamespace(); Element head = doc.getRootElement().getElement(html, "head"); Element title = head.getElement(html, "title"); if (title != null) { fields.put(TITLE, XFormParser.getXMLText(title, true)); } Element model = getChildElement(head, "model"); Element cur = getChildElement(model,"instance"); int idx = cur.getChildCount(); int i; for (i = 0; i < idx; ++i) { if (cur.isText(i)) continue; if (cur.getType(i) == Node.ELEMENT) { break; } } if (i < idx) { cur = cur.getElement(i); // this is the first data element String id = cur.getAttributeValue(null, "id"); String xmlns = cur.getNamespace(); String version = cur.getAttributeValue(null, "version"); String uiVersion = cur.getAttributeValue(null, "uiVersion"); if ( uiVersion != null ) { // pre-OpenRosa 1.0 variant of spec Log.e(t, "Obsolete use of uiVersion -- IGNORED -- only using version: " + version); } fields.put(FORMID, (id == null) ? xmlns : id); fields.put(VERSION, (version == null) ? null : version); } else { throw new IllegalStateException(xmlFile.getAbsolutePath() + " could not be parsed"); } try { Element submission = model.getElement(xforms, "submission"); String submissionUri = submission.getAttributeValue(null, "action"); fields.put(SUBMISSIONURI, (submissionUri == null) ? null : submissionUri); String base64RsaPublicKey = submission.getAttributeValue(null, "base64RsaPublicKey"); fields.put(BASE64_RSA_PUBLIC_KEY, (base64RsaPublicKey == null || base64RsaPublicKey.trim().length() == 0) ? null : base64RsaPublicKey.trim()); } catch (Exception e) { Log.i(t, xmlFile.getAbsolutePath() + " does not have a submission element"); // and that's totally fine. } } return fields; } // needed because element.getelement fails when there are attributes private static Element getChildElement(Element parent, String childName) { Element e = null; int c = parent.getChildCount(); int i = 0; for (i = 0; i < c; i++) { if (parent.getType(i) == Node.ELEMENT) { if (parent.getElement(i).getName().equalsIgnoreCase(childName)) { return parent.getElement(i); } } } return e; } public static void deleteAndReport(File file) { if (file != null && file.exists()) { // remove garbage if (!file.delete()) { Log.w(t, file.getAbsolutePath() + " will be deleted upon exit."); file.deleteOnExit(); } else { Log.w(t, file.getAbsolutePath() + " has been deleted."); } } } public static String constructMediaPath(String formFilePath) { String pathNoExtension = formFilePath.substring(0, formFilePath.lastIndexOf(".")); return pathNoExtension + "-media"; } /** * @param mediaDir the media folder */ public static void checkMediaPath(File mediaDir) { if (mediaDir.exists() && mediaDir.isFile()) { Log.e(t, "The media folder is already there and it is a FILE!! We will need to delete it and create a folder instead"); boolean deleted = mediaDir.delete(); if (!deleted) { throw new RuntimeException(Collect.getInstance().getString(R.string.fs_delete_media_path_if_file_error, mediaDir.getAbsolutePath())); } } // the directory case boolean createdOrExisted = createFolder(mediaDir.getAbsolutePath()); if (!createdOrExisted) { throw new RuntimeException(Collect.getInstance().getString(R.string.fs_create_media_folder_error, mediaDir.getAbsolutePath())); } } public static void purgeMediaPath(String mediaPath) { File tempMediaFolder = new File(mediaPath); File[] tempMediaFiles = tempMediaFolder.listFiles(); if (tempMediaFiles == null || tempMediaFiles.length == 0) { deleteAndReport(tempMediaFolder); } else { for (File tempMediaFile : tempMediaFiles) { deleteAndReport(tempMediaFile); } } } public static void moveMediaFiles(String tempMediaPath, File formMediaPath) throws IOException { File tempMediaFolder = new File(tempMediaPath); File[] mediaFiles = tempMediaFolder.listFiles(); if (mediaFiles == null || mediaFiles.length == 0) { deleteAndReport(tempMediaFolder); } else { for (File mediaFile : mediaFiles) { org.apache.commons.io.FileUtils.moveFileToDirectory(mediaFile, formMediaPath, true); } deleteAndReport(tempMediaFolder); } } }
Java
/* * Copyright (C) 2011 University of Washington * * 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 org.odk.collect.android.utilities; import java.io.*; import java.security.InvalidAlgorithmParameterException; import java.security.InvalidKeyException; import java.security.KeyFactory; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.security.NoSuchProviderException; import java.security.PublicKey; import java.security.SecureRandom; import java.security.spec.InvalidKeySpecException; import java.security.spec.X509EncodedKeySpec; import java.util.ArrayList; import java.util.List; import javax.crypto.BadPaddingException; import javax.crypto.Cipher; import javax.crypto.CipherOutputStream; import javax.crypto.IllegalBlockSizeException; import javax.crypto.NoSuchPaddingException; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; import org.apache.commons.io.IOUtils; import org.kxml2.io.KXmlSerializer; import org.kxml2.kdom.Document; import org.kxml2.kdom.Element; import org.kxml2.kdom.Node; import org.odk.collect.android.application.Collect; import org.odk.collect.android.exception.EncryptionException; import org.odk.collect.android.logic.FormController.InstanceMetadata; import org.odk.collect.android.provider.FormsProviderAPI.FormsColumns; import org.odk.collect.android.provider.InstanceProviderAPI.InstanceColumns; import android.content.ContentResolver; import android.database.Cursor; import android.net.Uri; import android.util.Log; /** * Utility class for encrypting submissions during the SaveToDiskTask. * * @author mitchellsundt@gmail.com * */ public class EncryptionUtils { private static final String t = "EncryptionUtils"; public static final String RSA_ALGORITHM = "RSA"; // the symmetric key we are encrypting with RSA is only 256 bits... use SHA-256 public static final String ASYMMETRIC_ALGORITHM = "RSA/NONE/OAEPWithSHA256AndMGF1Padding"; public static final String SYMMETRIC_ALGORITHM = "AES/CFB/PKCS5Padding"; public static final String UTF_8 = "UTF-8"; public static final int SYMMETRIC_KEY_LENGTH = 256; public static final int IV_BYTE_LENGTH = 16; // tags in the submission manifest private static final String XML_ENCRYPTED_TAG_NAMESPACE = "http://www.opendatakit.org/xforms/encrypted"; private static final String XML_OPENROSA_NAMESPACE = "http://openrosa.org/xforms"; private static final String DATA = "data"; private static final String ID = "id"; private static final String VERSION = "version"; private static final String ENCRYPTED = "encrypted"; private static final String BASE64_ENCRYPTED_KEY = "base64EncryptedKey"; private static final String ENCRYPTED_XML_FILE = "encryptedXmlFile"; private static final String META = "meta"; private static final String INSTANCE_ID = "instanceID"; private static final String MEDIA = "media"; private static final String FILE = "file"; private static final String BASE64_ENCRYPTED_ELEMENT_SIGNATURE = "base64EncryptedElementSignature"; private static final String NEW_LINE = "\n"; private static final String ENCRYPTION_PROVIDER = "BC"; private EncryptionUtils() { } public static final class EncryptedFormInformation { public final String formId; public final String formVersion; public final InstanceMetadata instanceMetadata; public final PublicKey rsaPublicKey; public final String base64RsaEncryptedSymmetricKey; public final SecretKeySpec symmetricKey; public final byte[] ivSeedArray; private int ivCounter = 0; public final StringBuilder elementSignatureSource = new StringBuilder(); public final Base64Wrapper wrapper; private boolean isNotBouncyCastle = false; EncryptedFormInformation(String formId, String formVersion, InstanceMetadata instanceMetadata, PublicKey rsaPublicKey, Base64Wrapper wrapper) { this.formId = formId; this.formVersion = formVersion; this.instanceMetadata = instanceMetadata; this.rsaPublicKey = rsaPublicKey; this.wrapper = wrapper; // generate the symmetric key from random bits... SecureRandom r = new SecureRandom(); byte[] key = new byte[SYMMETRIC_KEY_LENGTH/8]; r.nextBytes(key); SecretKeySpec sk = new SecretKeySpec(key, SYMMETRIC_ALGORITHM); symmetricKey = sk; // construct the fixed portion of the iv -- the ivSeedArray // this is the md5 hash of the instanceID and the symmetric key try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(instanceMetadata.instanceId.getBytes(UTF_8)); md.update(key); byte[] messageDigest = md.digest(); ivSeedArray = new byte[IV_BYTE_LENGTH]; for ( int i = 0 ; i < IV_BYTE_LENGTH ; ++i ) { ivSeedArray[i] = messageDigest[(i % messageDigest.length)]; } } catch (NoSuchAlgorithmException e) { Log.e(t, e.toString()); e.printStackTrace(); throw new IllegalArgumentException(e.getMessage()); } catch (UnsupportedEncodingException e) { Log.e(t, e.toString()); e.printStackTrace(); throw new IllegalArgumentException(e.getMessage()); } // construct the base64-encoded RSA-encrypted symmetric key try { Cipher pkCipher; pkCipher = Cipher.getInstance(ASYMMETRIC_ALGORITHM); // write AES key pkCipher.init(Cipher.ENCRYPT_MODE, rsaPublicKey); byte[] pkEncryptedKey = pkCipher.doFinal(key); String alg = pkCipher.getAlgorithm(); Log.i(t, "AlgorithmUsed: " + alg); base64RsaEncryptedSymmetricKey = wrapper .encodeToString(pkEncryptedKey); } catch (NoSuchAlgorithmException e) { Log.e(t, "Unable to encrypt the symmetric key"); e.printStackTrace(); throw new IllegalArgumentException(e.getMessage()); } catch (NoSuchPaddingException e) { Log.e(t, "Unable to encrypt the symmetric key"); e.printStackTrace(); throw new IllegalArgumentException(e.getMessage()); } catch (InvalidKeyException e) { Log.e(t, "Unable to encrypt the symmetric key"); e.printStackTrace(); throw new IllegalArgumentException(e.getMessage()); } catch (IllegalBlockSizeException e) { Log.e(t, "Unable to encrypt the symmetric key"); e.printStackTrace(); throw new IllegalArgumentException(e.getMessage()); } catch (BadPaddingException e) { Log.e(t, "Unable to encrypt the symmetric key"); e.printStackTrace(); throw new IllegalArgumentException(e.getMessage()); } // start building elementSignatureSource... appendElementSignatureSource(formId); if ( formVersion != null ) { appendElementSignatureSource(formVersion.toString()); } appendElementSignatureSource(base64RsaEncryptedSymmetricKey); appendElementSignatureSource( instanceMetadata.instanceId ); } public void appendElementSignatureSource(String value) { elementSignatureSource.append(value).append("\n"); } public void appendFileSignatureSource(File file) { String md5Hash = FileUtils.getMd5Hash(file); appendElementSignatureSource(file.getName()+"::"+md5Hash); } public String getBase64EncryptedElementSignature() { // Step 0: construct the text of the elements in elementSignatureSource (done) // Where... // * Elements are separated by newline characters. // * Filename is the unencrypted filename (no .enc suffix). // * Md5 hashes of the unencrypted files' contents are converted // to zero-padded 32-character strings before concatenation. // Assumes this is in the order: // formId // version (omitted if null) // base64RsaEncryptedSymmetricKey // instanceId // for each media file { filename "::" md5Hash } // submission.xml "::" md5Hash // Step 1: construct the (raw) md5 hash of Step 0. byte[] messageDigest; try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(elementSignatureSource.toString().getBytes(UTF_8)); messageDigest = md.digest(); } catch (NoSuchAlgorithmException e) { Log.e(t, e.toString()); e.printStackTrace(); throw new IllegalArgumentException(e.getMessage()); } catch (UnsupportedEncodingException e) { Log.e(t, e.toString()); e.printStackTrace(); throw new IllegalArgumentException(e.getMessage()); } // Step 2: construct the base64-encoded RSA-encrypted md5 try { Cipher pkCipher; pkCipher = Cipher.getInstance(ASYMMETRIC_ALGORITHM); // write AES key pkCipher.init(Cipher.ENCRYPT_MODE, rsaPublicKey); byte[] pkEncryptedKey = pkCipher.doFinal(messageDigest); return wrapper.encodeToString(pkEncryptedKey); } catch (NoSuchAlgorithmException e) { Log.e(t, "Unable to encrypt the symmetric key"); e.printStackTrace(); throw new IllegalArgumentException(e.getMessage()); } catch (NoSuchPaddingException e) { Log.e(t, "Unable to encrypt the symmetric key"); e.printStackTrace(); throw new IllegalArgumentException(e.getMessage()); } catch (InvalidKeyException e) { Log.e(t, "Unable to encrypt the symmetric key"); e.printStackTrace(); throw new IllegalArgumentException(e.getMessage()); } catch (IllegalBlockSizeException e) { Log.e(t, "Unable to encrypt the symmetric key"); e.printStackTrace(); throw new IllegalArgumentException(e.getMessage()); } catch (BadPaddingException e) { Log.e(t, "Unable to encrypt the symmetric key"); e.printStackTrace(); throw new IllegalArgumentException(e.getMessage()); } } public Cipher getCipher() throws InvalidKeyException, InvalidAlgorithmParameterException, NoSuchAlgorithmException, NoSuchPaddingException { ++ivSeedArray[ivCounter % ivSeedArray.length]; ++ivCounter; IvParameterSpec baseIv = new IvParameterSpec(ivSeedArray); Cipher c = null; try { c = Cipher.getInstance(EncryptionUtils.SYMMETRIC_ALGORITHM, "BC"); isNotBouncyCastle = false; } catch (NoSuchProviderException e) { Log.w(t, "Unable to obtain BouncyCastle provider! Decryption may fail!"); e.printStackTrace(); isNotBouncyCastle = true; c = Cipher.getInstance(EncryptionUtils.SYMMETRIC_ALGORITHM); } c.init(Cipher.ENCRYPT_MODE, symmetricKey, baseIv); return c; } public boolean isNotBouncyCastle() { return isNotBouncyCastle; } } /** * Retrieve the encryption information for this uri. * * @param mUri either an instance URI (if previously saved) or a form URI * @param instanceMetadata * @return */ public static EncryptedFormInformation getEncryptedFormInformation(Uri mUri, InstanceMetadata instanceMetadata) { ContentResolver cr = Collect.getInstance().getContentResolver(); // fetch the form information String formId; String formVersion; PublicKey pk; Base64Wrapper wrapper; Cursor formCursor = null; try { if (cr.getType(mUri) == InstanceColumns.CONTENT_ITEM_TYPE) { // chain back to the Form record... String[] selectionArgs = null; String selection = null; Cursor instanceCursor = null; try { instanceCursor = cr.query(mUri, null, null, null, null); if ( instanceCursor.getCount() != 1 ) { Log.e(t, "Not exactly one record for this instance!"); return null; // save unencrypted. } instanceCursor.moveToFirst(); String jrFormId = instanceCursor.getString(instanceCursor.getColumnIndex(InstanceColumns.JR_FORM_ID)); int idxJrVersion = instanceCursor.getColumnIndex(InstanceColumns.JR_VERSION); if ( !instanceCursor.isNull(idxJrVersion) ) { selectionArgs = new String[] {jrFormId, instanceCursor.getString(idxJrVersion)}; selection = FormsColumns.JR_FORM_ID + " =? AND " + FormsColumns.JR_VERSION + "=?"; } else { selectionArgs = new String[] {jrFormId}; selection = FormsColumns.JR_FORM_ID + " =? AND " + FormsColumns.JR_VERSION + " IS NULL"; } } finally { if ( instanceCursor != null ) { instanceCursor.close(); } } formCursor = cr.query(FormsColumns.CONTENT_URI, null, selection, selectionArgs, null); if (formCursor.getCount() != 1) { Log.e(t, "Not exactly one blank form matches this jr_form_id"); return null; // save unencrypted } formCursor.moveToFirst(); } else if (cr.getType(mUri) == FormsColumns.CONTENT_ITEM_TYPE) { formCursor = cr.query(mUri, null, null, null, null); if ( formCursor.getCount() != 1 ) { Log.e(t, "Not exactly one blank form!"); return null; // save unencrypted. } formCursor.moveToFirst(); } formId = formCursor.getString(formCursor.getColumnIndex(FormsColumns.JR_FORM_ID)); if (formId == null || formId.length() == 0) { Log.e(t, "No FormId specified???"); return null; } int idxVersion = formCursor.getColumnIndex(FormsColumns.JR_VERSION); int idxBase64RsaPublicKey = formCursor.getColumnIndex(FormsColumns.BASE64_RSA_PUBLIC_KEY); formVersion = formCursor.isNull(idxVersion) ? null : formCursor.getString(idxVersion); String base64RsaPublicKey = formCursor.isNull(idxBase64RsaPublicKey) ? null : formCursor.getString(idxBase64RsaPublicKey); if (base64RsaPublicKey == null || base64RsaPublicKey.length() == 0) { return null; // this is legitimately not an encrypted form } int version = android.os.Build.VERSION.SDK_INT; if (version < 8) { Log.e(t, "Phone does not support encryption."); return null; // save unencrypted } // this constructor will throw an exception if we are not // running on version 8 or above (if Base64 is not found). try { wrapper = new Base64Wrapper(); } catch (ClassNotFoundException e) { Log.e(t, "Phone does not have Base64 class but API level is " + version); e.printStackTrace(); return null; // save unencrypted } // OK -- Base64 decode (requires API Version 8 or higher) byte[] publicKey = wrapper.decode(base64RsaPublicKey); X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(publicKey); KeyFactory kf; try { kf = KeyFactory.getInstance(RSA_ALGORITHM); } catch (NoSuchAlgorithmException e) { Log.e(t, "Phone does not support RSA encryption."); e.printStackTrace(); return null; } try { pk = kf.generatePublic(publicKeySpec); } catch (InvalidKeySpecException e) { e.printStackTrace(); Log.e(t, "Invalid RSA public key."); return null; } } finally { if (formCursor != null) { formCursor.close(); } } // submission must have an OpenRosa metadata block with a non-null // instanceID value. if (instanceMetadata.instanceId == null) { Log.e(t, "No OpenRosa metadata block or no instanceId defined in that block"); return null; } // For now, prevent encryption if the BouncyCastle implementation is not present. // https://code.google.com/p/opendatakit/issues/detail?id=918 try { Cipher.getInstance(EncryptionUtils.SYMMETRIC_ALGORITHM, ENCRYPTION_PROVIDER); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); Log.e(t, "No BouncyCastle implementation of symmetric algorithm!"); return null; } catch (NoSuchProviderException e) { e.printStackTrace(); Log.e(t, "No BouncyCastle provider for implementation of symmetric algorithm!"); return null; } catch (NoSuchPaddingException e) { e.printStackTrace(); Log.e(t, "No BouncyCastle provider for padding implementation of symmetric algorithm!"); return null; } return new EncryptedFormInformation(formId, formVersion, instanceMetadata, pk, wrapper); } private static void encryptFile(File file, EncryptedFormInformation formInfo) throws IOException, EncryptionException { File encryptedFile = new File(file.getParentFile(), file.getName() + ".enc"); if (encryptedFile.exists() && !encryptedFile.delete()) { throw new IOException("Cannot overwrite " + encryptedFile.getAbsolutePath() + ". Perhaps the file is locked?"); } // add elementSignatureSource for this file... formInfo.appendFileSignatureSource(file); RandomAccessFile randomAccessFile = null; CipherOutputStream cipherOutputStream = null; try { Cipher c = formInfo.getCipher(); randomAccessFile = new RandomAccessFile(encryptedFile, "rws"); ByteArrayOutputStream encryptedData = new ByteArrayOutputStream(); cipherOutputStream = new CipherOutputStream(encryptedData, c); InputStream fin = new FileInputStream(file); byte[] buffer = new byte[2048]; int len = fin.read(buffer); while (len != -1) { cipherOutputStream.write(buffer, 0, len); len = fin.read(buffer); } fin.close(); cipherOutputStream.flush(); cipherOutputStream.close(); randomAccessFile.write(encryptedData.toByteArray()); Log.i(t, "Encrpyted:" + file.getName() + " -> " + encryptedFile.getName()); } catch (Exception e) { String msg = "Error encrypting: " + file.getName() + " -> " + encryptedFile.getName(); Log.e(t, msg, e); e.printStackTrace(); throw new EncryptionException(msg, e); } finally { IOUtils.closeQuietly(cipherOutputStream); if (randomAccessFile != null) { randomAccessFile.close(); } } } public static boolean deletePlaintextFiles(File instanceXml) { // NOTE: assume the directory containing the instanceXml contains ONLY // files related to this one instance. File instanceDir = instanceXml.getParentFile(); boolean allSuccessful = true; // encrypt files that do not end with ".enc", and do not start with "."; // ignore directories File[] allFiles = instanceDir.listFiles(); for (File f : allFiles) { if (f.equals(instanceXml)) continue; // don't touch instance file if (f.isDirectory()) continue; // don't handle directories if (!f.getName().endsWith(".enc")) { // not an encrypted file -- delete it! allSuccessful = allSuccessful & f.delete(); // DO NOT // short-circuit } } return allSuccessful; } private static List<File> encryptSubmissionFiles(File instanceXml, File submissionXml, EncryptedFormInformation formInfo) throws IOException, EncryptionException { // NOTE: assume the directory containing the instanceXml contains ONLY // files related to this one instance. File instanceDir = instanceXml.getParentFile(); // encrypt files that do not end with ".enc", and do not start with "."; // ignore directories File[] allFiles = instanceDir.listFiles(); List<File> filesToProcess = new ArrayList<File>(); for (File f : allFiles) { if (f.equals(instanceXml)) continue; // don't touch restore file if (f.equals(submissionXml)) continue; // handled last if (f.isDirectory()) continue; // don't handle directories if (f.getName().startsWith(".")) continue; // MacOSX garbage if (f.getName().endsWith(".enc")) { f.delete(); // try to delete this (leftover junk) } else { filesToProcess.add(f); } } // encrypt here... for (File f : filesToProcess) { encryptFile(f, formInfo); } // encrypt the submission.xml as the last file... encryptFile(submissionXml, formInfo); return filesToProcess; } /** * Constructs the encrypted attachments, encrypted form xml, and the * plaintext submission manifest (with signature) for the form submission. * * Does not delete any of the original files. * * @param instanceXml * @param submissionXml * @param formInfo * @return */ public static void generateEncryptedSubmission(File instanceXml, File submissionXml, EncryptedFormInformation formInfo) throws IOException, EncryptionException { // submissionXml is the submission data to be published to Aggregate if (!submissionXml.exists() || !submissionXml.isFile()) { throw new IOException("No submission.xml found"); } // TODO: confirm that this xml is not already encrypted... // Step 1: encrypt the submission and all the media files... List<File> mediaFiles = encryptSubmissionFiles(instanceXml, submissionXml, formInfo); // Step 2: build the encrypted-submission manifest (overwrites // submission.xml)... writeSubmissionManifest(formInfo, submissionXml, mediaFiles); } private static void writeSubmissionManifest( EncryptedFormInformation formInfo, File submissionXml, List<File> mediaFiles) throws EncryptionException { Document d = new Document(); d.setStandalone(true); d.setEncoding(UTF_8); Element e = d.createElement(XML_ENCRYPTED_TAG_NAMESPACE, DATA); e.setPrefix(null, XML_ENCRYPTED_TAG_NAMESPACE); e.setAttribute(null, ID, formInfo.formId); if ( formInfo.formVersion != null ) { e.setAttribute(null, VERSION, formInfo.formVersion); } e.setAttribute(null, ENCRYPTED, "yes"); d.addChild(0, Node.ELEMENT, e); int idx = 0; Element c; c = d.createElement(XML_ENCRYPTED_TAG_NAMESPACE, BASE64_ENCRYPTED_KEY); c.addChild(0, Node.TEXT, formInfo.base64RsaEncryptedSymmetricKey); e.addChild(idx++, Node.ELEMENT, c); c = d.createElement(XML_OPENROSA_NAMESPACE, META); c.setPrefix("orx", XML_OPENROSA_NAMESPACE); { Element instanceTag = d.createElement(XML_OPENROSA_NAMESPACE, INSTANCE_ID); instanceTag.addChild(0, Node.TEXT, formInfo.instanceMetadata.instanceId); c.addChild(0, Node.ELEMENT, instanceTag); } e.addChild(idx++, Node.ELEMENT, c); e.addChild(idx++, Node.IGNORABLE_WHITESPACE, NEW_LINE); if (mediaFiles != null) { for (File file : mediaFiles) { c = d.createElement(XML_ENCRYPTED_TAG_NAMESPACE, MEDIA); Element fileTag = d.createElement(XML_ENCRYPTED_TAG_NAMESPACE, FILE); fileTag.addChild(0, Node.TEXT, file.getName() + ".enc"); c.addChild(0, Node.ELEMENT, fileTag); e.addChild(idx++, Node.ELEMENT, c); e.addChild(idx++, Node.IGNORABLE_WHITESPACE, NEW_LINE); } } c = d.createElement(XML_ENCRYPTED_TAG_NAMESPACE, ENCRYPTED_XML_FILE); c.addChild(0, Node.TEXT, submissionXml.getName() + ".enc"); e.addChild(idx++, Node.ELEMENT, c); c = d.createElement(XML_ENCRYPTED_TAG_NAMESPACE, BASE64_ENCRYPTED_ELEMENT_SIGNATURE); c.addChild(0, Node.TEXT, formInfo.getBase64EncryptedElementSignature()); e.addChild(idx++, Node.ELEMENT, c); FileOutputStream fout = null; OutputStreamWriter writer = null; try { fout = new FileOutputStream(submissionXml); writer = new OutputStreamWriter(fout, UTF_8); KXmlSerializer serializer = new KXmlSerializer(); serializer.setOutput(writer); // setting the response content type emits the xml header. // just write the body here... d.writeChildren(serializer); serializer.flush(); writer.flush(); fout.getChannel().force(true); writer.close(); } catch (Exception ex) { ex.printStackTrace(); String msg = "Error writing submission.xml for encrypted submission: " + submissionXml.getParentFile().getName(); Log.e(t, msg); throw new EncryptionException(msg, ex); } finally { IOUtils.closeQuietly(writer); IOUtils.closeQuietly(fout); } } }
Java
/* * Copyright (C) 2012 University of Washington * * 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 org.odk.collect.android.utilities; import org.odk.collect.android.R; import android.app.Dialog; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.LinearGradient; import android.graphics.Paint; import android.graphics.Shader; import android.os.Bundle; import android.util.AttributeSet; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup.LayoutParams; import android.widget.HorizontalScrollView; import android.widget.ScrollView; /** * Based heavily upon: * http://www.yougli.net/android/a-photoshop-like-color-picker * -for-your-android-application/ * * @author BehrAtherton@gmail.com * @author yougli@yougli.net * */ public class ColorPickerDialog extends Dialog { public interface OnColorChangedListener { void colorChanged(String key, int color); } private OnColorChangedListener mListener; private int mInitialColor, mDefaultColor; private String mKey; /** * Modified HorizontalScrollView that communicates scroll * actions to interior Vertical scroll view. * From: http://stackoverflow.com/questions/3866499/two-directional-scroll-view * */ public class WScrollView extends HorizontalScrollView { public ScrollView sv; public WScrollView(Context context) { super(context); } public WScrollView(Context context, AttributeSet attrs) { super(context, attrs); } public WScrollView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } @Override public boolean onTouchEvent(MotionEvent event) { boolean ret = super.onTouchEvent(event); ret = ret | sv.onTouchEvent(event); return ret; } @Override public boolean onInterceptTouchEvent(MotionEvent event) { boolean ret = super.onInterceptTouchEvent(event); ret = ret | sv.onInterceptTouchEvent(event); return ret; } } private static class ColorPickerView extends View { private Paint mPaint; private float mCurrentHue = 0; private int mCurrentX = 0, mCurrentY = 0; private int mCurrentColor, mDefaultColor; private final int[] mHueBarColors = new int[258]; private int[] mMainColors = new int[65536]; private OnColorChangedListener mListener; ColorPickerView(Context c, OnColorChangedListener l, int color, int defaultColor) { super(c); mListener = l; mDefaultColor = defaultColor; // Get the current hue from the current color and update the main // color field float[] hsv = new float[3]; Color.colorToHSV(color, hsv); mCurrentHue = hsv[0]; updateMainColors(); mCurrentColor = color; // Initialize the colors of the hue slider bar int index = 0; for (float i = 0; i < 256; i += 256 / 42) // Red (#f00) to pink // (#f0f) { mHueBarColors[index] = Color.rgb(255, 0, (int) i); index++; } for (float i = 0; i < 256; i += 256 / 42) // Pink (#f0f) to blue // (#00f) { mHueBarColors[index] = Color.rgb(255 - (int) i, 0, 255); index++; } for (float i = 0; i < 256; i += 256 / 42) // Blue (#00f) to light // blue (#0ff) { mHueBarColors[index] = Color.rgb(0, (int) i, 255); index++; } for (float i = 0; i < 256; i += 256 / 42) // Light blue (#0ff) to // green (#0f0) { mHueBarColors[index] = Color.rgb(0, 255, 255 - (int) i); index++; } for (float i = 0; i < 256; i += 256 / 42) // Green (#0f0) to yellow // (#ff0) { mHueBarColors[index] = Color.rgb((int) i, 255, 0); index++; } for (float i = 0; i < 256; i += 256 / 42) // Yellow (#ff0) to red // (#f00) { mHueBarColors[index] = Color.rgb(255, 255 - (int) i, 0); index++; } // Initializes the Paint that will draw the View mPaint = new Paint(Paint.ANTI_ALIAS_FLAG); mPaint.setTextAlign(Paint.Align.CENTER); mPaint.setTextSize(12); } // Get the current selected color from the hue bar private int getCurrentMainColor() { int translatedHue = 255 - (int) (mCurrentHue * 255 / 360); int index = 0; for (float i = 0; i < 256; i += 256 / 42) { if (index == translatedHue) return Color.rgb(255, 0, (int) i); index++; } for (float i = 0; i < 256; i += 256 / 42) { if (index == translatedHue) return Color.rgb(255 - (int) i, 0, 255); index++; } for (float i = 0; i < 256; i += 256 / 42) { if (index == translatedHue) return Color.rgb(0, (int) i, 255); index++; } for (float i = 0; i < 256; i += 256 / 42) { if (index == translatedHue) return Color.rgb(0, 255, 255 - (int) i); index++; } for (float i = 0; i < 256; i += 256 / 42) { if (index == translatedHue) return Color.rgb((int) i, 255, 0); index++; } for (float i = 0; i < 256; i += 256 / 42) { if (index == translatedHue) return Color.rgb(255, 255 - (int) i, 0); index++; } return Color.RED; } // Update the main field colors depending on the current selected hue private void updateMainColors() { int mainColor = getCurrentMainColor(); int index = 0; int[] topColors = new int[256]; for (int y = 0; y < 256; y++) { for (int x = 0; x < 256; x++) { if (y == 0) { mMainColors[index] = Color.rgb( 255 - (255 - Color.red(mainColor)) * x / 255, 255 - (255 - Color.green(mainColor)) * x / 255, 255 - (255 - Color.blue(mainColor)) * x / 255); topColors[x] = mMainColors[index]; } else mMainColors[index] = Color.rgb( (255 - y) * Color.red(topColors[x]) / 255, (255 - y) * Color.green(topColors[x]) / 255, (255 - y) * Color.blue(topColors[x]) / 255); index++; } } } @Override protected void onDraw(Canvas canvas) { int translatedHue = 255 - (int) (mCurrentHue * 255 / 360); // Display all the colors of the hue bar with lines for (int x = 0; x < 256; x++) { // If this is not the current selected hue, display the actual // color if (translatedHue != x) { mPaint.setColor(mHueBarColors[x]); mPaint.setStrokeWidth(1); } else // else display a slightly larger black line { mPaint.setColor(Color.BLACK); mPaint.setStrokeWidth(3); } canvas.drawLine(x + 10, 0, x + 10, 40, mPaint); } // Display the main field colors using LinearGradient for (int x = 0; x < 256; x++) { int[] colors = new int[2]; colors[0] = mMainColors[x]; colors[1] = Color.BLACK; Shader shader = new LinearGradient(0, 50, 0, 306, colors, null, Shader.TileMode.REPEAT); mPaint.setShader(shader); canvas.drawLine(x + 10, 50, x + 10, 306, mPaint); } mPaint.setShader(null); // Display the circle around the currently selected color in the // main field if (mCurrentX != 0 && mCurrentY != 0) { mPaint.setStyle(Paint.Style.STROKE); mPaint.setColor(Color.BLACK); canvas.drawCircle(mCurrentX, mCurrentY, 10, mPaint); } // Draw a 'button' with the currently selected color mPaint.setStyle(Paint.Style.FILL); mPaint.setColor(mCurrentColor); canvas.drawRect(10, 316, 138, 356, mPaint); // Set the text color according to the brightness of the color mPaint.setColor(getInverseColor(mCurrentColor)); canvas.drawText(getContext().getString(R.string.ok), 74, 340, mPaint); // Draw a 'button' with the default color mPaint.setStyle(Paint.Style.FILL); mPaint.setColor(mDefaultColor); canvas.drawRect(138, 316, 266, 356, mPaint); // Set the text color according to the brightness of the color mPaint.setColor(getInverseColor(mDefaultColor)); canvas.drawText(getContext().getString(R.string.cancel), 202, 340, mPaint); } private int getInverseColor(int color) { int red = Color.red(color); int green = Color.green(color); int blue = Color.blue(color); int alpha = Color.alpha(color); return Color.argb(alpha, 255 - red, 255 - green, 255 - blue); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { setMeasuredDimension(276, 366); } private boolean afterFirstDown = false; private float startX; private float startY; @Override public boolean onTouchEvent(MotionEvent event) { // allow scrolling... boolean ret = super.onTouchEvent(event); int action = event.getAction(); int pointerCount = event.getPointerCount(); if ( action == MotionEvent.ACTION_CANCEL ) { afterFirstDown = false; } else if ( pointerCount == 1 && action == MotionEvent.ACTION_DOWN ) { afterFirstDown = true; startX = event.getX(); startY = event.getY(); } else if ( pointerCount == 1 && action == MotionEvent.ACTION_MOVE && !afterFirstDown ) { afterFirstDown = true; startX = event.getX(); startY = event.getY(); } if ( !afterFirstDown || pointerCount != 1 || action != MotionEvent.ACTION_UP ) { return true; } // on an ACTION_UP, we reset the afterFirstDown flag. // processing uses the lifting of the finger to choose // the color... afterFirstDown = false; float x = event.getX(); float y = event.getY(); if ( Math.abs(x - startX) > 10 && Math.abs(y - startY) > 10 ) { // the color location drifted, so it must just be a scrolling action // ignore it... return ret; } // If the touch event is located in the hue bar if (x > 10 && x < 266 && y > 0 && y < 40) { // Update the main field colors mCurrentHue = (255 - x) * 360 / 255; updateMainColors(); // Update the current selected color int transX = mCurrentX - 10; int transY = mCurrentY - 60; int index = 256 * (transY - 1) + transX; if (index > 0 && index < mMainColors.length) mCurrentColor = mMainColors[256 * (transY - 1) + transX]; // Force the redraw of the dialog invalidate(); } // If the touch event is located in the main field if (x > 10 && x < 266 && y > 50 && y < 306) { mCurrentX = (int) x; mCurrentY = (int) y; int transX = mCurrentX - 10; int transY = mCurrentY - 60; int index = 256 * (transY - 1) + transX; if (index > 0 && index < mMainColors.length) { // Update the current color mCurrentColor = mMainColors[index]; // Force the redraw of the dialog invalidate(); } } // If the touch event is located in the left button, notify the // listener with the current color if (x > 10 && x < 138 && y > 316 && y < 356) mListener.colorChanged("", mCurrentColor); // If the touch event is located in the right button, notify the // listener with the default color if (x > 138 && x < 266 && y > 316 && y < 356) mListener.colorChanged("", mDefaultColor); return true; } } public ColorPickerDialog(Context context, OnColorChangedListener listener, String key, int initialColor, int defaultColor, String title) { super(context); mListener = listener; mKey = key; mInitialColor = initialColor; mDefaultColor = defaultColor; setTitle(title); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); OnColorChangedListener l = new OnColorChangedListener() { public void colorChanged(String key, int color) { mListener.colorChanged(mKey, color); dismiss(); } }; /*BIDIRECTIONAL SCROLLVIEW*/ ScrollView sv = new ScrollView(this.getContext()); WScrollView hsv = new WScrollView(this.getContext()); hsv.sv = sv; /*END OF BIDIRECTIONAL SCROLLVIEW*/ sv.addView(new ColorPickerView(getContext(), l, mInitialColor, mDefaultColor), new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT)); hsv.addView(sv, new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.FILL_PARENT)); setContentView(hsv, new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); setCanceledOnTouchOutside(true); } }
Java
/* * Copyright (C) 2011 University of Washington * * 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 org.odk.collect.android.utilities; import java.io.UnsupportedEncodingException; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; /** * Wrapper class for accessing Base64 functionality. * This allows API Level 7 deployment of ODK Collect while * enabling API Level 8 and higher phone to support encryption. * * @author mitchellsundt@gmail.com * */ public class Base64Wrapper { private static final int FLAGS = 2;// NO_WRAP private Class<?> base64 = null; public Base64Wrapper() throws ClassNotFoundException { base64 = this.getClass().getClassLoader() .loadClass("android.util.Base64"); } public String encodeToString(byte[] ba) { Class<?>[] argClassList = new Class[]{byte[].class, int.class}; try { Method m = base64.getDeclaredMethod("encode", argClassList); Object[] argList = new Object[]{ ba, FLAGS }; Object o = m.invoke(null, argList); byte[] outArray = (byte[]) o; String s = new String(outArray, "UTF-8"); return s; } catch (SecurityException e) { e.printStackTrace(); throw new IllegalArgumentException(e.toString()); } catch (NoSuchMethodException e) { e.printStackTrace(); throw new IllegalArgumentException(e.toString()); } catch (IllegalAccessException e) { e.printStackTrace(); throw new IllegalArgumentException(e.toString()); } catch (InvocationTargetException e) { e.printStackTrace(); throw new IllegalArgumentException(e.toString()); } catch (UnsupportedEncodingException e) { e.printStackTrace(); throw new IllegalArgumentException(e.toString()); } } public byte[] decode(String base64String) { Class<?>[] argClassList = new Class[]{String.class, int.class}; Object o; try { Method m = base64.getDeclaredMethod("decode", argClassList); Object[] argList = new Object[]{ base64String, FLAGS }; o = m.invoke(null, argList); } catch (SecurityException e) { e.printStackTrace(); throw new IllegalArgumentException(e.toString()); } catch (NoSuchMethodException e) { e.printStackTrace(); throw new IllegalArgumentException(e.toString()); } catch (IllegalAccessException e) { e.printStackTrace(); throw new IllegalArgumentException(e.toString()); } catch (InvocationTargetException e) { e.printStackTrace(); throw new IllegalArgumentException(e.toString()); } return (byte[]) o; } }
Java
/* * Copyright (C) 2011 University of Washington * * 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. * * Original License from BasicCredentialsProvider: * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.odk.collect.android.utilities; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import org.opendatakit.httpclientandroidlib.annotation.ThreadSafe; import org.opendatakit.httpclientandroidlib.auth.AuthScope; import org.opendatakit.httpclientandroidlib.auth.Credentials; import org.opendatakit.httpclientandroidlib.client.CredentialsProvider; /** * Modified BasicCredentialsProvider that will clear the provider * after 'expiryInterval' milliseconds of inactivity. Use the WebUtils * methods to manipulate the credentials in the local context. You should * first check that the credentials exist (which will reset the expiration * date), then set them if they are missing. * * Largely a cut-and-paste of BasicCredentialsProvider. * * @author mitchellsundt@gmail.com * */ @ThreadSafe public class AgingCredentialsProvider implements CredentialsProvider { private final ConcurrentHashMap<AuthScope, Credentials> credMap; private final long expiryInterval; private long nextClearTimestamp; /** * Default constructor. */ public AgingCredentialsProvider(int expiryInterval) { super(); this.credMap = new ConcurrentHashMap<AuthScope, Credentials>(); this.expiryInterval = expiryInterval; nextClearTimestamp = System.currentTimeMillis() + expiryInterval; } public void setCredentials( final AuthScope authscope, final Credentials credentials) { if (authscope == null) { throw new IllegalArgumentException("Authentication scope may not be null"); } if (nextClearTimestamp < System.currentTimeMillis()) { clear(); } nextClearTimestamp = System.currentTimeMillis() + expiryInterval; if ( credentials == null ) { credMap.remove(authscope); } else { credMap.put(authscope, credentials); } } /** * Find matching {@link Credentials credentials} for the given authentication scope. * * @param map the credentials hash map * @param authscope the {@link AuthScope authentication scope} * @return the credentials * */ private static Credentials matchCredentials( final Map<AuthScope, Credentials> map, final AuthScope authscope) { // see if we get a direct hit Credentials creds = map.get(authscope); if (creds == null) { // Nope. // Do a full scan int bestMatchFactor = -1; AuthScope bestMatch = null; for (AuthScope current: map.keySet()) { int factor = authscope.match(current); if (factor > bestMatchFactor) { bestMatchFactor = factor; bestMatch = current; } } if (bestMatch != null) { creds = map.get(bestMatch); } } return creds; } public Credentials getCredentials(final AuthScope authscope) { if (authscope == null) { throw new IllegalArgumentException("Authentication scope may not be null"); } if (nextClearTimestamp < System.currentTimeMillis()) { clear(); } nextClearTimestamp = System.currentTimeMillis() + expiryInterval; Credentials c = matchCredentials(this.credMap, authscope); return c; } public void clear() { this.credMap.clear(); } @Override public String toString() { return credMap.toString(); } }
Java
/* * Copyright (C) 2009 University of Washington * * 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 org.odk.collect.android.utilities; import java.io.File; import java.util.ArrayList; import java.util.List; import org.odk.collect.android.application.Collect; import android.annotation.SuppressLint; import android.content.ContentResolver; import android.content.ContentUris; import android.content.Context; import android.database.Cursor; import android.net.Uri; import android.os.Build; import android.os.Environment; import android.provider.DocumentsContract; import android.provider.MediaStore; import android.provider.MediaStore.Audio; import android.provider.MediaStore.Images; import android.provider.MediaStore.Video; import android.util.Log; /** * Consolidate all interactions with media providers here. * * The functionality of getPath() was provided by paulburke as described here: * See * http://stackoverflow.com/questions/20067508/get-real-path-from-uri-android * -kitkat-new-storage-access-framework for details * * @author mitchellsundt@gmail.com * @author paulburke * * */ public class MediaUtils { private static final String t = "MediaUtils"; private MediaUtils() { // static methods only } private static String escapePath(String path) { String ep = path; ep = ep.replaceAll("\\!", "!!"); ep = ep.replaceAll("_", "!_"); ep = ep.replaceAll("%", "!%"); return ep; } public static final Uri getImageUriFromMediaProvider(String imageFile) { String selection = Images.ImageColumns.DATA + "=?"; String[] selectArgs = { imageFile }; String[] projection = { Images.ImageColumns._ID }; Cursor c = null; try { c = Collect .getInstance() .getContentResolver() .query(android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI, projection, selection, selectArgs, null); if (c.getCount() > 0) { c.moveToFirst(); String id = c.getString(c .getColumnIndex(Images.ImageColumns._ID)); return Uri .withAppendedPath( android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI, id); } return null; } finally { if (c != null) { c.close(); } } } public static final int deleteImageFileFromMediaProvider(String imageFile) { ContentResolver cr = Collect.getInstance().getContentResolver(); // images int count = 0; Cursor imageCursor = null; try { String select = Images.Media.DATA + "=?"; String[] selectArgs = { imageFile }; String[] projection = { Images.ImageColumns._ID }; imageCursor = cr .query(android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI, projection, select, selectArgs, null); if (imageCursor.getCount() > 0) { imageCursor.moveToFirst(); List<Uri> imagesToDelete = new ArrayList<Uri>(); do { String id = imageCursor.getString(imageCursor .getColumnIndex(Images.ImageColumns._ID)); imagesToDelete .add(Uri.withAppendedPath( android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI, id)); } while (imageCursor.moveToNext()); for (Uri uri : imagesToDelete) { Log.i(t, "attempting to delete: " + uri); count += cr.delete(uri, null, null); } } } catch (Exception e) { Log.e(t, e.toString()); } finally { if (imageCursor != null) { imageCursor.close(); } } File f = new File(imageFile); if (f.exists()) { f.delete(); } return count; } public static final int deleteImagesInFolderFromMediaProvider(File folder) { ContentResolver cr = Collect.getInstance().getContentResolver(); // images int count = 0; Cursor imageCursor = null; try { String select = Images.Media.DATA + " like ? escape '!'"; String[] selectArgs = { escapePath(folder.getAbsolutePath()) }; String[] projection = { Images.ImageColumns._ID }; imageCursor = cr .query(android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI, projection, select, selectArgs, null); if (imageCursor.getCount() > 0) { imageCursor.moveToFirst(); List<Uri> imagesToDelete = new ArrayList<Uri>(); do { String id = imageCursor.getString(imageCursor .getColumnIndex(Images.ImageColumns._ID)); imagesToDelete .add(Uri.withAppendedPath( android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI, id)); } while (imageCursor.moveToNext()); for (Uri uri : imagesToDelete) { Log.i(t, "attempting to delete: " + uri); count += cr.delete(uri, null, null); } } } catch (Exception e) { Log.e(t, e.toString()); } finally { if (imageCursor != null) { imageCursor.close(); } } return count; } public static final Uri getAudioUriFromMediaProvider(String audioFile) { String selection = Audio.AudioColumns.DATA + "=?"; String[] selectArgs = { audioFile }; String[] projection = { Audio.AudioColumns._ID }; Cursor c = null; try { c = Collect .getInstance() .getContentResolver() .query(android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, projection, selection, selectArgs, null); if (c.getCount() > 0) { c.moveToFirst(); String id = c.getString(c .getColumnIndex(Audio.AudioColumns._ID)); return Uri .withAppendedPath( android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, id); } return null; } finally { if (c != null) { c.close(); } } } public static final int deleteAudioFileFromMediaProvider(String audioFile) { ContentResolver cr = Collect.getInstance().getContentResolver(); // audio int count = 0; Cursor audioCursor = null; try { String select = Audio.Media.DATA + "=?"; String[] selectArgs = { audioFile }; String[] projection = { Audio.AudioColumns._ID }; audioCursor = cr .query(android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, projection, select, selectArgs, null); if (audioCursor.getCount() > 0) { audioCursor.moveToFirst(); List<Uri> audioToDelete = new ArrayList<Uri>(); do { String id = audioCursor.getString(audioCursor .getColumnIndex(Audio.AudioColumns._ID)); audioToDelete .add(Uri.withAppendedPath( android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, id)); } while (audioCursor.moveToNext()); for (Uri uri : audioToDelete) { Log.i(t, "attempting to delete: " + uri); count += cr.delete(uri, null, null); } } } catch (Exception e) { Log.e(t, e.toString()); } finally { if (audioCursor != null) { audioCursor.close(); } } File f = new File(audioFile); if (f.exists()) { f.delete(); } return count; } public static final int deleteAudioInFolderFromMediaProvider(File folder) { ContentResolver cr = Collect.getInstance().getContentResolver(); // audio int count = 0; Cursor audioCursor = null; try { String select = Audio.Media.DATA + " like ? escape '!'"; String[] selectArgs = { escapePath(folder.getAbsolutePath()) }; String[] projection = { Audio.AudioColumns._ID }; audioCursor = cr .query(android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, projection, select, selectArgs, null); if (audioCursor.getCount() > 0) { audioCursor.moveToFirst(); List<Uri> audioToDelete = new ArrayList<Uri>(); do { String id = audioCursor.getString(audioCursor .getColumnIndex(Audio.AudioColumns._ID)); audioToDelete .add(Uri.withAppendedPath( android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, id)); } while (audioCursor.moveToNext()); for (Uri uri : audioToDelete) { Log.i(t, "attempting to delete: " + uri); count += cr.delete(uri, null, null); } } } catch (Exception e) { Log.e(t, e.toString()); } finally { if (audioCursor != null) { audioCursor.close(); } } return count; } public static final Uri getVideoUriFromMediaProvider(String videoFile) { String selection = Video.VideoColumns.DATA + "=?"; String[] selectArgs = { videoFile }; String[] projection = { Video.VideoColumns._ID }; Cursor c = null; try { c = Collect .getInstance() .getContentResolver() .query(android.provider.MediaStore.Video.Media.EXTERNAL_CONTENT_URI, projection, selection, selectArgs, null); if (c.getCount() > 0) { c.moveToFirst(); String id = c.getString(c .getColumnIndex(Video.VideoColumns._ID)); return Uri .withAppendedPath( android.provider.MediaStore.Video.Media.EXTERNAL_CONTENT_URI, id); } return null; } finally { if (c != null) { c.close(); } } } public static final int deleteVideoFileFromMediaProvider(String videoFile) { ContentResolver cr = Collect.getInstance().getContentResolver(); // video int count = 0; Cursor videoCursor = null; try { String select = Video.Media.DATA + "=?"; String[] selectArgs = { videoFile }; String[] projection = { Video.VideoColumns._ID }; videoCursor = cr .query(android.provider.MediaStore.Video.Media.EXTERNAL_CONTENT_URI, projection, select, selectArgs, null); if (videoCursor.getCount() > 0) { videoCursor.moveToFirst(); List<Uri> videoToDelete = new ArrayList<Uri>(); do { String id = videoCursor.getString(videoCursor .getColumnIndex(Video.VideoColumns._ID)); videoToDelete .add(Uri.withAppendedPath( android.provider.MediaStore.Video.Media.EXTERNAL_CONTENT_URI, id)); } while (videoCursor.moveToNext()); for (Uri uri : videoToDelete) { Log.i(t, "attempting to delete: " + uri); count += cr.delete(uri, null, null); } } } catch (Exception e) { Log.e(t, e.toString()); } finally { if (videoCursor != null) { videoCursor.close(); } } File f = new File(videoFile); if (f.exists()) { f.delete(); } return count; } public static final int deleteVideoInFolderFromMediaProvider(File folder) { ContentResolver cr = Collect.getInstance().getContentResolver(); // video int count = 0; Cursor videoCursor = null; try { String select = Video.Media.DATA + " like ? escape '!'"; String[] selectArgs = { escapePath(folder.getAbsolutePath()) }; String[] projection = { Video.VideoColumns._ID }; videoCursor = cr .query(android.provider.MediaStore.Video.Media.EXTERNAL_CONTENT_URI, projection, select, selectArgs, null); if (videoCursor.getCount() > 0) { videoCursor.moveToFirst(); List<Uri> videoToDelete = new ArrayList<Uri>(); do { String id = videoCursor.getString(videoCursor .getColumnIndex(Video.VideoColumns._ID)); videoToDelete .add(Uri.withAppendedPath( android.provider.MediaStore.Video.Media.EXTERNAL_CONTENT_URI, id)); } while (videoCursor.moveToNext()); for (Uri uri : videoToDelete) { Log.i(t, "attempting to delete: " + uri); count += cr.delete(uri, null, null); } } } catch (Exception e) { Log.e(t, e.toString()); } finally { if (videoCursor != null) { videoCursor.close(); } } return count; } /** * Consolidates the file path determination functionality of the various * media prompts. Beginning with KitKat, the responses use a different * mechanism and needs a lot of special handling. * * @param ctxt * @param uri * @param pathKey * @return */ @SuppressLint("NewApi") public static String getPathFromUri(Context ctxt, Uri uri, String pathKey) { if (Build.VERSION.SDK_INT >= 19) { return getPath(ctxt, uri); } else { if (uri.toString().startsWith("file")) { return uri.toString().substring(7); } else { String[] projection = { pathKey }; Cursor c = null; try { c = ctxt.getContentResolver().query(uri, projection, null, null, null); int column_index = c.getColumnIndexOrThrow(pathKey); String path = null; if (c.getCount() > 0) { c.moveToFirst(); path = c.getString(column_index); } return path; } finally { if (c != null) { c.close(); } } } } } @SuppressLint("NewApi") /** * Get a file path from a Uri. This will get the the path for Storage Access * Framework Documents, as well as the _data field for the MediaStore and * other file-based ContentProviders.<br> * <br> * Callers should check whether the path is local before assuming it * represents a local file. * * @param context The context. * @param uri The Uri to query. * @see #isLocal(String) * @see #getFile(Context, Uri) * @author paulburke */ public static String getPath(final Context context, final Uri uri) { final boolean isKitKat = Build.VERSION.SDK_INT >= 19; // DocumentProvider if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) { // ExternalStorageProvider if (isExternalStorageDocument(uri)) { final String docId = DocumentsContract.getDocumentId(uri); final String[] split = docId.split(":"); final String type = split[0]; if ("primary".equalsIgnoreCase(type)) { return Environment.getExternalStorageDirectory() + "/" + split[1]; } // TODO handle non-primary volumes } // DownloadsProvider else if (isDownloadsDocument(uri)) { final String id = DocumentsContract.getDocumentId(uri); final Uri contentUri = ContentUris.withAppendedId( Uri.parse("content://downloads/public_downloads"), Long.valueOf(id)); return getDataColumn(context, contentUri, null, null); } // MediaProvider else if (isMediaDocument(uri)) { final String docId = DocumentsContract.getDocumentId(uri); final String[] split = docId.split(":"); final String type = split[0]; Uri contentUri = null; if ("image".equals(type)) { contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI; } else if ("video".equals(type)) { contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI; } else if ("audio".equals(type)) { contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI; } final String selection = "_id=?"; final String[] selectionArgs = new String[] { split[1] }; return getDataColumn(context, contentUri, selection, selectionArgs); } } // MediaStore (and general) else if ("content".equalsIgnoreCase(uri.getScheme())) { // Return the remote address if (isGooglePhotosUri(uri)) return uri.getLastPathSegment(); return getDataColumn(context, uri, null, null); } // File else if ("file".equalsIgnoreCase(uri.getScheme())) { return uri.getPath(); } return null; } /** * @param uri * The Uri to check. * @return Whether the Uri authority is ExternalStorageProvider. * @author paulburke */ public static boolean isExternalStorageDocument(Uri uri) { return "com.android.externalstorage.documents".equals(uri .getAuthority()); } /** * @param uri * The Uri to check. * @return Whether the Uri authority is DownloadsProvider. * @author paulburke */ public static boolean isDownloadsDocument(Uri uri) { return "com.android.providers.downloads.documents".equals(uri .getAuthority()); } /** * @param uri * The Uri to check. * @return Whether the Uri authority is MediaProvider. * @author paulburke */ public static boolean isMediaDocument(Uri uri) { return "com.android.providers.media.documents".equals(uri .getAuthority()); } /** * @param uri * The Uri to check. * @return Whether the Uri authority is Google Photos. */ public static boolean isGooglePhotosUri(Uri uri) { return "com.google.android.apps.photos.content".equals(uri .getAuthority()); } /** * Get the value of the data column for this Uri. This is useful for * MediaStore Uris, and other file-based ContentProviders. * * @param context * The context. * @param uri * The Uri to query. * @param selection * (Optional) Filter used in the query. * @param selectionArgs * (Optional) Selection arguments used in the query. * @return The value of the _data column, which is typically a file path. * @author paulburke */ public static String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) { Cursor cursor = null; final String column = "_data"; final String[] projection = { column }; try { cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null); if (cursor != null && cursor.moveToFirst()) { final int column_index = cursor.getColumnIndexOrThrow(column); return cursor.getString(column_index); } } finally { if (cursor != null) cursor.close(); } return null; } }
Java
/* * Copyright (C) 2013 University of Washington * * 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 org.odk.collect.android.utilities; import android.annotation.SuppressLint; import android.app.Activity; import android.app.ActivityManager; import android.content.Context; import android.content.pm.ConfigurationInfo; import android.os.Build; import android.view.MenuItem; /** * Compatibility utilities for backward-compatible support of Android APIs above SDK 8 * * @author mitchellsundt@gmail.com * */ @SuppressLint("NewApi") public class CompatibilityUtils { public static void setShowAsAction(MenuItem item, int action) { if ( Build.VERSION.SDK_INT >= 11 ) { item.setShowAsAction(action); } } public static void invalidateOptionsMenu(final Activity a) { if ( Build.VERSION.SDK_INT >= 11 ) { a.runOnUiThread( new Runnable() { @Override public void run() { a.invalidateOptionsMenu(); } }); } } public static boolean useMapsV2(final Context context) { if ( Build.VERSION.SDK_INT >= 8 ) { final ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE); final ConfigurationInfo configurationInfo = activityManager.getDeviceConfigurationInfo(); boolean supportsEs2 = configurationInfo.reqGlEsVersion >= 0x20000; return supportsEs2; } return false; } }
Java
/* * Copyright (C) 2011 University of Washington * * 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 org.odk.collect.android.utilities; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.URI; import java.net.URL; import java.util.ArrayList; import java.util.Date; import java.util.GregorianCalendar; import java.util.List; import java.util.Locale; import java.util.TimeZone; import java.util.zip.GZIPInputStream; import org.apache.http.HttpStatus; import org.kxml2.io.KXmlParser; import org.kxml2.kdom.Document; import org.odk.collect.android.R; import org.odk.collect.android.application.Collect; import org.odk.collect.android.preferences.PreferencesActivity; import org.opendatakit.httpclientandroidlib.Header; import org.opendatakit.httpclientandroidlib.HttpEntity; import org.opendatakit.httpclientandroidlib.HttpHost; import org.opendatakit.httpclientandroidlib.HttpRequest; import org.opendatakit.httpclientandroidlib.HttpResponse; import org.opendatakit.httpclientandroidlib.auth.AuthScope; import org.opendatakit.httpclientandroidlib.auth.Credentials; import org.opendatakit.httpclientandroidlib.auth.UsernamePasswordCredentials; import org.opendatakit.httpclientandroidlib.auth.params.AuthPNames; import org.opendatakit.httpclientandroidlib.client.AuthCache; import org.opendatakit.httpclientandroidlib.client.CredentialsProvider; import org.opendatakit.httpclientandroidlib.client.HttpClient; import org.opendatakit.httpclientandroidlib.client.methods.HttpGet; import org.opendatakit.httpclientandroidlib.client.methods.HttpHead; import org.opendatakit.httpclientandroidlib.client.methods.HttpPost; import org.opendatakit.httpclientandroidlib.client.params.AuthPolicy; import org.opendatakit.httpclientandroidlib.client.params.ClientPNames; import org.opendatakit.httpclientandroidlib.client.params.CookiePolicy; import org.opendatakit.httpclientandroidlib.client.params.HttpClientParams; import org.opendatakit.httpclientandroidlib.client.protocol.ClientContext; import org.opendatakit.httpclientandroidlib.conn.ClientConnectionManager; import org.opendatakit.httpclientandroidlib.impl.auth.BasicScheme; import org.opendatakit.httpclientandroidlib.impl.client.BasicAuthCache; import org.opendatakit.httpclientandroidlib.impl.client.DefaultHttpClient; import org.opendatakit.httpclientandroidlib.params.BasicHttpParams; import org.opendatakit.httpclientandroidlib.params.HttpConnectionParams; import org.opendatakit.httpclientandroidlib.params.HttpParams; import org.opendatakit.httpclientandroidlib.protocol.HttpContext; import org.xmlpull.v1.XmlPullParser; import android.content.SharedPreferences; import android.net.Uri; import android.preference.PreferenceManager; import android.text.format.DateFormat; import android.util.Log; /** * Common utility methods for managing the credentials associated with the * request context and constructing http context, client and request with the * proper parameters and OpenRosa headers. * * @author mitchellsundt@gmail.com */ public final class WebUtils { public static final String t = "WebUtils"; public static final String OPEN_ROSA_VERSION_HEADER = "X-OpenRosa-Version"; public static final String OPEN_ROSA_VERSION = "1.0"; private static final String DATE_HEADER = "Date"; public static final String HTTP_CONTENT_TYPE_TEXT_XML = "text/xml"; public static final int CONNECTION_TIMEOUT = 30000; public static final String ACCEPT_ENCODING_HEADER = "Accept-Encoding"; public static final String GZIP_CONTENT_ENCODING = "gzip"; private static ClientConnectionManager httpConnectionManager = null; public static final List<AuthScope> buildAuthScopes(String host) { List<AuthScope> asList = new ArrayList<AuthScope>(); AuthScope a; // allow digest auth on any port... a = new AuthScope(host, -1, null, AuthPolicy.DIGEST); asList.add(a); // and allow basic auth on the standard TLS/SSL ports... a = new AuthScope(host, 443, null, AuthPolicy.BASIC); asList.add(a); a = new AuthScope(host, 8443, null, AuthPolicy.BASIC); asList.add(a); return asList; } public static final void clearAllCredentials() { CredentialsProvider credsProvider = Collect.getInstance() .getCredentialsProvider(); Log.i(t, "clearAllCredentials"); credsProvider.clear(); } public static final boolean hasCredentials(String userEmail, String host) { CredentialsProvider credsProvider = Collect.getInstance() .getCredentialsProvider(); List<AuthScope> asList = buildAuthScopes(host); boolean hasCreds = true; for (AuthScope a : asList) { Credentials c = credsProvider.getCredentials(a); if (c == null) { hasCreds = false; continue; } } return hasCreds; } /** * Remove all credentials for accessing the specified host. * * @param host */ public static final void clearHostCredentials(String host) { CredentialsProvider credsProvider = Collect.getInstance() .getCredentialsProvider(); Log.i(t, "clearHostCredentials: " + host); List<AuthScope> asList = buildAuthScopes(host); for (AuthScope a : asList) { credsProvider.setCredentials(a, null); } } /** * Remove all credentials for accessing the specified host and, if the * username is not null or blank then add a (username, password) credential * for accessing this host. * * @param username * @param password * @param host */ public static final void addCredentials(String username, String password, String host) { // to ensure that this is the only authentication available for this // host... clearHostCredentials(host); if (username != null && username.trim().length() != 0) { Log.i(t, "adding credential for host: " + host + " username:" + username); Credentials c = new UsernamePasswordCredentials(username, password); addCredentials(c, host); } } private static final void addCredentials(Credentials c, String host) { CredentialsProvider credsProvider = Collect.getInstance() .getCredentialsProvider(); List<AuthScope> asList = buildAuthScopes(host); for (AuthScope a : asList) { credsProvider.setCredentials(a, c); } } public static final void enablePreemptiveBasicAuth( HttpContext localContext, String host) { AuthCache ac = (AuthCache) localContext .getAttribute(ClientContext.AUTH_CACHE); HttpHost h = new HttpHost(host); if (ac == null) { ac = new BasicAuthCache(); localContext.setAttribute(ClientContext.AUTH_CACHE, ac); } List<AuthScope> asList = buildAuthScopes(host); for (AuthScope a : asList) { if (a.getScheme() == AuthPolicy.BASIC) { ac.put(h, new BasicScheme()); } } } private static final void setOpenRosaHeaders(HttpRequest req) { req.setHeader(OPEN_ROSA_VERSION_HEADER, OPEN_ROSA_VERSION); GregorianCalendar g = new GregorianCalendar(TimeZone.getTimeZone("GMT")); g.setTime(new Date()); req.setHeader(DATE_HEADER, DateFormat.format("E, dd MMM yyyy hh:mm:ss zz", g).toString()); } public static final HttpHead createOpenRosaHttpHead(Uri u) { HttpHead req = new HttpHead(URI.create(u.toString())); setOpenRosaHeaders(req); return req; } public static final HttpGet createOpenRosaHttpGet(URI uri) { HttpGet req = new HttpGet(); setOpenRosaHeaders(req); setGoogleHeaders(req); req.setURI(uri); return req; } public static final void setGoogleHeaders(HttpRequest req) { SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(Collect.getInstance().getApplicationContext()); String protocol = settings.getString(PreferencesActivity.KEY_PROTOCOL, Collect.getInstance().getString(R.string.protocol_odk_default)); // TODO: this doesn't exist.... // if ( protocol.equals(PreferencesActivity.PROTOCOL_GOOGLE) ) { // String auth = settings.getString(PreferencesActivity.KEY_AUTH, ""); // if ((auth != null) && (auth.length() > 0)) { // req.setHeader("Authorization", "GoogleLogin auth=" + auth); // } // } } public static final HttpPost createOpenRosaHttpPost(Uri u) { HttpPost req = new HttpPost(URI.create(u.toString())); setOpenRosaHeaders(req); setGoogleHeaders(req); return req; } /** * Create an httpClient with connection timeouts and other parameters set. * Save and reuse the connection manager across invocations (this is what * requires synchronized access). * * @param timeout * @return HttpClient properly configured. */ public static final synchronized HttpClient createHttpClient(int timeout) { // configure connection HttpParams params = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(params, timeout); HttpConnectionParams.setSoTimeout(params, 2 * timeout); // support redirecting to handle http: => https: transition HttpClientParams.setRedirecting(params, true); // support authenticating HttpClientParams.setAuthenticating(params, true); HttpClientParams.setCookiePolicy(params, CookiePolicy.BROWSER_COMPATIBILITY); // if possible, bias toward digest auth (may not be in 4.0 beta 2) List<String> authPref = new ArrayList<String>(); authPref.add(AuthPolicy.DIGEST); authPref.add(AuthPolicy.BASIC); // does this work in Google's 4.0 beta 2 snapshot? params.setParameter(AuthPNames.TARGET_AUTH_PREF, authPref); params.setParameter(ClientPNames.MAX_REDIRECTS, 1); params.setParameter(ClientPNames.ALLOW_CIRCULAR_REDIRECTS, true); // setup client DefaultHttpClient httpclient; // reuse the connection manager across all clients this ODK Collect // creates. if (httpConnectionManager == null) { // let Apache stack create a connection manager. httpclient = new DefaultHttpClient(params); httpConnectionManager = httpclient.getConnectionManager(); } else { // reuse the connection manager we already got. httpclient = new DefaultHttpClient(httpConnectionManager, params); } return httpclient; } /** * Utility to ensure that the entity stream of a response is drained of * bytes. * * @param response */ public static final void discardEntityBytes(HttpResponse response) { // may be a server that does not handle HttpEntity entity = response.getEntity(); if (entity != null) { try { // have to read the stream in order to reuse the connection InputStream is = response.getEntity().getContent(); // read to end of stream... final long count = 1024L; while (is.skip(count) == count) ; is.close(); } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } } /** * Common method for returning a parsed xml document given a url and the * http context and client objects involved in the web connection. * * @param urlString * @param localContext * @param httpclient * @return */ public static DocumentFetchResult getXmlDocument(String urlString, HttpContext localContext, HttpClient httpclient) { URI u = null; try { URL url = new URL(urlString); u = url.toURI(); } catch (Exception e) { e.printStackTrace(); return new DocumentFetchResult(e.getLocalizedMessage() // + app.getString(R.string.while_accessing) + urlString); + ("while accessing") + urlString, 0); } if (u.getHost() == null ) { return new DocumentFetchResult("Invalid server URL (no hostname): " + urlString, 0); } // if https then enable preemptive basic auth... if (u.getScheme().equals("https")) { enablePreemptiveBasicAuth(localContext, u.getHost()); } // set up request... HttpGet req = WebUtils.createOpenRosaHttpGet(u); req.addHeader(WebUtils.ACCEPT_ENCODING_HEADER, WebUtils.GZIP_CONTENT_ENCODING); HttpResponse response = null; try { response = httpclient.execute(req, localContext); int statusCode = response.getStatusLine().getStatusCode(); HttpEntity entity = response.getEntity(); if (statusCode != HttpStatus.SC_OK) { WebUtils.discardEntityBytes(response); if (statusCode == HttpStatus.SC_UNAUTHORIZED) { // clear the cookies -- should not be necessary? Collect.getInstance().getCookieStore().clear(); } String webError = response.getStatusLine().getReasonPhrase() + " (" + statusCode + ")"; return new DocumentFetchResult(u.toString() + " responded with: " + webError, statusCode); } if (entity == null) { String error = "No entity body returned from: " + u.toString(); Log.e(t, error); return new DocumentFetchResult(error, 0); } if (!entity.getContentType().getValue().toLowerCase(Locale.ENGLISH) .contains(WebUtils.HTTP_CONTENT_TYPE_TEXT_XML)) { WebUtils.discardEntityBytes(response); String error = "ContentType: " + entity.getContentType().getValue() + " returned from: " + u.toString() + " is not text/xml. This is often caused a network proxy. Do you need to login to your network?"; Log.e(t, error); return new DocumentFetchResult(error, 0); } // parse response Document doc = null; try { InputStream is = null; InputStreamReader isr = null; try { is = entity.getContent(); Header contentEncoding = entity.getContentEncoding(); if ( contentEncoding != null && contentEncoding.getValue().equalsIgnoreCase(WebUtils.GZIP_CONTENT_ENCODING) ) { is = new GZIPInputStream(is); } isr = new InputStreamReader(is, "UTF-8"); doc = new Document(); KXmlParser parser = new KXmlParser(); parser.setInput(isr); parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, true); doc.parse(parser); isr.close(); isr = null; } finally { if (isr != null) { try { // ensure stream is consumed... final long count = 1024L; while (isr.skip(count) == count) ; } catch (Exception e) { // no-op } try { isr.close(); } catch (Exception e) { // no-op } } if (is != null) { try { is.close(); } catch (Exception e) { // no-op } } } } catch (Exception e) { e.printStackTrace(); String error = "Parsing failed with " + e.getMessage() + "while accessing " + u.toString(); Log.e(t, error); return new DocumentFetchResult(error, 0); } boolean isOR = false; Header[] fields = response .getHeaders(WebUtils.OPEN_ROSA_VERSION_HEADER); if (fields != null && fields.length >= 1) { isOR = true; boolean versionMatch = false; boolean first = true; StringBuilder b = new StringBuilder(); for (Header h : fields) { if (WebUtils.OPEN_ROSA_VERSION.equals(h.getValue())) { versionMatch = true; break; } if (!first) { b.append("; "); } first = false; b.append(h.getValue()); } if (!versionMatch) { Log.w(t, WebUtils.OPEN_ROSA_VERSION_HEADER + " unrecognized version(s): " + b.toString()); } } return new DocumentFetchResult(doc, isOR); } catch (Exception e) { clearHttpConnectionManager(); e.printStackTrace(); String cause; Throwable c = e; while (c.getCause() != null) { c = c.getCause(); } cause = c.toString(); String error = "Error: " + cause + " while accessing " + u.toString(); Log.w(t, error); return new DocumentFetchResult(error, 0); } } public static void clearHttpConnectionManager() { // If we get an unexpected exception, the safest thing is to close // all connections // so that if there is garbage on the connection we ensure it is // removed. This // is especially important if the connection times out. if ( httpConnectionManager != null ) { httpConnectionManager.shutdown(); httpConnectionManager = null; } } }
Java
/* * Copyright (C) 2009 University of Washington * * 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 org.odk.collect.android.utilities; import java.net.MalformedURLException; import java.net.URL; public class UrlUtils { public static boolean isValidUrl(String url) { try { new URL(url); return true; } catch (MalformedURLException e) { return false; } } }
Java
/* * Copyright (C) 2011 University of Washington * * 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 org.odk.collect.android.utilities; import org.kxml2.kdom.Document; public class DocumentFetchResult { public final String errorMessage; public final int responseCode; public final Document doc; public final boolean isOpenRosaResponse; public DocumentFetchResult(String msg, int response) { responseCode = response; errorMessage = msg; doc = null; isOpenRosaResponse = false; } public DocumentFetchResult(Document doc, boolean isOpenRosaResponse) { responseCode = 0; errorMessage = null; this.doc = doc; this.isOpenRosaResponse = isOpenRosaResponse; } }
Java
/* * Copyright (C) 2013 University of Washington * * 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 org.odk.collect.android.utilities; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.UnsupportedEncodingException; import org.odk.collect.android.application.Collect; import android.util.Log; /** * Used for logging data to log files that could be retrieved after a field deployment. * The initial use for this is to assist in diagnosing a report of a cached geopoints * being reported, causing stale GPS coordinates to be recorded (issue 780). * * @author mitchellsundt@gmail.com * */ public class InfoLogger { private static final String t = "InfoLogger"; private static final String LOG_DIRECTORY = "logging"; private static final String LOG_FILE = "geotrace.log"; public static final void geolog(String msg) { geologToLogcat(msg); } private static final void geologToLogcat(String msg) { Log.i(t, msg); } @SuppressWarnings("unused") private static final void geologToFile(String msg) { File dir = new File( Collect.ODK_ROOT + File.separator + LOG_DIRECTORY ); if ( !dir.exists() ) { dir.mkdirs(); } File log = new File(dir, LOG_FILE); FileOutputStream fo = null; try { fo = new FileOutputStream(log, true); msg = msg + "\n"; fo.write( msg.getBytes("UTF-8") ); fo.flush(); fo.close(); } catch (FileNotFoundException e) { e.printStackTrace(); Log.e(t, "exception: " + e.toString()); } catch (UnsupportedEncodingException e) { e.printStackTrace(); Log.e(t, "exception: " + e.toString()); } catch (IOException e) { e.printStackTrace(); Log.e(t, "exception: " + e.toString()); } } }
Java
/* * Copyright (C) 2012 University of Washington * * 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 org.odk.collect.android.database; import java.io.File; import java.util.Calendar; import java.util.LinkedList; import org.javarosa.core.model.FormIndex; import org.odk.collect.android.application.Collect; import org.odk.collect.android.logic.FormController; import android.app.Activity; import android.content.ContentValues; import android.database.SQLException; import android.database.sqlite.SQLiteConstraintException; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteException; /** * Log all user interface activity into a SQLite database. Logging is disabled by default. * * The logging database will be "/sdcard/odk/log/activityLog.db" * * Logging is enabled if the file "/sdcard/odk/log/enabled" exists. * * @author mitchellsundt@gmail.com * @author Carl Hartung (carlhartung@gmail.com) * */ public final class ActivityLogger { private static class DatabaseHelper extends ODKSQLiteOpenHelper { DatabaseHelper() { super(Collect.LOG_PATH, DATABASE_NAME, null, DATABASE_VERSION); new File(Collect.LOG_PATH).mkdirs(); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL(DATABASE_CREATE); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE); onCreate(db); } } /** * The minimum delay, in milliseconds, for a scroll action to be considered new. */ private static final long MIN_SCROLL_DELAY = 400L; /** * The maximum size of the scroll action buffer. After it reaches this size, * it will be flushed. */ private static final int MAX_SCROLL_ACTION_BUFFER_SIZE = 8; private static final String DATABASE_TABLE = "log"; private static final String ENABLE_LOGGING = "enabled"; private static final int DATABASE_VERSION = 1; private static final String DATABASE_NAME = "activityLog.db"; // Database columns private static final String ID = "_id"; private static final String TIMESTAMP = "timestamp"; private static final String DEVICEID = "device_id"; private static final String CLASS = "class"; private static final String CONTEXT = "context"; private static final String ACTION = "action"; private static final String INSTANCE_PATH = "instance_path"; private static final String QUESTION = "question"; private static final String PARAM1 = "param1"; private static final String PARAM2 = "param2"; private static final String DATABASE_CREATE = "create table " + DATABASE_TABLE + " (" + ID + " integer primary key autoincrement, " + TIMESTAMP + " integer not null, " + DEVICEID + " text not null, " + CLASS + " text not null, " + CONTEXT + " text not null, " + ACTION + " text, " + INSTANCE_PATH + " text, " + QUESTION + " text, " + PARAM1 + " text, " + PARAM2 + " text);"; private final boolean mLoggingEnabled; private final String mDeviceId; private DatabaseHelper mDbHelper = null; private SQLiteDatabase mDb = null; private boolean mIsOpen = false; // We buffer scroll actions to make sure there aren't too many pauses // during scrolling. This list is flushed every time any other type of // action is logged. private LinkedList<ContentValues> mScrollActions = new LinkedList<ContentValues>(); public ActivityLogger(String deviceId) { this.mDeviceId = deviceId; mLoggingEnabled = new File(Collect.LOG_PATH, ENABLE_LOGGING).exists(); open(); } public boolean isOpen() { return mLoggingEnabled && mIsOpen; } public void open() throws SQLException { if (!mLoggingEnabled || mIsOpen) return; try { mDbHelper = new DatabaseHelper(); mDb = mDbHelper.getWritableDatabase(); mIsOpen = true; } catch (SQLiteException e) { System.err.println("Error: " + e.getMessage()); mIsOpen = false; } } // cached to improve logging performance... // only access these through getXPath(FormIndex index); private FormIndex cachedXPathIndex = null; private String cachedXPathValue = null; // DO NOT CALL THIS OUTSIDE OF synchronized(mScrollActions) !!!! // DO NOT CALL THIS OUTSIDE OF synchronized(mScrollActions) !!!! // DO NOT CALL THIS OUTSIDE OF synchronized(mScrollActions) !!!! // DO NOT CALL THIS OUTSIDE OF synchronized(mScrollActions) !!!! private String getXPath(FormIndex index) { if ( index == cachedXPathIndex ) return cachedXPathValue; cachedXPathIndex = index; cachedXPathValue = Collect.getInstance().getFormController().getXPath(index); return cachedXPathValue; } private void log(String object, String context, String action, String instancePath, FormIndex index, String param1, String param2) { if (!isOpen()) return; ContentValues cv = new ContentValues(); cv.put(DEVICEID, mDeviceId); cv.put(CLASS, object); cv.put(CONTEXT, context); cv.put(ACTION, action); cv.put(INSTANCE_PATH, instancePath); cv.put(PARAM1, param1); cv.put(PARAM2, param2); cv.put(TIMESTAMP, Calendar.getInstance().getTimeInMillis()); insertContentValues(cv, index); } public void logScrollAction(Object t, int distance) { if (!isOpen()) return; synchronized(mScrollActions) { long timeStamp = Calendar.getInstance().getTimeInMillis(); // Check to see if we can add this scroll action to the previous action. if (!mScrollActions.isEmpty()) { ContentValues lastCv = mScrollActions.get(mScrollActions.size() - 1); long oldTimeStamp = lastCv.getAsLong(TIMESTAMP); int oldDistance = Integer.parseInt(lastCv.getAsString(PARAM1)); if (Integer.signum(distance) == Integer.signum(oldDistance) && timeStamp - oldTimeStamp < MIN_SCROLL_DELAY) { lastCv.put(PARAM1, oldDistance + distance); lastCv.put(TIMESTAMP, timeStamp); return; } } if (mScrollActions.size() >= MAX_SCROLL_ACTION_BUFFER_SIZE) { insertContentValues(null, null); // flush scroll list... } String idx = ""; String instancePath = ""; FormController formController = Collect.getInstance().getFormController(); if ( formController != null ) { idx = getXPath(formController.getFormIndex()); instancePath = formController.getInstancePath().getAbsolutePath(); } // Add a new scroll action to the buffer. ContentValues cv = new ContentValues(); cv.put(DEVICEID, mDeviceId); cv.put(CLASS, t.getClass().getName()); cv.put(CONTEXT, "scroll"); cv.put(ACTION, ""); cv.put(PARAM1, distance); cv.put(QUESTION, idx); cv.put(INSTANCE_PATH, instancePath); cv.put(TIMESTAMP, timeStamp); cv.put(PARAM2, timeStamp); mScrollActions.add(cv); } } private void insertContentValues(ContentValues cv, FormIndex index) { synchronized(mScrollActions) { try { while ( !mScrollActions.isEmpty() ) { ContentValues scv = mScrollActions.removeFirst(); mDb.insert(DATABASE_TABLE, null, scv); } if ( cv != null ) { String idx = ""; if ( index != null ) { idx = getXPath(index); } cv.put(QUESTION,idx); mDb.insert(DATABASE_TABLE, null, cv); } } catch (SQLiteConstraintException e) { System.err.println("Error: " + e.getMessage()); } } } // Convenience methods public void logOnStart(Activity a) { log( a.getClass().getName(), "onStart", null, null, null, null, null); } public void logOnStop(Activity a) { log( a.getClass().getName(), "onStop", null, null, null, null, null); } public void logAction(Object t, String context, String action) { log( t.getClass().getName(), context, action, null, null, null, null); } public void logActionParam(Object t, String context, String action, String param1) { log( t.getClass().getName(), context, action, null, null, param1, null); } public void logInstanceAction(Object t, String context, String action) { FormIndex index = null; String instancePath = null; FormController formController = Collect.getInstance().getFormController(); if ( formController != null ) { index = formController.getFormIndex(); File instanceFile = formController.getInstancePath(); if ( instanceFile != null ) { instancePath = instanceFile.getAbsolutePath(); } } log( t.getClass().getName(), context, action, instancePath, index, null, null); } public void logInstanceAction(Object t, String context, String action, FormIndex index) { String instancePath = null; FormController formController = Collect.getInstance().getFormController(); if ( formController != null ) { index = formController.getFormIndex(); instancePath = formController.getInstancePath().getAbsolutePath(); } log( t.getClass().getName(), context, action, instancePath, index, null, null); } }
Java
package org.odk.collect.android.database; import java.math.BigInteger; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import org.odk.collect.android.application.Collect; import android.content.ContentValues; import android.database.Cursor; import android.database.SQLException; import android.database.sqlite.SQLiteDatabase; import android.util.Log; public class ItemsetDbAdapter { public static final String KEY_ID = "_id"; private static final String TAG = "ItemsetDbAdapter"; private DatabaseHelper mDbHelper; private SQLiteDatabase mDb; private static final String DATABASE_NAME = "itemsets.db"; private static final String DATABASE_TABLE = "itemset_"; private static final int DATABASE_VERSION = 2; private static final String ITEMSET_TABLE = "itemsets"; private static final String KEY_ITEMSET_HASH = "hash"; private static final String KEY_PATH = "path"; private static final String CREATE_ITEMSET_TABLE = "create table " + ITEMSET_TABLE + " (_id integer primary key autoincrement, " + KEY_ITEMSET_HASH + " text, " + KEY_PATH + " text " + ");"; /** * This class helps open, create, and upgrade the database file. */ private static class DatabaseHelper extends ODKSQLiteOpenHelper { DatabaseHelper() { super(Collect.METADATA_PATH, DATABASE_NAME, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase db) { // create table to keep track of the itemsets db.execSQL(CREATE_ITEMSET_TABLE); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { Log.w(TAG, "Upgrading database from version " + oldVersion + " to " + newVersion + ", which will destroy all old data"); // first drop all of our generated itemset tables Cursor c = db.query(ITEMSET_TABLE, null, null, null, null, null, null); if (c != null) { c.move(-1); while (c.moveToNext()) { String table = c.getString(c.getColumnIndex(KEY_ITEMSET_HASH)); db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE + table); } c.close(); } // then drop the table tracking itemsets itself db.execSQL("DROP TABLE IF EXISTS " + ITEMSET_TABLE); onCreate(db); } } public ItemsetDbAdapter() { } /** * Open the database. If it cannot be opened, try to create a new instance * of the database. If it cannot be created, throw an exception to signal * the failure * * @return this (self reference, allowing this to be chained in an * initialization call) * @throws SQLException if the database could be neither opened or created */ public ItemsetDbAdapter open() throws SQLException { mDbHelper = new DatabaseHelper(); mDb = mDbHelper.getWritableDatabase(); return this; } public void close() { mDbHelper.close(); } public boolean createTable(String formHash, String pathHash, String[] columns, String path) { StringBuilder sb = new StringBuilder(); // get md5 of the path to itemset.csv, which is unique per form // the md5 is easier to use because it doesn't have chars like '/' sb.append("create table " + DATABASE_TABLE + pathHash + " (_id integer primary key autoincrement "); for (int j = 0; j < columns.length; j++) { // add double quotes in case the column is of label:lang sb.append(" , \"" + columns[j] + "\" text "); // create database with first line } sb.append(");"); String tableCreate = sb.toString(); Log.i(TAG, "create string: " + tableCreate); mDb.execSQL(tableCreate); ContentValues cv = new ContentValues(); cv.put(KEY_ITEMSET_HASH, formHash); cv.put(KEY_PATH, path); mDb.insert(ITEMSET_TABLE, null, cv); return true; } public boolean addRow(String tableName, String[] columns, String[] newRow) { ContentValues cv = new ContentValues(); // rows don't necessarily use all the columns // but a column is guaranteed to exist for a row (or else blow up) for (int i = 0; i < newRow.length; i++) { cv.put("\"" + columns[i] + "\"", newRow[i]); } mDb.insert(DATABASE_TABLE + tableName, null, cv); return true; } public boolean tableExists(String tableName) { // select name from sqlite_master where type = 'table' String selection = "type=? and name=?"; String selectionArgs[] = { "table", DATABASE_TABLE + tableName }; Cursor c = mDb.query("sqlite_master", null, selection, selectionArgs, null, null, null); boolean exists = false; if (c.getCount() == 1) { exists = true; } c.close(); return exists; } public void beginTransaction() { mDb.execSQL("BEGIN"); } public void commit() { mDb.execSQL("COMMIT"); } public Cursor query(String hash, String selection, String[] selectionArgs) throws SQLException { Cursor mCursor = mDb.query(true, DATABASE_TABLE + hash, null, selection, selectionArgs, null, null, null, null); return mCursor; } public void dropTable(String pathHash, String path) { // drop the table mDb.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE + pathHash); // and remove the entry from the itemsets table String where = KEY_PATH + "=?"; String[] whereArgs = { path }; mDb.delete(ITEMSET_TABLE, where, whereArgs); } public Cursor getItemsets(String path) { String selection = KEY_PATH + "=?"; String[] selectionArgs = { path }; Cursor c = mDb.query(ITEMSET_TABLE, null, selection, selectionArgs, null, null, null); return c; } public void delete(String path) { Cursor c = getItemsets(path); if (c != null) { if (c.getCount() == 1) { c.moveToFirst(); String table = getMd5FromString(c.getString(c.getColumnIndex(KEY_PATH))); mDb.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE + table); } c.close(); } String where = KEY_PATH + "=?"; String[] whereArgs = { path }; mDb.delete(ITEMSET_TABLE, where, whereArgs); } public static String getMd5FromString(String toEncode) { MessageDigest md = null; try { md = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); Log.e("MD5", e.getMessage()); } md.update(toEncode.getBytes()); byte[] digest = md.digest(); BigInteger bigInt = new BigInteger(1,digest); String hashtext = bigInt.toString(16); return hashtext; } }
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 org.odk.collect.android.database; import java.io.File; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteDatabase.CursorFactory; import android.database.sqlite.SQLiteException; import android.os.Environment; import android.util.Log; import org.odk.collect.android.R; import org.odk.collect.android.application.Collect; /** * We've taken this from Android's SQLiteOpenHelper. However, we can't appropriately lock the * database so there may be issues if a thread opens the database read-only and another thread tries * to open the database read/write. I don't think this will ever happen in ODK, though. (fingers * crossed). */ /** * A helper class to manage database creation and version management. You create a subclass * implementing {@link #onCreate}, {@link #onUpgrade} and optionally {@link #onOpen}, and this class * takes care of opening the database if it exists, creating it if it does not, and upgrading it as * necessary. Transactions are used to make sure the database is always in a sensible state. * <p> * For an example, see the NotePadProvider class in the NotePad sample application, in the * <em>samples/</em> directory of the SDK. * </p> */ public abstract class ODKSQLiteOpenHelper { private static final String t = ODKSQLiteOpenHelper.class.getSimpleName(); private final String mPath; private final String mName; private final CursorFactory mFactory; private final int mNewVersion; private SQLiteDatabase mDatabase = null; private boolean mIsInitializing = false; /** * Create a helper object to create, open, and/or manage a database. The database is not * actually created or opened until one of {@link #getWritableDatabase} or * {@link #getReadableDatabase} is called. * * @param path to the file * @param name of the database file, or null for an in-memory database * @param factory to use for creating cursor objects, or null for the default * @param version number of the database (starting at 1); if the database is older, * {@link #onUpgrade} will be used to upgrade the database */ public ODKSQLiteOpenHelper(String path, String name, CursorFactory factory, int version) { if (version < 1) throw new IllegalArgumentException("Version must be >= 1, was " + version); mPath = path; mName = name; mFactory = factory; mNewVersion = version; } /** * Create and/or open a database that will be used for reading and writing. Once opened * successfully, the database is cached, so you can call this method every time you need to * write to the database. Make sure to call {@link #close} when you no longer need it. * <p> * Errors such as bad permissions or a full disk may cause this operation to fail, but future * attempts may succeed if the problem is fixed. * </p> * * @throws SQLiteException if the database cannot be opened for writing * @return a read/write database object valid until {@link #close} is called */ public synchronized SQLiteDatabase getWritableDatabase() { if (mDatabase != null && mDatabase.isOpen() && !mDatabase.isReadOnly()) { return mDatabase; // The database is already open for business } if (mIsInitializing) { throw new IllegalStateException("getWritableDatabase called recursively"); } // If we have a read-only database open, someone could be using it // (though they shouldn't), which would cause a lock to be held on // the file, and our attempts to open the database read-write would // fail waiting for the file lock. To prevent that, we acquire the // lock on the read-only database, which shuts out other users. boolean success = false; SQLiteDatabase db = null; // if (mDatabase != null) mDatabase.lock(); try { mIsInitializing = true; if (mName == null) { db = SQLiteDatabase.create(null); } else { db = SQLiteDatabase.openOrCreateDatabase(mPath + File.separator + mName, mFactory); // db = mContext.openOrCreateDatabase(mName, 0, mFactory); } int version = db.getVersion(); if (version != mNewVersion) { db.beginTransaction(); try { if (version == 0) { onCreate(db); } else { onUpgrade(db, version, mNewVersion); } db.setVersion(mNewVersion); db.setTransactionSuccessful(); } finally { db.endTransaction(); } } onOpen(db); success = true; return db; } finally { mIsInitializing = false; if (success) { if (mDatabase != null) { try { mDatabase.close(); } catch (Exception e) { } // mDatabase.unlock(); } mDatabase = db; } else { // if (mDatabase != null) mDatabase.unlock(); if (db != null) db.close(); } } } /** * Create and/or open a database. This will be the same object returned by * {@link #getWritableDatabase} unless some problem, such as a full disk, requires the database * to be opened read-only. In that case, a read-only database object will be returned. If the * problem is fixed, a future call to {@link #getWritableDatabase} may succeed, in which case * the read-only database object will be closed and the read/write object will be returned in * the future. * * @throws SQLiteException if the database cannot be opened * @return a database object valid until {@link #getWritableDatabase} or {@link #close} is * called. */ public synchronized SQLiteDatabase getReadableDatabase() { if (mDatabase != null && mDatabase.isOpen()) { return mDatabase; // The database is already open for business } if (mIsInitializing) { throw new IllegalStateException("getReadableDatabase called recursively"); } try { return getWritableDatabase(); } catch (SQLiteException e) { if (mName == null) throw e; // Can't open a temp database read-only! Log.e(t, "Couldn't open " + mName + " for writing (will try read-only):", e); } SQLiteDatabase db = null; try { mIsInitializing = true; String path = mPath + File.separator + mName; // mContext.getDatabasePath(mName).getPath(); try { db = SQLiteDatabase.openDatabase(path, mFactory, SQLiteDatabase.OPEN_READONLY); } catch (RuntimeException e) { Log.e(t, e.getMessage(), e); String cardstatus = Environment.getExternalStorageState(); if (!cardstatus.equals(Environment.MEDIA_MOUNTED)) { throw new RuntimeException(Collect.getInstance().getString(R.string.sdcard_unmounted, cardstatus)); } else { throw e; } } if (db.getVersion() != mNewVersion) { throw new SQLiteException("Can't upgrade read-only database from version " + db.getVersion() + " to " + mNewVersion + ": " + path); } onOpen(db); Log.w(t, "Opened " + mName + " in read-only mode"); mDatabase = db; return mDatabase; } finally { mIsInitializing = false; if (db != null && db != mDatabase) db.close(); } } /** * Close any open database object. */ public synchronized void close() { if (mIsInitializing) throw new IllegalStateException("Closed during initialization"); if (mDatabase != null && mDatabase.isOpen()) { mDatabase.close(); mDatabase = null; } } /** * Called when the database is created for the first time. This is where the creation of tables * and the initial population of the tables should happen. * * @param db The database. */ public abstract void onCreate(SQLiteDatabase db); /** * Called when the database needs to be upgraded. The implementation should use this method to * drop tables, add tables, or do anything else it needs to upgrade to the new schema version. * <p> * The SQLite ALTER TABLE documentation can be found <a * href="http://sqlite.org/lang_altertable.html">here</a>. If you add new columns you can use * ALTER TABLE to insert them into a live table. If you rename or remove columns you can use * ALTER TABLE to rename the old table, then create the new table and then populate the new * table with the contents of the old table. * * @param db The database. * @param oldVersion The old database version. * @param newVersion The new database version. */ public abstract void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion); /** * Called when the database has been opened. Override method should check * {@link SQLiteDatabase#isReadOnly} before updating the database. * * @param db The database. */ public void onOpen(SQLiteDatabase db) { } }
Java
/* * Copyright (C) 2011 University of Washington * * 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 org.odk.collect.android.widgets; import java.io.File; import java.util.ArrayList; import java.util.List; import org.javarosa.core.model.SelectChoice; import org.javarosa.core.model.data.IAnswerData; import org.javarosa.core.model.data.SelectMultiData; import org.javarosa.core.model.data.helper.Selection; import org.javarosa.core.reference.InvalidReferenceException; import org.javarosa.core.reference.ReferenceManager; import org.javarosa.form.api.FormEntryCaption; import org.javarosa.form.api.FormEntryPrompt; import org.javarosa.xpath.expr.XPathFuncExpr; import org.odk.collect.android.R; import org.odk.collect.android.application.Collect; import org.odk.collect.android.external.ExternalDataUtil; import org.odk.collect.android.external.ExternalSelectChoice; import org.odk.collect.android.utilities.FileUtils; import android.content.Context; import android.graphics.Bitmap; import android.graphics.Typeface; import android.util.Log; import android.util.TypedValue; import android.view.Display; import android.view.Gravity; import android.view.View; import android.view.WindowManager; import android.view.inputmethod.InputMethodManager; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.ImageView; import android.widget.ImageView.ScaleType; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.TextView; /** * ListMultiWidget handles multiple selection fields using check boxes. The check boxes are aligned * horizontally. They are typically meant to be used in a field list, where multiple questions with * the same multiple choice answers can sit on top of each other and make a grid of buttons that is * easy to navigate quickly. Optionally, you can turn off the labels. This would be done if a label * widget was at the top of your field list to provide the labels. If audio or video are specified * in the select answers they are ignored. This class is almost identical to ListWidget, except it * uses checkboxes. It also did not require a custom clickListener class. * * @author Jeff Beorse (jeff@beorse.net) */ public class ListMultiWidget extends QuestionWidget { private static final String t = "ListMultiWidget"; // Holds the entire question and answers. It is a horizontally aligned linear layout // needed because it is created in the super() constructor via addQuestionText() call. LinearLayout questionLayout; private boolean mCheckboxInit = true; private List<SelectChoice> mItems; // may take a while to compute... private ArrayList<CheckBox> mCheckboxes; @SuppressWarnings("unchecked") public ListMultiWidget(Context context, FormEntryPrompt prompt, boolean displayLabel) { super(context, prompt); // SurveyCTO-added support for dynamic select content (from .csv files) XPathFuncExpr xPathFuncExpr = ExternalDataUtil.getSearchXPathExpression(prompt.getAppearanceHint()); if (xPathFuncExpr != null) { mItems = ExternalDataUtil.populateExternalChoices(prompt, xPathFuncExpr); } else { mItems = prompt.getSelectChoices(); } mCheckboxes = new ArrayList<CheckBox>(); mPrompt = prompt; // Layout holds the horizontal list of buttons LinearLayout buttonLayout = new LinearLayout(context); List<Selection> ve = new ArrayList<Selection>(); if (prompt.getAnswerValue() != null) { ve = (List<Selection>) prompt.getAnswerValue().getValue(); } if (mItems != null) { for (int i = 0; i < mItems.size(); i++) { CheckBox c = new CheckBox(getContext()); c.setTag(Integer.valueOf(i)); c.setId(QuestionWidget.newUniqueId()); c.setFocusable(!prompt.isReadOnly()); c.setEnabled(!prompt.isReadOnly()); for (int vi = 0; vi < ve.size(); vi++) { // match based on value, not key if (mItems.get(i).getValue().equals(ve.get(vi).getValue())) { c.setChecked(true); break; } } mCheckboxes.add(c); // when clicked, check for readonly before toggling c.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (!mCheckboxInit && mPrompt.isReadOnly()) { if (buttonView.isChecked()) { buttonView.setChecked(false); Collect.getInstance().getActivityLogger().logInstanceAction(this, "onItemClick.deselect", mItems.get((Integer)buttonView.getTag()).getValue(), mPrompt.getIndex()); } else { buttonView.setChecked(true); Collect.getInstance().getActivityLogger().logInstanceAction(this, "onItemClick.select", mItems.get((Integer)buttonView.getTag()).getValue(), mPrompt.getIndex()); } } } }); String imageURI; if (mItems.get(i) instanceof ExternalSelectChoice) { imageURI = ((ExternalSelectChoice) mItems.get(i)).getImage(); } else { imageURI = prompt.getSpecialFormSelectChoiceText(mItems.get(i), FormEntryCaption.TEXT_FORM_IMAGE); } // build image view (if an image is provided) ImageView mImageView = null; TextView mMissingImage = null; final int labelId = QuestionWidget.newUniqueId(); // Now set up the image view String errorMsg = null; if (imageURI != null) { try { String imageFilename = ReferenceManager._().DeriveReference(imageURI).getLocalURI(); final File imageFile = new File(imageFilename); if (imageFile.exists()) { Bitmap b = null; try { Display display = ((WindowManager) getContext().getSystemService( Context.WINDOW_SERVICE)).getDefaultDisplay(); int screenWidth = display.getWidth(); int screenHeight = display.getHeight(); b = FileUtils.getBitmapScaledToDisplay(imageFile, screenHeight, screenWidth); } catch (OutOfMemoryError e) { errorMsg = "ERROR: " + e.getMessage(); } if (b != null) { mImageView = new ImageView(getContext()); mImageView.setPadding(2, 2, 2, 2); mImageView.setAdjustViewBounds(true); mImageView.setImageBitmap(b); mImageView.setId(labelId); } else if (errorMsg == null) { // An error hasn't been logged and loading the image failed, so it's // likely // a bad file. errorMsg = getContext().getString(R.string.file_invalid, imageFile); } } else if (errorMsg == null) { // An error hasn't been logged. We should have an image, but the file // doesn't // exist. errorMsg = getContext().getString(R.string.file_missing, imageFile); } if (errorMsg != null) { // errorMsg is only set when an error has occured Log.e(t, errorMsg); mMissingImage = new TextView(getContext()); mMissingImage.setText(errorMsg); mMissingImage.setPadding(2, 2, 2, 2); mMissingImage.setId(labelId); } } catch (InvalidReferenceException e) { Log.e(t, "image invalid reference exception"); e.printStackTrace(); } } else { // There's no imageURI listed, so just ignore it. } // build text label. Don't assign the text to the built in label to he // button because it aligns horizontally, and we want the label on top TextView label = new TextView(getContext()); label.setText(prompt.getSelectChoiceText(mItems.get(i))); label.setTextSize(TypedValue.COMPLEX_UNIT_DIP, mAnswerFontsize); label.setGravity(Gravity.CENTER_HORIZONTAL); if (!displayLabel) { label.setVisibility(View.GONE); } // answer layout holds the label text/image on top and the radio button on bottom RelativeLayout answer = new RelativeLayout(getContext()); RelativeLayout.LayoutParams headerParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); headerParams.addRule(RelativeLayout.ALIGN_PARENT_TOP); headerParams.addRule(RelativeLayout.CENTER_HORIZONTAL); RelativeLayout.LayoutParams buttonParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); buttonParams.addRule(RelativeLayout.CENTER_HORIZONTAL); if (mImageView != null) { mImageView.setScaleType(ScaleType.CENTER); if (!displayLabel) { mImageView.setVisibility(View.GONE); } answer.addView(mImageView, headerParams); } else if (mMissingImage != null) { answer.addView(mMissingImage, headerParams); } else { if (displayLabel) { label.setId(labelId); answer.addView(label, headerParams); } } if (displayLabel) { buttonParams.addRule(RelativeLayout.BELOW, labelId); } answer.addView(c, buttonParams); answer.setPadding(4, 0, 4, 0); // /Each button gets equal weight LinearLayout.LayoutParams answerParams = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT); answerParams.weight = 1; buttonLayout.addView(answer, answerParams); } } // Align the buttons so that they appear horizonally and are right justified // buttonLayout.setGravity(Gravity.RIGHT); buttonLayout.setOrientation(LinearLayout.HORIZONTAL); // LinearLayout.LayoutParams params = new // LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); // buttonLayout.setLayoutParams(params); // The buttons take up the right half of the screen LinearLayout.LayoutParams buttonParams = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT); buttonParams.weight = 1; questionLayout.addView(buttonLayout, buttonParams); addView(questionLayout); } @Override public void clearAnswer() { for (int i = 0; i < mCheckboxes.size(); i++) { CheckBox c = mCheckboxes.get(i); if (c.isChecked()) { c.setChecked(false); } } } @Override public IAnswerData getAnswer() { List<Selection> vc = new ArrayList<Selection>(); for (int i = 0; i < mCheckboxes.size(); i++) { CheckBox c = mCheckboxes.get(i); if (c.isChecked()) { vc.add(new Selection(mItems.get(i))); } } if (vc.size() == 0) { return null; } else { return new SelectMultiData(vc); } } @Override public void setFocus(Context context) { // Hide the soft keyboard if it's showing. InputMethodManager inputManager = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE); inputManager.hideSoftInputFromWindow(this.getWindowToken(), 0); } // Override QuestionWidget's add question text. Build it the same // but add it to the questionLayout protected void addQuestionText(FormEntryPrompt p) { // Add the text view. Textview always exists, regardless of whether there's text. TextView questionText = new TextView(getContext()); questionText.setText(p.getLongText()); questionText.setTextSize(TypedValue.COMPLEX_UNIT_DIP, mQuestionFontsize); questionText.setTypeface(null, Typeface.BOLD); questionText.setPadding(0, 0, 0, 7); questionText.setId(QuestionWidget.newUniqueId()); // assign random id // Wrap to the size of the parent view questionText.setHorizontallyScrolling(false); if (p.getLongText() == null) { questionText.setVisibility(GONE); } // Put the question text on the left half of the screen LinearLayout.LayoutParams labelParams = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT); labelParams.weight = 1; questionLayout = new LinearLayout(getContext()); questionLayout.setOrientation(LinearLayout.HORIZONTAL); questionLayout.addView(questionText, labelParams); } @Override public void setOnLongClickListener(OnLongClickListener l) { for (CheckBox c : mCheckboxes) { c.setOnLongClickListener(l); } } @Override public void cancelLongPress() { super.cancelLongPress(); for (CheckBox c : mCheckboxes) { c.cancelLongPress(); } } }
Java
/* * Copyright (C) 2012 University of Washington * * 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 org.odk.collect.android.widgets; import java.io.File; import org.javarosa.core.model.data.IAnswerData; import org.javarosa.core.model.data.StringData; import org.javarosa.form.api.FormEntryPrompt; import org.odk.collect.android.R; import org.odk.collect.android.activities.DrawActivity; import org.odk.collect.android.activities.FormEntryActivity; import org.odk.collect.android.application.Collect; import org.odk.collect.android.utilities.FileUtils; import org.odk.collect.android.utilities.MediaUtils; import android.app.Activity; import android.content.ActivityNotFoundException; import android.content.ContentValues; import android.content.Context; import android.content.Intent; import android.graphics.Bitmap; import android.net.Uri; import android.provider.MediaStore.Images; import android.util.Log; import android.util.TypedValue; import android.view.Display; import android.view.View; import android.view.WindowManager; import android.view.inputmethod.InputMethodManager; import android.widget.Button; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TableLayout; import android.widget.TextView; import android.widget.Toast; /** * Signature widget. * * @author BehrAtherton@gmail.com * */ public class SignatureWidget extends QuestionWidget implements IBinaryWidget { private final static String t = "SignatureWidget"; private Button mSignButton; private String mBinaryName; private String mInstanceFolder; private ImageView mImageView; private TextView mErrorTextView; public SignatureWidget(Context context, FormEntryPrompt prompt) { super(context, prompt); mInstanceFolder = Collect.getInstance().getFormController().getInstancePath().getParent(); setOrientation(LinearLayout.VERTICAL); TableLayout.LayoutParams params = new TableLayout.LayoutParams(); params.setMargins(7, 5, 7, 5); mErrorTextView = new TextView(context); mErrorTextView.setId(QuestionWidget.newUniqueId()); mErrorTextView.setText("Selected file is not a valid image"); // setup Blank Image Button mSignButton = new Button(getContext()); mSignButton.setId(QuestionWidget.newUniqueId()); mSignButton.setText(getContext().getString(R.string.sign_button)); mSignButton.setTextSize(TypedValue.COMPLEX_UNIT_DIP, mAnswerFontsize); mSignButton.setPadding(20, 20, 20, 20); mSignButton.setEnabled(!prompt.isReadOnly()); mSignButton.setLayoutParams(params); // launch capture intent on click mSignButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Collect.getInstance() .getActivityLogger() .logInstanceAction(this, "signButton", "click", mPrompt.getIndex()); launchSignatureActivity(); } }); // finish complex layout addView(mSignButton); addView(mErrorTextView); // and hide the sign button if read-only if ( prompt.isReadOnly() ) { mSignButton.setVisibility(View.GONE); } mErrorTextView.setVisibility(View.GONE); // retrieve answer from data model and update ui mBinaryName = prompt.getAnswerText(); // Only add the imageView if the user has signed if (mBinaryName != null) { mImageView = new ImageView(getContext()); mImageView.setId(QuestionWidget.newUniqueId()); Display display = ((WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE)) .getDefaultDisplay(); int screenWidth = display.getWidth(); int screenHeight = display.getHeight(); File f = new File(mInstanceFolder + File.separator + mBinaryName); if (f.exists()) { Bitmap bmp = FileUtils.getBitmapScaledToDisplay(f, screenHeight, screenWidth); if (bmp == null) { mErrorTextView.setVisibility(View.VISIBLE); } mImageView.setImageBitmap(bmp); } else { mImageView.setImageBitmap(null); } mImageView.setPadding(10, 10, 10, 10); mImageView.setAdjustViewBounds(true); mImageView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Collect.getInstance().getActivityLogger().logInstanceAction(this, "viewImage", "click", mPrompt.getIndex()); launchSignatureActivity(); } }); addView(mImageView); } } private void launchSignatureActivity() { mErrorTextView.setVisibility(View.GONE); Intent i = new Intent(getContext(), DrawActivity.class); i.putExtra(DrawActivity.OPTION, DrawActivity.OPTION_SIGNATURE); // copy... if ( mBinaryName != null ) { File f = new File(mInstanceFolder + File.separator + mBinaryName); i.putExtra(DrawActivity.REF_IMAGE, Uri.fromFile(f)); } i.putExtra(DrawActivity.EXTRA_OUTPUT, Uri.fromFile(new File(Collect.TMPFILE_PATH))); try { Collect.getInstance().getFormController().setIndexWaitingForData(mPrompt.getIndex()); ((Activity) getContext()).startActivityForResult(i, FormEntryActivity.SIGNATURE_CAPTURE); } catch (ActivityNotFoundException e) { Toast.makeText(getContext(), getContext().getString(R.string.activity_not_found, "signature capture"), Toast.LENGTH_SHORT).show(); Collect.getInstance().getFormController().setIndexWaitingForData(null); } } private void deleteMedia() { // get the file path and delete the file String name = mBinaryName; // clean up variables mBinaryName = null; // delete from media provider int del = MediaUtils.deleteImageFileFromMediaProvider(mInstanceFolder + File.separator + name); Log.i(t, "Deleted " + del + " rows from media content provider"); } @Override public void clearAnswer() { // remove the file deleteMedia(); mImageView.setImageBitmap(null); mErrorTextView.setVisibility(View.GONE); // reset buttons mSignButton.setText(getContext().getString(R.string.sign_button)); } @Override public IAnswerData getAnswer() { if (mBinaryName != null) { return new StringData(mBinaryName.toString()); } else { return null; } } @Override public void setBinaryData(Object answer) { // you are replacing an answer. delete the previous image using the // content provider. if (mBinaryName != null) { deleteMedia(); } File newImage = (File) answer; if (newImage.exists()) { // Add the new image to the Media content provider so that the // viewing is fast in Android 2.0+ ContentValues values = new ContentValues(6); values.put(Images.Media.TITLE, newImage.getName()); values.put(Images.Media.DISPLAY_NAME, newImage.getName()); values.put(Images.Media.DATE_TAKEN, System.currentTimeMillis()); values.put(Images.Media.MIME_TYPE, "image/jpeg"); values.put(Images.Media.DATA, newImage.getAbsolutePath()); Uri imageURI = getContext().getContentResolver().insert( Images.Media.EXTERNAL_CONTENT_URI, values); Log.i(t, "Inserting image returned uri = " + imageURI.toString()); mBinaryName = newImage.getName(); Log.i(t, "Setting current answer to " + newImage.getName()); } else { Log.e(t, "NO IMAGE EXISTS at: " + newImage.getAbsolutePath()); } Collect.getInstance().getFormController().setIndexWaitingForData(null); } @Override public void setFocus(Context context) { // Hide the soft keyboard if it's showing. InputMethodManager inputManager = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE); inputManager.hideSoftInputFromWindow(this.getWindowToken(), 0); } @Override public boolean isWaitingForBinaryData() { return mPrompt.getIndex().equals(Collect.getInstance().getFormController().getIndexWaitingForData()); } @Override public void cancelWaitingForBinaryData() { Collect.getInstance().getFormController().setIndexWaitingForData(null); } @Override public void setOnLongClickListener(OnLongClickListener l) { mSignButton.setOnLongClickListener(l); if (mImageView != null) { mImageView.setOnLongClickListener(l); } } @Override public void cancelLongPress() { super.cancelLongPress(); mSignButton.cancelLongPress(); if (mImageView != null) { mImageView.cancelLongPress(); } } }
Java
/* * Copyright (C) 2009 University of Washington * * 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 org.odk.collect.android.widgets; import org.javarosa.core.model.data.IAnswerData; import org.javarosa.core.model.data.StringData; import org.javarosa.form.api.FormEntryPrompt; import org.odk.collect.android.application.Collect; import android.content.Context; import android.text.Editable; import android.text.TextWatcher; import android.text.method.TextKeyListener; import android.text.method.TextKeyListener.Capitalize; import android.util.Log; import android.util.TypedValue; import android.view.Gravity; import android.view.KeyEvent; import android.view.inputmethod.InputMethodManager; import android.widget.EditText; import android.widget.TableLayout; /** * The most basic widget that allows for entry of any text. * * @author Carl Hartung (carlhartung@gmail.com) * @author Yaw Anokwa (yanokwa@gmail.com) */ public class StringWidget extends QuestionWidget { private static final String ROWS = "rows"; boolean mReadOnly = false; protected EditText mAnswer; public StringWidget(Context context, FormEntryPrompt prompt, boolean readOnlyOverride) { this(context, prompt, readOnlyOverride, true); setupChangeListener(); } protected StringWidget(Context context, FormEntryPrompt prompt, boolean readOnlyOverride, boolean derived) { super(context, prompt); mAnswer = new EditText(context); mAnswer.setId(QuestionWidget.newUniqueId()); mReadOnly = prompt.isReadOnly() || readOnlyOverride; mAnswer.setTextSize(TypedValue.COMPLEX_UNIT_DIP, mAnswerFontsize); TableLayout.LayoutParams params = new TableLayout.LayoutParams(); /** * If a 'rows' attribute is on the input tag, set the minimum number of lines * to display in the field to that value. * * I.e., * <input ref="foo" rows="5"> * ... * </input> * * will set the height of the EditText box to 5 rows high. */ String height = prompt.getQuestion().getAdditionalAttribute(null, ROWS); if ( height != null && height.length() != 0 ) { try { int rows = Integer.valueOf(height); mAnswer.setMinLines(rows); mAnswer.setGravity(Gravity.TOP); // to write test starting at the top of the edit area } catch (Exception e) { Log.e(this.getClass().getName(), "Unable to process the rows setting for the answer field: " + e.toString()); } } params.setMargins(7, 5, 7, 5); mAnswer.setLayoutParams(params); // capitalize the first letter of the sentence mAnswer.setKeyListener(new TextKeyListener(Capitalize.SENTENCES, false)); // needed to make long read only text scroll mAnswer.setHorizontallyScrolling(false); mAnswer.setSingleLine(false); String s = prompt.getAnswerText(); if (s != null) { mAnswer.setText(s); } if (mReadOnly) { mAnswer.setBackgroundDrawable(null); mAnswer.setFocusable(false); mAnswer.setClickable(false); } addView(mAnswer); } protected void setupChangeListener() { mAnswer.addTextChangedListener(new TextWatcher() { private String oldText = ""; @Override public void afterTextChanged(Editable s) { if (!s.toString().equals(oldText)) { Collect.getInstance().getActivityLogger() .logInstanceAction(this, "answerTextChanged", s.toString(), getPrompt().getIndex()); } } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { oldText = s.toString(); } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } }); } @Override public void clearAnswer() { mAnswer.setText(null); } @Override public IAnswerData getAnswer() { clearFocus(); String s = mAnswer.getText().toString(); if (s == null || s.equals("")) { return null; } else { return new StringData(s); } } @Override public void setFocus(Context context) { // Put focus on text input field and display soft keyboard if appropriate. mAnswer.requestFocus(); InputMethodManager inputManager = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE); if (!mReadOnly) { inputManager.showSoftInput(mAnswer, 0); /* * If you do a multi-question screen after a "add another group" dialog, this won't * automatically pop up. It's an Android issue. * * That is, if I have an edit text in an activity, and pop a dialog, and in that * dialog's button's OnClick() I call edittext.requestFocus() and * showSoftInput(edittext, 0), showSoftinput() returns false. However, if the edittext * is focused before the dialog pops up, everything works fine. great. */ } else { inputManager.hideSoftInputFromWindow(mAnswer.getWindowToken(), 0); } } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (event.isAltPressed() == true) { return false; } return super.onKeyDown(keyCode, event); } @Override public void setOnLongClickListener(OnLongClickListener l) { mAnswer.setOnLongClickListener(l); } @Override public void cancelLongPress() { super.cancelLongPress(); mAnswer.cancelLongPress(); } }
Java
/* * Copyright (C) 2012 University of Washington * * 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 org.odk.collect.android.widgets; import java.io.File; import org.javarosa.core.model.data.IAnswerData; import org.javarosa.core.model.data.StringData; import org.javarosa.form.api.FormEntryPrompt; import org.odk.collect.android.R; import org.odk.collect.android.activities.DrawActivity; import org.odk.collect.android.activities.FormEntryActivity; import org.odk.collect.android.application.Collect; import org.odk.collect.android.utilities.FileUtils; import org.odk.collect.android.utilities.MediaUtils; import android.app.Activity; import android.content.ActivityNotFoundException; import android.content.ContentValues; import android.content.Context; import android.content.Intent; import android.graphics.Bitmap; import android.net.Uri; import android.provider.MediaStore.Images; import android.util.Log; import android.util.TypedValue; import android.view.Display; import android.view.View; import android.view.WindowManager; import android.view.inputmethod.InputMethodManager; import android.widget.Button; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TableLayout; import android.widget.TextView; import android.widget.Toast; /** * Free drawing widget. * * @author BehrAtherton@gmail.com * */ public class DrawWidget extends QuestionWidget implements IBinaryWidget { private final static String t = "DrawWidget"; private Button mDrawButton; private String mBinaryName; private String mInstanceFolder; private ImageView mImageView; private TextView mErrorTextView; public DrawWidget(Context context, FormEntryPrompt prompt) { super(context, prompt); mErrorTextView = new TextView(context); mErrorTextView.setId(QuestionWidget.newUniqueId()); mErrorTextView.setText("Selected file is not a valid image"); mInstanceFolder = Collect.getInstance().getFormController() .getInstancePath().getParent(); setOrientation(LinearLayout.VERTICAL); TableLayout.LayoutParams params = new TableLayout.LayoutParams(); params.setMargins(7, 5, 7, 5); // setup Blank Image Button mDrawButton = new Button(getContext()); mDrawButton.setId(QuestionWidget.newUniqueId()); mDrawButton.setText(getContext().getString(R.string.draw_image)); mDrawButton.setTextSize(TypedValue.COMPLEX_UNIT_DIP, mAnswerFontsize); mDrawButton.setPadding(20, 20, 20, 20); mDrawButton.setEnabled(!prompt.isReadOnly()); mDrawButton.setLayoutParams(params); // launch capture intent on click mDrawButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Collect.getInstance() .getActivityLogger() .logInstanceAction(this, "drawButton", "click", mPrompt.getIndex()); launchDrawActivity(); } }); // finish complex layout addView(mDrawButton); addView(mErrorTextView); if (mPrompt.isReadOnly()) { mDrawButton.setVisibility(View.GONE); } mErrorTextView.setVisibility(View.GONE); // retrieve answer from data model and update ui mBinaryName = prompt.getAnswerText(); // Only add the imageView if the user has signed if (mBinaryName != null) { mImageView = new ImageView(getContext()); mImageView.setId(QuestionWidget.newUniqueId()); Display display = ((WindowManager) getContext().getSystemService( Context.WINDOW_SERVICE)).getDefaultDisplay(); int screenWidth = display.getWidth(); int screenHeight = display.getHeight(); File f = new File(mInstanceFolder + File.separator + mBinaryName); if (f.exists()) { Bitmap bmp = FileUtils.getBitmapScaledToDisplay(f, screenHeight, screenWidth); if (bmp == null) { mErrorTextView.setVisibility(View.VISIBLE); } mImageView.setImageBitmap(bmp); } else { mImageView.setImageBitmap(null); } mImageView.setPadding(10, 10, 10, 10); mImageView.setAdjustViewBounds(true); mImageView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Collect.getInstance() .getActivityLogger() .logInstanceAction(this, "viewImage", "click", mPrompt.getIndex()); launchDrawActivity(); } }); addView(mImageView); } } private void launchDrawActivity() { mErrorTextView.setVisibility(View.GONE); Intent i = new Intent(getContext(), DrawActivity.class); i.putExtra(DrawActivity.OPTION, DrawActivity.OPTION_DRAW); // copy... if (mBinaryName != null) { File f = new File(mInstanceFolder + File.separator + mBinaryName); i.putExtra(DrawActivity.REF_IMAGE, Uri.fromFile(f)); } i.putExtra(DrawActivity.EXTRA_OUTPUT, Uri.fromFile(new File(Collect.TMPFILE_PATH))); try { Collect.getInstance().getFormController() .setIndexWaitingForData(mPrompt.getIndex()); ((Activity) getContext()).startActivityForResult(i, FormEntryActivity.DRAW_IMAGE); } catch (ActivityNotFoundException e) { Toast.makeText( getContext(), getContext().getString(R.string.activity_not_found, "draw image"), Toast.LENGTH_SHORT).show(); Collect.getInstance().getFormController() .setIndexWaitingForData(null); } } private void deleteMedia() { // get the file path and delete the file String name = mBinaryName; // clean up variables mBinaryName = null; // delete from media provider int del = MediaUtils.deleteImageFileFromMediaProvider(mInstanceFolder + File.separator + name); Log.i(t, "Deleted " + del + " rows from media content provider"); } @Override public void clearAnswer() { // remove the file deleteMedia(); mImageView.setImageBitmap(null); mErrorTextView.setVisibility(View.GONE); // reset buttons mDrawButton.setText(getContext().getString(R.string.draw_image)); } @Override public IAnswerData getAnswer() { if (mBinaryName != null) { return new StringData(mBinaryName.toString()); } else { return null; } } @Override public void setBinaryData(Object answer) { // you are replacing an answer. delete the previous image using the // content provider. if (mBinaryName != null) { deleteMedia(); } File newImage = (File) answer; if (newImage.exists()) { // Add the new image to the Media content provider so that the // viewing is fast in Android 2.0+ ContentValues values = new ContentValues(6); values.put(Images.Media.TITLE, newImage.getName()); values.put(Images.Media.DISPLAY_NAME, newImage.getName()); values.put(Images.Media.DATE_TAKEN, System.currentTimeMillis()); values.put(Images.Media.MIME_TYPE, "image/jpeg"); values.put(Images.Media.DATA, newImage.getAbsolutePath()); Uri imageURI = getContext().getContentResolver().insert( Images.Media.EXTERNAL_CONTENT_URI, values); Log.i(t, "Inserting image returned uri = " + imageURI.toString()); mBinaryName = newImage.getName(); Log.i(t, "Setting current answer to " + newImage.getName()); } else { Log.e(t, "NO IMAGE EXISTS at: " + newImage.getAbsolutePath()); } Collect.getInstance().getFormController().setIndexWaitingForData(null); } @Override public void setFocus(Context context) { // Hide the soft keyboard if it's showing. InputMethodManager inputManager = (InputMethodManager) context .getSystemService(Context.INPUT_METHOD_SERVICE); inputManager.hideSoftInputFromWindow(this.getWindowToken(), 0); } @Override public boolean isWaitingForBinaryData() { return mPrompt.getIndex().equals( Collect.getInstance().getFormController() .getIndexWaitingForData()); } @Override public void cancelWaitingForBinaryData() { Collect.getInstance().getFormController().setIndexWaitingForData(null); } @Override public void setOnLongClickListener(OnLongClickListener l) { mDrawButton.setOnLongClickListener(l); if (mImageView != null) { mImageView.setOnLongClickListener(l); } } @Override public void cancelLongPress() { super.cancelLongPress(); mDrawButton.cancelLongPress(); if (mImageView != null) { mImageView.cancelLongPress(); } } }
Java
/* * Copyright (C) 2009 University of Washington * * 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 org.odk.collect.android.widgets; import java.util.Locale; import org.javarosa.core.model.Constants; import org.javarosa.form.api.FormEntryPrompt; import android.content.Context; import android.util.Log; /** * Convenience class that handles creation of widgets. * * @author Carl Hartung (carlhartung@gmail.com) */ public class WidgetFactory { /** * Returns the appropriate QuestionWidget for the given FormEntryPrompt. * * @param fep prompt element to be rendered * @param context Android context * @param readOnlyOverride a flag to be ORed with JR readonly attribute. */ static public QuestionWidget createWidgetFromPrompt(FormEntryPrompt fep, Context context, boolean readOnlyOverride) { // get appearance hint and clean it up so it is lower case and never null... String appearance = fep.getAppearanceHint(); if ( appearance == null ) appearance = ""; // for now, all appearance tags are in english... appearance = appearance.toLowerCase(Locale.ENGLISH); QuestionWidget questionWidget; switch (fep.getControlType()) { case Constants.CONTROL_INPUT: switch (fep.getDataType()) { case Constants.DATATYPE_DATE_TIME: questionWidget = new DateTimeWidget(context, fep); break; case Constants.DATATYPE_DATE: questionWidget = new DateWidget(context, fep); break; case Constants.DATATYPE_TIME: questionWidget = new TimeWidget(context, fep); break; case Constants.DATATYPE_DECIMAL: if ( appearance.startsWith("ex:") ) { questionWidget = new ExDecimalWidget(context, fep); } else if (appearance.equals("bearing")) { questionWidget = new BearingWidget(context, fep); } else { questionWidget = new DecimalWidget(context, fep, readOnlyOverride); } break; case Constants.DATATYPE_INTEGER: if ( appearance.startsWith("ex:") ) { questionWidget = new ExIntegerWidget(context, fep); } else { questionWidget = new IntegerWidget(context, fep, readOnlyOverride); } break; case Constants.DATATYPE_GEOPOINT: questionWidget = new GeoPointWidget(context, fep); break; case Constants.DATATYPE_BARCODE: questionWidget = new BarcodeWidget(context, fep); break; case Constants.DATATYPE_TEXT: String query = fep.getQuestion().getAdditionalAttribute(null, "query"); if (query != null) { questionWidget = new ItemsetWidget(context, fep, readOnlyOverride); } else if (appearance.startsWith("printer")) { questionWidget = new ExPrinterWidget(context, fep); } else if (appearance.startsWith("ex:")) { questionWidget = new ExStringWidget(context, fep); } else if (appearance.equals("numbers")) { questionWidget = new StringNumberWidget(context, fep, readOnlyOverride); } else if (appearance.equals("url")) { questionWidget = new UrlWidget(context, fep); } else { questionWidget = new StringWidget(context, fep, readOnlyOverride); } break; default: questionWidget = new StringWidget(context, fep, readOnlyOverride); break; } break; case Constants.CONTROL_IMAGE_CHOOSE: if (appearance.equals("web")) { questionWidget = new ImageWebViewWidget(context, fep); } else if(appearance.equals("signature")) { questionWidget = new SignatureWidget(context, fep); } else if(appearance.equals("annotate")) { questionWidget = new AnnotateWidget(context, fep); } else if(appearance.equals("draw")) { questionWidget = new DrawWidget(context, fep); } else if(appearance.startsWith("align:")) { questionWidget = new AlignedImageWidget(context, fep); } else { questionWidget = new ImageWidget(context, fep); } break; case Constants.CONTROL_AUDIO_CAPTURE: questionWidget = new AudioWidget(context, fep); break; case Constants.CONTROL_VIDEO_CAPTURE: questionWidget = new VideoWidget(context, fep); break; case Constants.CONTROL_SELECT_ONE: // SurveyCTO-revised support for dynamic select content (from .csv files) // consider traditional ODK appearance to be first word in appearance string if (appearance.startsWith("compact") || appearance.startsWith("quickcompact")) { int numColumns = -1; try { String firstWord = appearance.split("\\s+")[0]; int idx = firstWord.indexOf("-"); if ( idx != -1 ) { numColumns = Integer.parseInt(firstWord.substring(idx + 1)); } } catch (Exception e) { // Do nothing, leave numColumns as -1 Log.e("WidgetFactory", "Exception parsing numColumns"); } if (appearance.startsWith("quick")) { questionWidget = new GridWidget(context, fep, numColumns, true); } else { questionWidget = new GridWidget(context, fep, numColumns, false); } } else if (appearance.startsWith("minimal")) { questionWidget = new SpinnerWidget(context, fep); } // else if (appearance != null && appearance.contains("autocomplete")) { // String filterType = null; // try { // filterType = appearance.substring(appearance.indexOf('-') + 1); // } catch (Exception e) { // // Do nothing, leave filerType null // Log.e("WidgetFactory", "Exception parsing filterType"); // } // questionWidget = new AutoCompleteWidget(context, fep, filterType); // // } else if (appearance.startsWith("quick")) { questionWidget = new SelectOneAutoAdvanceWidget(context, fep); } else if (appearance.equals("list-nolabel")) { questionWidget = new ListWidget(context, fep, false); } else if (appearance.equals("list")) { questionWidget = new ListWidget(context, fep, true); } else if (appearance.equals("label")) { questionWidget = new LabelWidget(context, fep); } else { questionWidget = new SelectOneWidget(context, fep); } break; case Constants.CONTROL_SELECT_MULTI: // SurveyCTO-revised support for dynamic select content (from .csv files) // consider traditional ODK appearance to be first word in appearance string if (appearance.startsWith("compact")) { int numColumns = -1; try { String firstWord = appearance.split("\\s+")[0]; int idx = firstWord.indexOf("-"); if ( idx != -1 ) { numColumns = Integer.parseInt(firstWord.substring(idx + 1)); } } catch (Exception e) { // Do nothing, leave numColumns as -1 Log.e("WidgetFactory", "Exception parsing numColumns"); } questionWidget = new GridMultiWidget(context, fep, numColumns); } else if (appearance.startsWith("minimal")) { questionWidget = new SpinnerMultiWidget(context, fep); } else if (appearance.startsWith("list-nolabel")) { questionWidget = new ListMultiWidget(context, fep, false); } else if (appearance.startsWith("list")) { questionWidget = new ListMultiWidget(context, fep, true); } else if (appearance.startsWith("label")) { questionWidget = new LabelWidget(context, fep); } else { questionWidget = new SelectMultiWidget(context, fep); } break; case Constants.CONTROL_TRIGGER: questionWidget = new TriggerWidget(context, fep); break; default: questionWidget = new StringWidget(context, fep, readOnlyOverride); break; } return questionWidget; } }
Java
/* * Copyright (C) 2009 University of Washington * * 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 org.odk.collect.android.widgets; import java.io.File; import java.util.ArrayList; import java.util.HashMap; import org.javarosa.core.model.FormDef; import org.javarosa.core.model.condition.EvaluationContext; import org.javarosa.core.model.data.IAnswerData; import org.javarosa.core.model.data.StringData; import org.javarosa.core.model.instance.TreeElement; import org.javarosa.form.api.FormEntryPrompt; import org.javarosa.xpath.XPathNodeset; import org.javarosa.xpath.XPathParseTool; import org.javarosa.xpath.expr.XPathExpression; import org.javarosa.xpath.parser.XPathSyntaxException; import org.odk.collect.android.R; import org.odk.collect.android.application.Collect; import org.odk.collect.android.database.ItemsetDbAdapter; import android.content.Context; import android.database.Cursor; import android.util.Log; import android.view.KeyEvent; import android.view.inputmethod.InputMethodManager; import android.widget.CompoundButton; import android.widget.RadioButton; import android.widget.RadioGroup; import android.widget.TextView; /** * The most basic widget that allows for entry of any text. * * @author Carl Hartung (carlhartung@gmail.com) * @author Yaw Anokwa (yanokwa@gmail.com) */ public class ItemsetWidget extends QuestionWidget implements android.widget.CompoundButton.OnCheckedChangeListener { private static String tag = "ItemsetWidget"; boolean mReadOnly; protected RadioGroup mButtons; private String mAnswer = null; // Hashmap linking label:value private HashMap<String, String> mAnswers; public ItemsetWidget(Context context, FormEntryPrompt prompt, boolean readOnlyOverride) { this(context, prompt, readOnlyOverride, true); } protected ItemsetWidget(Context context, FormEntryPrompt prompt, boolean readOnlyOverride, boolean derived) { super(context, prompt); mButtons = new RadioGroup(context); mButtons.setId(QuestionWidget.newUniqueId()); mReadOnly = prompt.isReadOnly() || readOnlyOverride; mAnswers = new HashMap<String, String>(); String currentAnswer = prompt.getAnswerText(); // the format of the query should be something like this: // query="instance('cities')/root/item[state=/data/state and county=/data/county]" // "query" is what we're using to notify that this is an // itemset widget. String nodesetStr = prompt.getQuestion().getAdditionalAttribute(null, "query"); // parse out the list name, between the '' String list_name = nodesetStr.substring(nodesetStr.indexOf("'") + 1, nodesetStr.lastIndexOf("'")); // isolate the string between between the [ ] characters String queryString = nodesetStr.substring(nodesetStr.indexOf("[") + 1, nodesetStr.lastIndexOf("]")); StringBuilder selection = new StringBuilder(); // add the list name as the first argument, which will always be there selection.append("list_name=?"); // check to see if there are any arguments if (queryString.indexOf("=") != -1) { selection.append(" and "); } // can't just split on 'and' or 'or' because they have different // behavior, so loop through and break them off until we don't have any // more // must include the spaces in indexOf so we don't match words like // "land" int andIndex = -1; int orIndex = -1; ArrayList<String> arguments = new ArrayList<String>(); while ((andIndex = queryString.indexOf(" and ")) != -1 || (orIndex = queryString.indexOf(" or ")) != -1) { if (andIndex != -1) { String subString = queryString.substring(0, andIndex); String pair[] = subString.split("="); if (pair.length == 2) { selection.append(pair[0].trim() + "=? and "); arguments.add(pair[1].trim()); } else { // parse error } // move string forward to after " and " queryString = queryString.substring(andIndex + 5, queryString.length()); andIndex = -1; } else if (orIndex != -1) { String subString = queryString.substring(0, orIndex); String pair[] = subString.split("="); if (pair.length == 2) { selection.append(pair[0].trim() + "=? or "); arguments.add(pair[1].trim()); } else { // parse error } // move string forward to after " or " queryString = queryString.substring(orIndex + 4, queryString.length()); orIndex = -1; } } // parse the last segment (or only segment if there are no 'and' or 'or' // clauses String pair[] = queryString.split("="); if (pair.length == 2) { selection.append(pair[0].trim() + "=?"); arguments.add(pair[1].trim()); } if (pair.length == 1) { // this is probably okay, because then you just list all items in // the list } else { // parse error } // +1 is for the list_name String[] selectionArgs = new String[arguments.size() + 1]; boolean nullArgs = false; // can't have any null arguments selectionArgs[0] = list_name; // first argument is always listname // loop through the arguments, evaluate any expressions // and build the query string for the DB for (int i = 0; i < arguments.size(); i++) { XPathExpression xpr = null; try { xpr = XPathParseTool.parseXPath(arguments.get(i)); } catch (XPathSyntaxException e) { e.printStackTrace(); TextView error = new TextView(context); error.setText("XPathParser Exception: \"" + arguments.get(i) + "\""); addView(error); break; } if (xpr != null) { FormDef form = Collect.getInstance().getFormController().getFormDef(); TreeElement mTreeElement = form.getMainInstance().resolveReference(prompt.getIndex().getReference()); EvaluationContext ec = new EvaluationContext(form.getEvaluationContext(), mTreeElement.getRef()); Object value = xpr.eval(form.getMainInstance(), ec); if (value == null) { nullArgs = true; } else { if (value instanceof XPathNodeset) { XPathNodeset xpn = (XPathNodeset) value; value = xpn.getValAt(0); } selectionArgs[i + 1] = value.toString(); } } } File itemsetFile = new File(Collect.getInstance().getFormController().getMediaFolder().getAbsolutePath() + "/itemsets.csv"); if (nullArgs) { // we can't try to query with null values else it blows up // so just leave the screen blank // TODO: put an error? } else if (itemsetFile.exists()) { ItemsetDbAdapter ida = new ItemsetDbAdapter(); ida.open(); // name of the itemset table for this form String pathHash = ItemsetDbAdapter.getMd5FromString(itemsetFile.getAbsolutePath()); try { Cursor c = ida.query(pathHash, selection.toString(), selectionArgs); if (c != null) { c.move(-1); while (c.moveToNext()) { String label = ""; String val = ""; // try to get the value associated with the label:lang // string if that doen't exist, then just use label String lang = ""; if (Collect.getInstance().getFormController().getLanguages() != null && Collect.getInstance().getFormController().getLanguages().length > 0) { lang = Collect.getInstance().getFormController().getLanguage(); } // apparently you only need the double quotes in the // column name when creating the column with a : // included String labelLang = "label" + "::" + lang; int langCol = c.getColumnIndex(labelLang); if (langCol == -1) { label = c.getString(c.getColumnIndex("label")); } else { label = c.getString(c.getColumnIndex(labelLang)); } // the actual value is stored in name val = c.getString(c.getColumnIndex("name")); mAnswers.put(label, val); RadioButton rb = new RadioButton(context); rb.setOnCheckedChangeListener(this); rb.setText(label); rb.setTextSize(mAnswerFontsize); mButtons.addView(rb); // have to add it to the radiogroup before checking it, // else it lets two buttons be checked... if (currentAnswer != null && val.compareTo(currentAnswer) == 0) { rb.setChecked(true); } } c.close(); } } finally { ida.close(); } addView(mButtons); } else { TextView error = new TextView(context); error.setText(getContext().getString(R.string.file_missing, itemsetFile.getAbsolutePath())); addView(error); } } @Override public void clearAnswer() { mButtons.clearCheck(); mAnswer = null; } @Override public IAnswerData getAnswer() { if (mAnswer == null) { return null; } else { return new StringData(mAnswer); } } @Override public void setFocus(Context context) { // Hide the soft keyboard if it's showing. InputMethodManager inputManager = (InputMethodManager) context .getSystemService(Context.INPUT_METHOD_SERVICE); inputManager.hideSoftInputFromWindow(this.getWindowToken(), 0); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (event.isAltPressed() == true) { return false; } return super.onKeyDown(keyCode, event); } @Override public void setOnLongClickListener(OnLongClickListener l) { mButtons.setOnLongClickListener(l); for (int i = 0; i < mButtons.getChildCount(); i++) { mButtons.getChildAt(i).setOnLongClickListener(l); } } @Override public void cancelLongPress() { super.cancelLongPress(); mButtons.cancelLongPress(); for (int i = 0; i < mButtons.getChildCount(); i++) { mButtons.getChildAt(i).cancelLongPress(); } } @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (isChecked) { mAnswer = mAnswers.get((String) buttonView.getText()); } } }
Java
/* * Copyright (C) 2013 University of Washington * * 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 org.odk.collect.android.widgets; import java.io.File; import org.javarosa.core.model.data.IAnswerData; import org.javarosa.core.model.data.StringData; import org.javarosa.form.api.FormEntryPrompt; import org.odk.collect.android.R; import org.odk.collect.android.activities.FormEntryActivity; import org.odk.collect.android.application.Collect; import org.odk.collect.android.utilities.FileUtils; import org.odk.collect.android.utilities.MediaUtils; import android.app.Activity; import android.content.ActivityNotFoundException; import android.content.ComponentName; import android.content.ContentValues; import android.content.Context; import android.content.Intent; import android.graphics.Bitmap; import android.net.Uri; import android.provider.MediaStore.Images; import android.util.Log; import android.util.TypedValue; import android.view.Display; import android.view.View; import android.view.WindowManager; import android.view.inputmethod.InputMethodManager; import android.widget.Button; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TableLayout; import android.widget.TextView; import android.widget.Toast; /** * Widget that allows user to invoke the aligned-image camera to take pictures and add them to the form. * Modified to launch the Aligned-image camera app. * * @author Carl Hartung (carlhartung@gmail.com) * @author Yaw Anokwa (yanokwa@gmail.com) * @author mitchellsundt@gmail.com * @author Mitchell Tyler Lee */ public class AlignedImageWidget extends QuestionWidget implements IBinaryWidget { private static final String ODK_CAMERA_TAKE_PICTURE_INTENT_COMPONENT = "org.opendatakit.camera.TakePicture"; private static final String ODK_CAMERA_INTENT_PACKAGE = "org.opendatakit.camera"; private static final String RETAKE_OPTION_EXTRA = "retakeOption"; private static final String DIMENSIONS_EXTRA = "dimensions"; private static final String FILE_PATH_EXTRA = "filePath"; private final static String t = "AlignedImageWidget"; private Button mCaptureButton; private Button mChooseButton; private ImageView mImageView; private String mBinaryName; private String mInstanceFolder; private TextView mErrorTextView; private int iArray[] = new int[6]; public AlignedImageWidget(Context context, FormEntryPrompt prompt) { super(context, prompt); String appearance = prompt.getAppearanceHint(); String alignments = appearance.substring(appearance.indexOf(":") + 1); String[] splits = alignments.split(" "); if ( splits.length != 6 ) { Log.w(t, "Only have " + splits.length + " alignment values"); } for ( int i = 0 ; i < 6 ; ++i ) { if ( splits.length < i ) { iArray[i] = 0; } else { iArray[i] = Integer.valueOf(splits[i]); } } mInstanceFolder = Collect.getInstance().getFormController().getInstancePath().getParent(); setOrientation(LinearLayout.VERTICAL); TableLayout.LayoutParams params = new TableLayout.LayoutParams(); params.setMargins(7, 5, 7, 5); mErrorTextView = new TextView(context); mErrorTextView.setId(QuestionWidget.newUniqueId()); mErrorTextView.setText("Selected file is not a valid image"); // setup capture button mCaptureButton = new Button(getContext()); mCaptureButton.setId(QuestionWidget.newUniqueId()); mCaptureButton.setText(getContext().getString(R.string.capture_image)); mCaptureButton.setTextSize(TypedValue.COMPLEX_UNIT_DIP, mAnswerFontsize); mCaptureButton.setPadding(20, 20, 20, 20); mCaptureButton.setEnabled(!prompt.isReadOnly()); mCaptureButton.setLayoutParams(params); // launch capture intent on click mCaptureButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Collect.getInstance().getActivityLogger().logInstanceAction(this, "captureButton", "click", mPrompt.getIndex()); mErrorTextView.setVisibility(View.GONE); Intent i = new Intent(); i.setComponent(new ComponentName(ODK_CAMERA_INTENT_PACKAGE, ODK_CAMERA_TAKE_PICTURE_INTENT_COMPONENT)); i.putExtra(FILE_PATH_EXTRA, Collect.CACHE_PATH); i.putExtra(DIMENSIONS_EXTRA, iArray); i.putExtra(RETAKE_OPTION_EXTRA, false); // We give the camera an absolute filename/path where to put the // picture because of bug: // http://code.google.com/p/android/issues/detail?id=1480 // The bug appears to be fixed in Android 2.0+, but as of feb 2, // 2010, G1 phones only run 1.6. Without specifying the path the // images returned by the camera in 1.6 (and earlier) are ~1/4 // the size. boo. // if this gets modified, the onActivityResult in // FormEntyActivity will also need to be updated. try { Collect.getInstance().getFormController().setIndexWaitingForData(mPrompt.getIndex()); ((Activity) getContext()).startActivityForResult(i, FormEntryActivity.ALIGNED_IMAGE); } catch (ActivityNotFoundException e) { Toast.makeText(getContext(), getContext().getString(R.string.activity_not_found, "aligned image capture"), Toast.LENGTH_SHORT).show(); Collect.getInstance().getFormController().setIndexWaitingForData(null); } } }); // setup chooser button mChooseButton = new Button(getContext()); mChooseButton.setId(QuestionWidget.newUniqueId()); mChooseButton.setText(getContext().getString(R.string.choose_image)); mChooseButton.setTextSize(TypedValue.COMPLEX_UNIT_DIP, mAnswerFontsize); mChooseButton.setPadding(20, 20, 20, 20); mChooseButton.setEnabled(!prompt.isReadOnly()); mChooseButton.setLayoutParams(params); // launch capture intent on click mChooseButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Collect.getInstance().getActivityLogger().logInstanceAction(this, "chooseButton", "click", mPrompt.getIndex()); mErrorTextView.setVisibility(View.GONE); Intent i = new Intent(Intent.ACTION_GET_CONTENT); i.setType("image/*"); try { Collect.getInstance().getFormController() .setIndexWaitingForData(mPrompt.getIndex()); ((Activity) getContext()).startActivityForResult(i, FormEntryActivity.IMAGE_CHOOSER); } catch (ActivityNotFoundException e) { Toast.makeText(getContext(), getContext().getString(R.string.activity_not_found, "choose image"), Toast.LENGTH_SHORT).show(); Collect.getInstance().getFormController().setIndexWaitingForData(null); } } }); // finish complex layout addView(mCaptureButton); addView(mChooseButton); addView(mErrorTextView); // and hide the capture and choose button if read-only if ( prompt.isReadOnly() ) { mCaptureButton.setVisibility(View.GONE); mChooseButton.setVisibility(View.GONE); } mErrorTextView.setVisibility(View.GONE); // retrieve answer from data model and update ui mBinaryName = prompt.getAnswerText(); // Only add the imageView if the user has taken a picture if (mBinaryName != null) { mImageView = new ImageView(getContext()); mImageView.setId(QuestionWidget.newUniqueId()); Display display = ((WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE)) .getDefaultDisplay(); int screenWidth = display.getWidth(); int screenHeight = display.getHeight(); File f = new File(mInstanceFolder + File.separator + mBinaryName); if (f.exists()) { Bitmap bmp = FileUtils.getBitmapScaledToDisplay(f, screenHeight, screenWidth); if (bmp == null) { mErrorTextView.setVisibility(View.VISIBLE); } mImageView.setImageBitmap(bmp); } else { mImageView.setImageBitmap(null); } mImageView.setPadding(10, 10, 10, 10); mImageView.setAdjustViewBounds(true); mImageView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Collect.getInstance().getActivityLogger().logInstanceAction(this, "viewButton", "click", mPrompt.getIndex()); Intent i = new Intent("android.intent.action.VIEW"); Uri uri = MediaUtils.getImageUriFromMediaProvider(mInstanceFolder + File.separator + mBinaryName); if ( uri != null ) { Log.i(t,"setting view path to: " + uri); i.setDataAndType(uri, "image/*"); try { getContext().startActivity(i); } catch (ActivityNotFoundException e) { Toast.makeText(getContext(), getContext().getString(R.string.activity_not_found, "view image"), Toast.LENGTH_SHORT).show(); } } } }); addView(mImageView); } } private void deleteMedia() { // get the file path and delete the file String name = mBinaryName; // clean up variables mBinaryName = null; // delete from media provider int del = MediaUtils.deleteImageFileFromMediaProvider(mInstanceFolder + File.separator + name); Log.i(t, "Deleted " + del + " rows from media content provider"); } @Override public void clearAnswer() { // remove the file deleteMedia(); mImageView.setImageBitmap(null); mErrorTextView.setVisibility(View.GONE); // reset buttons mCaptureButton.setText(getContext().getString(R.string.capture_image)); } @Override public IAnswerData getAnswer() { if (mBinaryName != null) { return new StringData(mBinaryName.toString()); } else { return null; } } @Override public void setBinaryData(Object newImageObj) { // you are replacing an answer. delete the previous image using the // content provider. if (mBinaryName != null) { deleteMedia(); } File newImage = (File) newImageObj; if (newImage.exists()) { // Add the new image to the Media content provider so that the // viewing is fast in Android 2.0+ ContentValues values = new ContentValues(6); values.put(Images.Media.TITLE, newImage.getName()); values.put(Images.Media.DISPLAY_NAME, newImage.getName()); values.put(Images.Media.DATE_TAKEN, System.currentTimeMillis()); values.put(Images.Media.MIME_TYPE, "image/jpeg"); values.put(Images.Media.DATA, newImage.getAbsolutePath()); Uri imageURI = getContext().getContentResolver().insert( Images.Media.EXTERNAL_CONTENT_URI, values); Log.i(t, "Inserting image returned uri = " + imageURI.toString()); mBinaryName = newImage.getName(); Log.i(t, "Setting current answer to " + newImage.getName()); } else { Log.e(t, "NO IMAGE EXISTS at: " + newImage.getAbsolutePath()); } Collect.getInstance().getFormController().setIndexWaitingForData(null); } @Override public void setFocus(Context context) { // Hide the soft keyboard if it's showing. InputMethodManager inputManager = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE); inputManager.hideSoftInputFromWindow(this.getWindowToken(), 0); } @Override public boolean isWaitingForBinaryData() { return mPrompt.getIndex().equals(Collect.getInstance().getFormController().getIndexWaitingForData()); } @Override public void cancelWaitingForBinaryData() { Collect.getInstance().getFormController().setIndexWaitingForData(null); } @Override public void setOnLongClickListener(OnLongClickListener l) { mCaptureButton.setOnLongClickListener(l); mChooseButton.setOnLongClickListener(l); if (mImageView != null) { mImageView.setOnLongClickListener(l); } } @Override public void cancelLongPress() { super.cancelLongPress(); mCaptureButton.cancelLongPress(); mChooseButton.cancelLongPress(); if (mImageView != null) { mImageView.cancelLongPress(); } } }
Java
/* * Copyright (C) 2009 University of Washington * * 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 org.odk.collect.android.widgets; /** * Interface implemented by widgets that need binary data. * * @author Carl Hartung (carlhartung@gmail.com) */ public interface IBinaryWidget { public void setBinaryData(Object answer); public void cancelWaitingForBinaryData(); public boolean isWaitingForBinaryData(); } /*TODO carlhartung: we might want to move this into the QuestionWidget abstract class? * */
Java
/* * Copyright (C) 2011 University of Washington * * 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 org.odk.collect.android.widgets; import java.util.ArrayList; import java.util.List; import org.javarosa.core.model.SelectChoice; import org.javarosa.core.model.data.IAnswerData; import org.javarosa.core.model.data.SelectMultiData; import org.javarosa.core.model.data.helper.Selection; import org.javarosa.form.api.FormEntryPrompt; import org.javarosa.xpath.expr.XPathFuncExpr; import org.odk.collect.android.R; import org.odk.collect.android.external.ExternalDataUtil; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.util.TypedValue; import android.view.View; import android.view.inputmethod.InputMethodManager; import android.widget.Button; import android.widget.TextView; /** * SpinnerMultiWidget, like SelectMultiWidget handles multiple selection fields using checkboxes, * but the user clicks a button to see the checkboxes. The goal is to be more compact. If images, * audio, or video are specified in the select answers they are ignored. WARNING: There is a bug in * android versions previous to 2.0 that affects this widget. You can find the report here: * http://code.google.com/p/android/issues/detail?id=922 This bug causes text to be white in alert * boxes, which makes the select options invisible in this widget. For this reason, this widget * should not be used on phones with android versions lower than 2.0. * * @author Jeff Beorse (jeff@beorse.net) */ public class SpinnerMultiWidget extends QuestionWidget { List<SelectChoice> mItems; // The possible select answers CharSequence[] answer_items; // The button to push to display the answers to choose from Button button; // Defines which answers are selected boolean[] selections; // The alert box that contains the answer selection view AlertDialog.Builder alert_builder; // Displays the current selections below the button TextView selectionText; @SuppressWarnings("unchecked") public SpinnerMultiWidget(final Context context, FormEntryPrompt prompt) { super(context, prompt); // SurveyCTO-added support for dynamic select content (from .csv files) XPathFuncExpr xPathFuncExpr = ExternalDataUtil.getSearchXPathExpression(prompt.getAppearanceHint()); if (xPathFuncExpr != null) { mItems = ExternalDataUtil.populateExternalChoices(prompt, xPathFuncExpr); } else { mItems = prompt.getSelectChoices(); } mPrompt = prompt; selections = new boolean[mItems.size()]; answer_items = new CharSequence[mItems.size()]; alert_builder = new AlertDialog.Builder(context); button = new Button(context); selectionText = new TextView(getContext()); // Build View for (int i = 0; i < mItems.size(); i++) { answer_items[i] = prompt.getSelectChoiceText(mItems.get(i)); } selectionText.setText(context.getString(R.string.selected)); selectionText.setTextSize(TypedValue.COMPLEX_UNIT_DIP, mQuestionFontsize); selectionText.setVisibility(View.GONE); button.setText(context.getString(R.string.select_answer)); button.setTextSize(TypedValue.COMPLEX_UNIT_DIP, mQuestionFontsize); button.setPadding(0, 0, 0, 7); // Give the button a click listener. This defines the alert as well. All the // click and selection behavior is defined here. button.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { alert_builder.setTitle(mPrompt.getQuestionText()).setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { boolean first = true; selectionText.setText(""); for (int i = 0; i < selections.length; i++) { if (selections[i]) { if (first) { first = false; selectionText.setText(context.getString(R.string.selected) + answer_items[i].toString()); selectionText.setVisibility(View.VISIBLE); } else { selectionText.setText(selectionText.getText() + ", " + answer_items[i].toString()); } } } } }); alert_builder.setMultiChoiceItems(answer_items, selections, new DialogInterface.OnMultiChoiceClickListener() { @Override public void onClick(DialogInterface dialog, int which, boolean isChecked) { selections[which] = isChecked; } }); AlertDialog alert = alert_builder.create(); alert.show(); } }); // Fill in previous answers List<Selection> ve = new ArrayList<Selection>(); if (prompt.getAnswerValue() != null) { ve = (List<Selection>) prompt.getAnswerValue().getValue(); } if (ve != null) { boolean first = true; for (int i = 0; i < selections.length; ++i) { String value = mItems.get(i).getValue(); boolean found = false; for (Selection s : ve) { if (value.equals(s.getValue())) { found = true; break; } } selections[i] = found; if (found) { if (first) { first = false; selectionText.setText(context.getString(R.string.selected) + answer_items[i].toString()); selectionText.setVisibility(View.VISIBLE); } else { selectionText.setText(selectionText.getText() + ", " + answer_items[i].toString()); } } } } addView(button); addView(selectionText); } @Override public IAnswerData getAnswer() { clearFocus(); List<Selection> vc = new ArrayList<Selection>(); for (int i = 0; i < mItems.size(); i++) { if (selections[i]) { SelectChoice sc = mItems.get(i); vc.add(new Selection(sc)); } } if (vc.size() == 0) { return null; } else { return new SelectMultiData(vc); } } @Override public void clearAnswer() { selectionText.setText(R.string.selected); selectionText.setVisibility(View.GONE); for (int i = 0; i < selections.length; i++) { selections[i] = false; } } @Override public void setFocus(Context context) { // Hide the soft keyboard if it's showing. InputMethodManager inputManager = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE); inputManager.hideSoftInputFromWindow(this.getWindowToken(), 0); } @Override public void setOnLongClickListener(OnLongClickListener l) { button.setOnLongClickListener(l); } @Override public void cancelLongPress() { super.cancelLongPress(); button.cancelLongPress(); } }
Java
/* * Copyright (C) 2009 University of Washington * * 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 org.odk.collect.android.widgets; import org.javarosa.core.model.data.IAnswerData; import org.javarosa.core.model.data.StringData; import org.javarosa.form.api.FormEntryPrompt; import android.content.Context; import android.text.InputType; import android.text.method.DigitsKeyListener; import android.util.TypedValue; /** * Widget that restricts values to integers. * * @author Carl Hartung (carlhartung@gmail.com) */ public class StringNumberWidget extends StringWidget { public StringNumberWidget(Context context, FormEntryPrompt prompt, boolean readOnlyOverride) { super(context, prompt, readOnlyOverride, true); mAnswer.setTextSize(TypedValue.COMPLEX_UNIT_DIP, mAnswerFontsize); mAnswer.setInputType(InputType.TYPE_NUMBER_FLAG_SIGNED); // needed to make long readonly text scroll mAnswer.setHorizontallyScrolling(false); mAnswer.setSingleLine(false); mAnswer.setKeyListener(new DigitsKeyListener() { @Override protected char[] getAcceptedChars() { char[] accepted = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '.', '-', '+', ' ', ',' }; return accepted; } }); if (prompt.isReadOnly()) { setBackgroundDrawable(null); setFocusable(false); setClickable(false); } String s = null; if (prompt.getAnswerValue() != null) s = (String) prompt.getAnswerValue().getValue(); if (s != null) { mAnswer.setText(s); } setupChangeListener(); } @Override public IAnswerData getAnswer() { clearFocus(); String s = mAnswer.getText().toString(); if (s == null || s.equals("")) { return null; } else { try { return new StringData(s); } catch (Exception NumberFormatException) { return null; } } } }
Java