text
stringlengths 30
1.67M
|
|---|
<s> package com . actionbarsherlock . internal . view ; import com . actionbarsherlock . internal . view . menu . SubMenuWrapper ; import com . actionbarsherlock . view . ActionProvider ; import android . view . View ; public class ActionProviderWrapper extends android . view . ActionProvider { private final ActionProvider mProvider ; public ActionProviderWrapper ( ActionProvider provider ) { super ( null ) ; mProvider = provider ; } public ActionProvider unwrap ( ) { return mProvider ; } @ Override public View onCreateActionView ( ) { return mProvider . onCreateActionView ( ) ; } @ Override public boolean hasSubMenu ( ) { return mProvider . hasSubMenu ( ) ; } @ Override public boolean onPerformDefaultAction ( ) { return mProvider . onPerformDefaultAction ( ) ; } @ Override public void onPrepareSubMenu ( android . view . SubMenu subMenu ) { mProvider . onPrepareSubMenu ( new SubMenuWrapper ( subMenu ) ) ; } } </s>
|
<s> 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 ( "<STR_LIT>" ) ; } 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 ; 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 ; } } ; mNativeItem . setOnActionExpandListener ( mNativeActionExpandListener ) ; } return this ; } } </s>
|
<s> package com . actionbarsherlock . internal . view . menu ; import android . content . Context ; import android . os . Parcelable ; import android . view . ViewGroup ; public interface MenuPresenter { public interface Callback { public void onCloseMenu ( MenuBuilder menu , boolean allMenusAreClosing ) ; public boolean onOpenSubMenu ( MenuBuilder subMenu ) ; } public void initForMenu ( Context context , MenuBuilder menu ) ; public MenuView getMenuView ( ViewGroup root ) ; public void updateMenuView ( boolean cleared ) ; public void setCallback ( Callback cb ) ; public boolean onSubMenuSelected ( SubMenuBuilder subMenu ) ; public void onCloseMenu ( MenuBuilder menu , boolean allMenusAreClosing ) ; public boolean flagActionItems ( ) ; public boolean expandItemActionView ( MenuBuilder menu , MenuItemImpl item ) ; public boolean collapseItemActionView ( MenuBuilder menu , MenuItemImpl item ) ; public int getId ( ) ; public Parcelable onSaveInstanceState ( ) ; public void onRestoreInstanceState ( Parcelable state ) ; } </s>
|
<s> package com . actionbarsherlock . internal . view . menu ; import java . util . WeakHashMap ; import android . content . ComponentName ; import android . content . Intent ; import android . view . KeyEvent ; import com . actionbarsherlock . view . Menu ; import com . actionbarsherlock . view . MenuItem ; import com . actionbarsherlock . view . SubMenu ; public class MenuWrapper implements Menu { private final android . view . Menu mNativeMenu ; private final WeakHashMap < android . view . MenuItem , MenuItem > mNativeMap = new WeakHashMap < android . view . MenuItem , MenuItem > ( ) ; public MenuWrapper ( android . view . Menu nativeMenu ) { mNativeMenu = nativeMenu ; } public android . view . Menu unwrap ( ) { return mNativeMenu ; } private MenuItem addInternal ( android . view . MenuItem nativeItem ) { MenuItem item = new MenuItemWrapper ( nativeItem ) ; mNativeMap . put ( nativeItem , item ) ; return item ; } @ Override public MenuItem add ( CharSequence title ) { return addInternal ( mNativeMenu . add ( title ) ) ; } @ Override public MenuItem add ( int titleRes ) { return addInternal ( mNativeMenu . add ( titleRes ) ) ; } @ Override public MenuItem add ( int groupId , int itemId , int order , CharSequence title ) { return addInternal ( mNativeMenu . add ( groupId , itemId , order , title ) ) ; } @ Override public MenuItem add ( int groupId , int itemId , int order , int titleRes ) { return addInternal ( mNativeMenu . add ( groupId , itemId , order , titleRes ) ) ; } private SubMenu addInternal ( android . view . SubMenu nativeSubMenu ) { SubMenu subMenu = new SubMenuWrapper ( nativeSubMenu ) ; android . view . MenuItem nativeItem = nativeSubMenu . getItem ( ) ; MenuItem item = subMenu . getItem ( ) ; mNativeMap . put ( nativeItem , item ) ; return subMenu ; } @ Override public SubMenu addSubMenu ( CharSequence title ) { return addInternal ( mNativeMenu . addSubMenu ( title ) ) ; } @ Override public SubMenu addSubMenu ( int titleRes ) { return addInternal ( mNativeMenu . addSubMenu ( titleRes ) ) ; } @ Override public SubMenu addSubMenu ( int groupId , int itemId , int order , CharSequence title ) { return addInternal ( mNativeMenu . addSubMenu ( groupId , itemId , order , title ) ) ; } @ Override public SubMenu addSubMenu ( int groupId , int itemId , int order , int titleRes ) { return addInternal ( mNativeMenu . addSubMenu ( groupId , itemId , order , titleRes ) ) ; } @ Override public int addIntentOptions ( int groupId , int itemId , int order , ComponentName caller , Intent [ ] specifics , Intent intent , int flags , MenuItem [ ] outSpecificItems ) { android . view . MenuItem [ ] nativeOutItems = new android . view . MenuItem [ outSpecificItems . length ] ; int result = mNativeMenu . addIntentOptions ( groupId , itemId , order , caller , specifics , intent , flags , nativeOutItems ) ; for ( int i = <NUM_LIT:0> , length = outSpecificItems . length ; i < length ; i ++ ) { outSpecificItems [ i ] = new MenuItemWrapper ( nativeOutItems [ i ] ) ; } return result ; } @ Override public void removeItem ( int id ) { mNativeMenu . removeItem ( id ) ; } @ Override public void removeGroup ( int groupId ) { mNativeMenu . removeGroup ( groupId ) ; } @ Override public void clear ( ) { mNativeMap . clear ( ) ; mNativeMenu . clear ( ) ; } @ Override public void setGroupCheckable ( int group , boolean checkable , boolean exclusive ) { mNativeMenu . setGroupCheckable ( group , checkable , exclusive ) ; } @ Override public void setGroupVisible ( int group , boolean visible ) { mNativeMenu . setGroupVisible ( group , visible ) ; } @ Override public void setGroupEnabled ( int group , boolean enabled ) { mNativeMenu . setGroupEnabled ( group , enabled ) ; } @ Override public boolean hasVisibleItems ( ) { return mNativeMenu . hasVisibleItems ( ) ; } @ Override public MenuItem findItem ( int id ) { android . view . MenuItem nativeItem = mNativeMenu . findItem ( id ) ; return findItem ( nativeItem ) ; } public MenuItem findItem ( android . view . MenuItem nativeItem ) { if ( nativeItem == null ) { return null ; } MenuItem wrapped = mNativeMap . get ( nativeItem ) ; if ( wrapped != null ) { return wrapped ; } return addInternal ( nativeItem ) ; } @ Override public int size ( ) { return mNativeMenu . size ( ) ; } @ Override public MenuItem getItem ( int index ) { android . view . MenuItem nativeItem = mNativeMenu . getItem ( index ) ; return findItem ( nativeItem ) ; } @ Override public void close ( ) { mNativeMenu . close ( ) ; } @ Override public boolean performShortcut ( int keyCode , KeyEvent event , int flags ) { return mNativeMenu . performShortcut ( keyCode , event , flags ) ; } @ Override public boolean isShortcutKey ( int keyCode , KeyEvent event ) { return mNativeMenu . isShortcutKey ( keyCode , event ) ; } @ Override public boolean performIdentifierAction ( int id , int flags ) { return mNativeMenu . performIdentifierAction ( id , flags ) ; } @ Override public void setQwertyMode ( boolean isQwerty ) { mNativeMenu . setQwertyMode ( isQwerty ) ; } } </s>
|
<s> package com . actionbarsherlock . internal . view . menu ; import java . util . ArrayList ; import android . content . Context ; import android . os . Build ; import android . view . LayoutInflater ; import android . view . View ; import android . view . ViewGroup ; public abstract class BaseMenuPresenter implements MenuPresenter { private static final boolean IS_HONEYCOMB = Build . VERSION . SDK_INT >= Build . VERSION_CODES . HONEYCOMB ; protected Context mSystemContext ; protected Context mContext ; protected MenuBuilder mMenu ; protected LayoutInflater mSystemInflater ; protected LayoutInflater mInflater ; private Callback mCallback ; private int mMenuLayoutRes ; private int mItemLayoutRes ; protected MenuView mMenuView ; private int mId ; public BaseMenuPresenter ( Context context , int menuLayoutRes , int itemLayoutRes ) { mSystemContext = context ; mSystemInflater = LayoutInflater . from ( context ) ; mMenuLayoutRes = menuLayoutRes ; mItemLayoutRes = itemLayoutRes ; } @ Override public void initForMenu ( Context context , MenuBuilder menu ) { mContext = context ; mInflater = LayoutInflater . from ( mContext ) ; mMenu = menu ; } @ Override public MenuView getMenuView ( ViewGroup root ) { if ( mMenuView == null ) { mMenuView = ( MenuView ) mSystemInflater . inflate ( mMenuLayoutRes , root , false ) ; mMenuView . initialize ( mMenu ) ; updateMenuView ( true ) ; } return mMenuView ; } public void updateMenuView ( boolean cleared ) { final ViewGroup parent = ( ViewGroup ) mMenuView ; if ( parent == null ) return ; int childIndex = <NUM_LIT:0> ; if ( mMenu != null ) { mMenu . flagActionItems ( ) ; ArrayList < MenuItemImpl > visibleItems = mMenu . getVisibleItems ( ) ; final int itemCount = visibleItems . size ( ) ; for ( int i = <NUM_LIT:0> ; i < itemCount ; i ++ ) { MenuItemImpl item = visibleItems . get ( i ) ; if ( shouldIncludeItem ( childIndex , item ) ) { final View convertView = parent . getChildAt ( childIndex ) ; final MenuItemImpl oldItem = convertView instanceof MenuView . ItemView ? ( ( MenuView . ItemView ) convertView ) . getItemData ( ) : null ; final View itemView = getItemView ( item , convertView , parent ) ; if ( item != oldItem ) { itemView . setPressed ( false ) ; if ( IS_HONEYCOMB ) itemView . jumpDrawablesToCurrentState ( ) ; } if ( itemView != convertView ) { addItemView ( itemView , childIndex ) ; } childIndex ++ ; } } } while ( childIndex < parent . getChildCount ( ) ) { if ( ! filterLeftoverView ( parent , childIndex ) ) { childIndex ++ ; } } } protected void addItemView ( View itemView , int childIndex ) { final ViewGroup currentParent = ( ViewGroup ) itemView . getParent ( ) ; if ( currentParent != null ) { currentParent . removeView ( itemView ) ; } ( ( ViewGroup ) mMenuView ) . addView ( itemView , childIndex ) ; } protected boolean filterLeftoverView ( ViewGroup parent , int childIndex ) { parent . removeViewAt ( childIndex ) ; return true ; } public void setCallback ( Callback cb ) { mCallback = cb ; } public MenuView . ItemView createItemView ( ViewGroup parent ) { return ( MenuView . ItemView ) mSystemInflater . inflate ( mItemLayoutRes , parent , false ) ; } public View getItemView ( MenuItemImpl item , View convertView , ViewGroup parent ) { MenuView . ItemView itemView ; if ( convertView instanceof MenuView . ItemView ) { itemView = ( MenuView . ItemView ) convertView ; } else { itemView = createItemView ( parent ) ; } bindItemView ( item , itemView ) ; return ( View ) itemView ; } public abstract void bindItemView ( MenuItemImpl item , MenuView . ItemView itemView ) ; public boolean shouldIncludeItem ( int childIndex , MenuItemImpl item ) { return true ; } public void onCloseMenu ( MenuBuilder menu , boolean allMenusAreClosing ) { if ( mCallback != null ) { mCallback . onCloseMenu ( menu , allMenusAreClosing ) ; } } public boolean onSubMenuSelected ( SubMenuBuilder menu ) { if ( mCallback != null ) { return mCallback . onOpenSubMenu ( menu ) ; } return false ; } public boolean flagActionItems ( ) { return false ; } public boolean expandItemActionView ( MenuBuilder menu , MenuItemImpl item ) { return false ; } public boolean collapseItemActionView ( MenuBuilder menu , MenuItemImpl item ) { return false ; } public int getId ( ) { return mId ; } public void setId ( int id ) { mId = id ; } } </s>
|
<s> package com . actionbarsherlock . internal . view . menu ; import java . util . ArrayList ; import java . util . List ; import android . content . ComponentName ; import android . content . Context ; import android . content . Intent ; import android . content . pm . PackageManager ; import android . content . pm . ResolveInfo ; import android . view . KeyEvent ; import com . actionbarsherlock . view . Menu ; import com . actionbarsherlock . view . MenuItem ; import com . actionbarsherlock . view . SubMenu ; public class ActionMenu implements Menu { private Context mContext ; private boolean mIsQwerty ; private ArrayList < ActionMenuItem > mItems ; public ActionMenu ( Context context ) { mContext = context ; mItems = new ArrayList < ActionMenuItem > ( ) ; } public Context getContext ( ) { return mContext ; } public MenuItem add ( CharSequence title ) { return add ( <NUM_LIT:0> , <NUM_LIT:0> , <NUM_LIT:0> , title ) ; } public MenuItem add ( int titleRes ) { return add ( <NUM_LIT:0> , <NUM_LIT:0> , <NUM_LIT:0> , titleRes ) ; } public MenuItem add ( int groupId , int itemId , int order , int titleRes ) { return add ( groupId , itemId , order , mContext . getResources ( ) . getString ( titleRes ) ) ; } public MenuItem add ( int groupId , int itemId , int order , CharSequence title ) { ActionMenuItem item = new ActionMenuItem ( getContext ( ) , groupId , itemId , <NUM_LIT:0> , order , title ) ; mItems . add ( order , item ) ; return item ; } public int addIntentOptions ( int groupId , int itemId , int order , ComponentName caller , Intent [ ] specifics , Intent intent , int flags , MenuItem [ ] outSpecificItems ) { PackageManager pm = mContext . getPackageManager ( ) ; final List < ResolveInfo > lri = pm . queryIntentActivityOptions ( caller , specifics , intent , <NUM_LIT:0> ) ; final int N = lri != null ? lri . size ( ) : <NUM_LIT:0> ; if ( ( flags & FLAG_APPEND_TO_GROUP ) == <NUM_LIT:0> ) { removeGroup ( groupId ) ; } for ( int i = <NUM_LIT:0> ; i < N ; i ++ ) { final ResolveInfo ri = lri . get ( i ) ; Intent rintent = new Intent ( ri . specificIndex < <NUM_LIT:0> ? intent : specifics [ ri . specificIndex ] ) ; rintent . setComponent ( new ComponentName ( ri . activityInfo . applicationInfo . packageName , ri . activityInfo . name ) ) ; final MenuItem item = add ( groupId , itemId , order , ri . loadLabel ( pm ) ) . setIcon ( ri . loadIcon ( pm ) ) . setIntent ( rintent ) ; if ( outSpecificItems != null && ri . specificIndex >= <NUM_LIT:0> ) { outSpecificItems [ ri . specificIndex ] = item ; } } return N ; } public SubMenu addSubMenu ( CharSequence title ) { return null ; } public SubMenu addSubMenu ( int titleRes ) { return null ; } public SubMenu addSubMenu ( int groupId , int itemId , int order , CharSequence title ) { return null ; } public SubMenu addSubMenu ( int groupId , int itemId , int order , int titleRes ) { return null ; } public void clear ( ) { mItems . clear ( ) ; } public void close ( ) { } private int findItemIndex ( int id ) { final ArrayList < ActionMenuItem > items = mItems ; final int itemCount = items . size ( ) ; for ( int i = <NUM_LIT:0> ; i < itemCount ; i ++ ) { if ( items . get ( i ) . getItemId ( ) == id ) { return i ; } } return - <NUM_LIT:1> ; } public MenuItem findItem ( int id ) { return mItems . get ( findItemIndex ( id ) ) ; } public MenuItem getItem ( int index ) { return mItems . get ( index ) ; } public boolean hasVisibleItems ( ) { final ArrayList < ActionMenuItem > items = mItems ; final int itemCount = items . size ( ) ; for ( int i = <NUM_LIT:0> ; i < itemCount ; i ++ ) { if ( items . get ( i ) . isVisible ( ) ) { return true ; } } return false ; } private ActionMenuItem findItemWithShortcut ( int keyCode , KeyEvent event ) { final boolean qwerty = mIsQwerty ; final ArrayList < ActionMenuItem > items = mItems ; final int itemCount = items . size ( ) ; for ( int i = <NUM_LIT:0> ; i < itemCount ; i ++ ) { ActionMenuItem item = items . get ( i ) ; final char shortcut = qwerty ? item . getAlphabeticShortcut ( ) : item . getNumericShortcut ( ) ; if ( keyCode == shortcut ) { return item ; } } return null ; } public boolean isShortcutKey ( int keyCode , KeyEvent event ) { return findItemWithShortcut ( keyCode , event ) != null ; } public boolean performIdentifierAction ( int id , int flags ) { final int index = findItemIndex ( id ) ; if ( index < <NUM_LIT:0> ) { return false ; } return mItems . get ( index ) . invoke ( ) ; } public boolean performShortcut ( int keyCode , KeyEvent event , int flags ) { ActionMenuItem item = findItemWithShortcut ( keyCode , event ) ; if ( item == null ) { return false ; } return item . invoke ( ) ; } public void removeGroup ( int groupId ) { final ArrayList < ActionMenuItem > items = mItems ; int itemCount = items . size ( ) ; int i = <NUM_LIT:0> ; while ( i < itemCount ) { if ( items . get ( i ) . getGroupId ( ) == groupId ) { items . remove ( i ) ; itemCount -- ; } else { i ++ ; } } } public void removeItem ( int id ) { mItems . remove ( findItemIndex ( id ) ) ; } public void setGroupCheckable ( int group , boolean checkable , boolean exclusive ) { final ArrayList < ActionMenuItem > items = mItems ; final int itemCount = items . size ( ) ; for ( int i = <NUM_LIT:0> ; i < itemCount ; i ++ ) { ActionMenuItem item = items . get ( i ) ; if ( item . getGroupId ( ) == group ) { item . setCheckable ( checkable ) ; item . setExclusiveCheckable ( exclusive ) ; } } } public void setGroupEnabled ( int group , boolean enabled ) { final ArrayList < ActionMenuItem > items = mItems ; final int itemCount = items . size ( ) ; for ( int i = <NUM_LIT:0> ; i < itemCount ; i ++ ) { ActionMenuItem item = items . get ( i ) ; if ( item . getGroupId ( ) == group ) { item . setEnabled ( enabled ) ; } } } public void setGroupVisible ( int group , boolean visible ) { final ArrayList < ActionMenuItem > items = mItems ; final int itemCount = items . size ( ) ; for ( int i = <NUM_LIT:0> ; i < itemCount ; i ++ ) { ActionMenuItem item = items . get ( i ) ; if ( item . getGroupId ( ) == group ) { item . setVisible ( visible ) ; } } } public void setQwertyMode ( boolean isQwerty ) { mIsQwerty = isQwerty ; } public int size ( ) { return mItems . size ( ) ; } } </s>
|
<s> package com . actionbarsherlock . internal . view . menu ; import android . content . Context ; import android . content . res . Configuration ; import android . graphics . Canvas ; import android . os . Build ; import android . util . AttributeSet ; import android . view . Gravity ; import android . view . View ; import android . view . ViewGroup ; import android . view . accessibility . AccessibilityEvent ; import android . widget . LinearLayout ; import com . actionbarsherlock . internal . widget . IcsLinearLayout ; public class ActionMenuView extends IcsLinearLayout implements MenuBuilder . ItemInvoker , MenuView { private static final boolean IS_FROYO = Build . VERSION . SDK_INT >= Build . VERSION_CODES . FROYO ; static final int MIN_CELL_SIZE = <NUM_LIT> ; static final int GENERATED_ITEM_PADDING = <NUM_LIT:4> ; private MenuBuilder mMenu ; private boolean mReserveOverflow ; private ActionMenuPresenter mPresenter ; private boolean mFormatItems ; private int mFormatItemsWidth ; private int mMinCellSize ; private int mGeneratedItemPadding ; private boolean mFirst = true ; public ActionMenuView ( Context context ) { this ( context , null ) ; } public ActionMenuView ( Context context , AttributeSet attrs ) { super ( context , attrs ) ; setBaselineAligned ( false ) ; final float density = context . getResources ( ) . getDisplayMetrics ( ) . density ; mMinCellSize = ( int ) ( MIN_CELL_SIZE * density ) ; mGeneratedItemPadding = ( int ) ( GENERATED_ITEM_PADDING * density ) ; } public void setPresenter ( ActionMenuPresenter presenter ) { mPresenter = presenter ; } public boolean isExpandedFormat ( ) { return mFormatItems ; } @ Override public void onConfigurationChanged ( Configuration newConfig ) { if ( IS_FROYO ) { super . onConfigurationChanged ( newConfig ) ; } mPresenter . updateMenuView ( false ) ; if ( mPresenter != null && mPresenter . isOverflowMenuShowing ( ) ) { mPresenter . hideOverflowMenu ( ) ; mPresenter . showOverflowMenu ( ) ; } } @ Override protected void onDraw ( Canvas canvas ) { if ( ! IS_FROYO && mFirst ) { mFirst = false ; requestLayout ( ) ; return ; } super . onDraw ( canvas ) ; } @ Override protected void onMeasure ( int widthMeasureSpec , int heightMeasureSpec ) { final boolean wasFormatted = mFormatItems ; mFormatItems = MeasureSpec . getMode ( widthMeasureSpec ) == MeasureSpec . EXACTLY ; if ( wasFormatted != mFormatItems ) { mFormatItemsWidth = <NUM_LIT:0> ; } final int widthSize = MeasureSpec . getMode ( widthMeasureSpec ) ; if ( mFormatItems && mMenu != null && widthSize != mFormatItemsWidth ) { mFormatItemsWidth = widthSize ; mMenu . onItemsChanged ( true ) ; } if ( mFormatItems ) { onMeasureExactFormat ( widthMeasureSpec , heightMeasureSpec ) ; } else { super . onMeasure ( widthMeasureSpec , heightMeasureSpec ) ; } } private void onMeasureExactFormat ( int widthMeasureSpec , int heightMeasureSpec ) { final int heightMode = MeasureSpec . getMode ( heightMeasureSpec ) ; int widthSize = MeasureSpec . getSize ( widthMeasureSpec ) ; int heightSize = MeasureSpec . getSize ( heightMeasureSpec ) ; final int widthPadding = getPaddingLeft ( ) + getPaddingRight ( ) ; final int heightPadding = getPaddingTop ( ) + getPaddingBottom ( ) ; widthSize -= widthPadding ; final int cellCount = widthSize / mMinCellSize ; final int cellSizeRemaining = widthSize % mMinCellSize ; if ( cellCount == <NUM_LIT:0> ) { setMeasuredDimension ( widthSize , <NUM_LIT:0> ) ; return ; } final int cellSize = mMinCellSize + cellSizeRemaining / cellCount ; int cellsRemaining = cellCount ; int maxChildHeight = <NUM_LIT:0> ; int maxCellsUsed = <NUM_LIT:0> ; int expandableItemCount = <NUM_LIT:0> ; int visibleItemCount = <NUM_LIT:0> ; boolean hasOverflow = false ; long smallestItemsAt = <NUM_LIT:0> ; final int childCount = getChildCount ( ) ; for ( int i = <NUM_LIT:0> ; i < childCount ; i ++ ) { final View child = getChildAt ( i ) ; if ( child . getVisibility ( ) == GONE ) continue ; final boolean isGeneratedItem = child instanceof ActionMenuItemView ; visibleItemCount ++ ; if ( isGeneratedItem ) { child . setPadding ( mGeneratedItemPadding , <NUM_LIT:0> , mGeneratedItemPadding , <NUM_LIT:0> ) ; } final LayoutParams lp = ( LayoutParams ) child . getLayoutParams ( ) ; lp . expanded = false ; lp . extraPixels = <NUM_LIT:0> ; lp . cellsUsed = <NUM_LIT:0> ; lp . expandable = false ; lp . leftMargin = <NUM_LIT:0> ; lp . rightMargin = <NUM_LIT:0> ; lp . preventEdgeOffset = isGeneratedItem && ( ( ActionMenuItemView ) child ) . hasText ( ) ; final int cellsAvailable = lp . isOverflowButton ? <NUM_LIT:1> : cellsRemaining ; final int cellsUsed = measureChildForCells ( child , cellSize , cellsAvailable , heightMeasureSpec , heightPadding ) ; maxCellsUsed = Math . max ( maxCellsUsed , cellsUsed ) ; if ( lp . expandable ) expandableItemCount ++ ; if ( lp . isOverflowButton ) hasOverflow = true ; cellsRemaining -= cellsUsed ; maxChildHeight = Math . max ( maxChildHeight , child . getMeasuredHeight ( ) ) ; if ( cellsUsed == <NUM_LIT:1> ) smallestItemsAt |= ( <NUM_LIT:1> << i ) ; } final boolean centerSingleExpandedItem = hasOverflow && visibleItemCount == <NUM_LIT:2> ; boolean needsExpansion = false ; while ( expandableItemCount > <NUM_LIT:0> && cellsRemaining > <NUM_LIT:0> ) { int minCells = Integer . MAX_VALUE ; long minCellsAt = <NUM_LIT:0> ; int minCellsItemCount = <NUM_LIT:0> ; for ( int i = <NUM_LIT:0> ; i < childCount ; i ++ ) { final View child = getChildAt ( i ) ; final LayoutParams lp = ( LayoutParams ) child . getLayoutParams ( ) ; if ( ! lp . expandable ) continue ; if ( lp . cellsUsed < minCells ) { minCells = lp . cellsUsed ; minCellsAt = <NUM_LIT:1> << i ; minCellsItemCount = <NUM_LIT:1> ; } else if ( lp . cellsUsed == minCells ) { minCellsAt |= <NUM_LIT:1> << i ; minCellsItemCount ++ ; } } smallestItemsAt |= minCellsAt ; if ( minCellsItemCount > cellsRemaining ) break ; minCells ++ ; for ( int i = <NUM_LIT:0> ; i < childCount ; i ++ ) { final View child = getChildAt ( i ) ; final LayoutParams lp = ( LayoutParams ) child . getLayoutParams ( ) ; if ( ( minCellsAt & ( <NUM_LIT:1> << i ) ) == <NUM_LIT:0> ) { if ( lp . cellsUsed == minCells ) smallestItemsAt |= <NUM_LIT:1> << i ; continue ; } if ( centerSingleExpandedItem && lp . preventEdgeOffset && cellsRemaining == <NUM_LIT:1> ) { child . setPadding ( mGeneratedItemPadding + cellSize , <NUM_LIT:0> , mGeneratedItemPadding , <NUM_LIT:0> ) ; } lp . cellsUsed ++ ; lp . expanded = true ; cellsRemaining -- ; } needsExpansion = true ; } final boolean singleItem = ! hasOverflow && visibleItemCount == <NUM_LIT:1> ; if ( cellsRemaining > <NUM_LIT:0> && smallestItemsAt != <NUM_LIT:0> && ( cellsRemaining < visibleItemCount - <NUM_LIT:1> || singleItem || maxCellsUsed > <NUM_LIT:1> ) ) { float expandCount = Long . bitCount ( smallestItemsAt ) ; if ( ! singleItem ) { if ( ( smallestItemsAt & <NUM_LIT:1> ) != <NUM_LIT:0> ) { LayoutParams lp = ( LayoutParams ) getChildAt ( <NUM_LIT:0> ) . getLayoutParams ( ) ; if ( ! lp . preventEdgeOffset ) expandCount -= <NUM_LIT> ; } if ( ( smallestItemsAt & ( <NUM_LIT:1> << ( childCount - <NUM_LIT:1> ) ) ) != <NUM_LIT:0> ) { LayoutParams lp = ( ( LayoutParams ) getChildAt ( childCount - <NUM_LIT:1> ) . getLayoutParams ( ) ) ; if ( ! lp . preventEdgeOffset ) expandCount -= <NUM_LIT> ; } } final int extraPixels = expandCount > <NUM_LIT:0> ? ( int ) ( cellsRemaining * cellSize / expandCount ) : <NUM_LIT:0> ; for ( int i = <NUM_LIT:0> ; i < childCount ; i ++ ) { if ( ( smallestItemsAt & ( <NUM_LIT:1> << i ) ) == <NUM_LIT:0> ) continue ; final View child = getChildAt ( i ) ; final LayoutParams lp = ( LayoutParams ) child . getLayoutParams ( ) ; if ( child instanceof ActionMenuItemView ) { lp . extraPixels = extraPixels ; lp . expanded = true ; if ( i == <NUM_LIT:0> && ! lp . preventEdgeOffset ) { lp . leftMargin = - extraPixels / <NUM_LIT:2> ; } needsExpansion = true ; } else if ( lp . isOverflowButton ) { lp . extraPixels = extraPixels ; lp . expanded = true ; lp . rightMargin = - extraPixels / <NUM_LIT:2> ; needsExpansion = true ; } else { if ( i != <NUM_LIT:0> ) { lp . leftMargin = extraPixels / <NUM_LIT:2> ; } if ( i != childCount - <NUM_LIT:1> ) { lp . rightMargin = extraPixels / <NUM_LIT:2> ; } } } cellsRemaining = <NUM_LIT:0> ; } if ( needsExpansion ) { int heightSpec = MeasureSpec . makeMeasureSpec ( heightSize - heightPadding , heightMode ) ; for ( int i = <NUM_LIT:0> ; i < childCount ; i ++ ) { final View child = getChildAt ( i ) ; final LayoutParams lp = ( LayoutParams ) child . getLayoutParams ( ) ; if ( ! lp . expanded ) continue ; final int width = lp . cellsUsed * cellSize + lp . extraPixels ; child . measure ( MeasureSpec . makeMeasureSpec ( width , MeasureSpec . EXACTLY ) , heightSpec ) ; } } if ( heightMode != MeasureSpec . EXACTLY ) { heightSize = maxChildHeight ; } setMeasuredDimension ( widthSize , heightSize ) ; } static int measureChildForCells ( View child , int cellSize , int cellsRemaining , int parentHeightMeasureSpec , int parentHeightPadding ) { final LayoutParams lp = ( LayoutParams ) child . getLayoutParams ( ) ; final int childHeightSize = MeasureSpec . getSize ( parentHeightMeasureSpec ) - parentHeightPadding ; final int childHeightMode = MeasureSpec . getMode ( parentHeightMeasureSpec ) ; final int childHeightSpec = MeasureSpec . makeMeasureSpec ( childHeightSize , childHeightMode ) ; int cellsUsed = <NUM_LIT:0> ; if ( cellsRemaining > <NUM_LIT:0> ) { final int childWidthSpec = MeasureSpec . makeMeasureSpec ( cellSize * cellsRemaining , MeasureSpec . AT_MOST ) ; child . measure ( childWidthSpec , childHeightSpec ) ; final int measuredWidth = child . getMeasuredWidth ( ) ; cellsUsed = measuredWidth / cellSize ; if ( measuredWidth % cellSize != <NUM_LIT:0> ) cellsUsed ++ ; } final ActionMenuItemView itemView = child instanceof ActionMenuItemView ? ( ActionMenuItemView ) child : null ; final boolean expandable = ! lp . isOverflowButton && itemView != null && itemView . hasText ( ) ; lp . expandable = expandable ; lp . cellsUsed = cellsUsed ; final int targetWidth = cellsUsed * cellSize ; child . measure ( MeasureSpec . makeMeasureSpec ( targetWidth , MeasureSpec . EXACTLY ) , childHeightSpec ) ; return cellsUsed ; } @ Override protected void onLayout ( boolean changed , int left , int top , int right , int bottom ) { if ( ! mFormatItems ) { super . onLayout ( changed , left , top , right , bottom ) ; return ; } final int childCount = getChildCount ( ) ; final int midVertical = ( top + bottom ) / <NUM_LIT:2> ; final int dividerWidth = <NUM_LIT:0> ; int overflowWidth = <NUM_LIT:0> ; int nonOverflowCount = <NUM_LIT:0> ; int widthRemaining = right - left - getPaddingRight ( ) - getPaddingLeft ( ) ; boolean hasOverflow = false ; for ( int i = <NUM_LIT:0> ; i < childCount ; i ++ ) { final View v = getChildAt ( i ) ; if ( v . getVisibility ( ) == GONE ) { continue ; } LayoutParams p = ( LayoutParams ) v . getLayoutParams ( ) ; if ( p . isOverflowButton ) { overflowWidth = v . getMeasuredWidth ( ) ; if ( hasDividerBeforeChildAt ( i ) ) { overflowWidth += dividerWidth ; } int height = v . getMeasuredHeight ( ) ; int r = getWidth ( ) - getPaddingRight ( ) - p . rightMargin ; int l = r - overflowWidth ; int t = midVertical - ( height / <NUM_LIT:2> ) ; int b = t + height ; v . layout ( l , t , r , b ) ; widthRemaining -= overflowWidth ; hasOverflow = true ; } else { final int size = v . getMeasuredWidth ( ) + p . leftMargin + p . rightMargin ; widthRemaining -= size ; nonOverflowCount ++ ; } } if ( childCount == <NUM_LIT:1> && ! hasOverflow ) { final View v = getChildAt ( <NUM_LIT:0> ) ; final int width = v . getMeasuredWidth ( ) ; final int height = v . getMeasuredHeight ( ) ; final int midHorizontal = ( right - left ) / <NUM_LIT:2> ; final int l = midHorizontal - width / <NUM_LIT:2> ; final int t = midVertical - height / <NUM_LIT:2> ; v . layout ( l , t , l + width , t + height ) ; return ; } final int spacerCount = nonOverflowCount - ( hasOverflow ? <NUM_LIT:0> : <NUM_LIT:1> ) ; final int spacerSize = Math . max ( <NUM_LIT:0> , spacerCount > <NUM_LIT:0> ? widthRemaining / spacerCount : <NUM_LIT:0> ) ; int startLeft = getPaddingLeft ( ) ; for ( int i = <NUM_LIT:0> ; i < childCount ; i ++ ) { final View v = getChildAt ( i ) ; final LayoutParams lp = ( LayoutParams ) v . getLayoutParams ( ) ; if ( v . getVisibility ( ) == GONE || lp . isOverflowButton ) { continue ; } startLeft += lp . leftMargin ; int width = v . getMeasuredWidth ( ) ; int height = v . getMeasuredHeight ( ) ; int t = midVertical - height / <NUM_LIT:2> ; v . layout ( startLeft , t , startLeft + width , t + height ) ; startLeft += width + lp . rightMargin + spacerSize ; } } @ Override public void onDetachedFromWindow ( ) { super . onDetachedFromWindow ( ) ; mPresenter . dismissPopupMenus ( ) ; } public boolean isOverflowReserved ( ) { return mReserveOverflow ; } public void setOverflowReserved ( boolean reserveOverflow ) { mReserveOverflow = reserveOverflow ; } @ Override protected LayoutParams generateDefaultLayoutParams ( ) { LayoutParams params = new LayoutParams ( LayoutParams . WRAP_CONTENT , LayoutParams . WRAP_CONTENT ) ; params . gravity = Gravity . CENTER_VERTICAL ; return params ; } @ Override public LayoutParams generateLayoutParams ( AttributeSet attrs ) { return new LayoutParams ( getContext ( ) , attrs ) ; } @ Override protected LayoutParams generateLayoutParams ( ViewGroup . LayoutParams p ) { if ( p instanceof LayoutParams ) { LayoutParams result = new LayoutParams ( ( LayoutParams ) p ) ; if ( result . gravity <= Gravity . NO_GRAVITY ) { result . gravity = Gravity . CENTER_VERTICAL ; } return result ; } return generateDefaultLayoutParams ( ) ; } @ Override protected boolean checkLayoutParams ( ViewGroup . LayoutParams p ) { return p != null && p instanceof LayoutParams ; } public LayoutParams generateOverflowButtonLayoutParams ( ) { LayoutParams result = generateDefaultLayoutParams ( ) ; result . isOverflowButton = true ; return result ; } public boolean invokeItem ( MenuItemImpl item ) { return mMenu . performItemAction ( item , <NUM_LIT:0> ) ; } public int getWindowAnimations ( ) { return <NUM_LIT:0> ; } public void initialize ( MenuBuilder menu ) { mMenu = menu ; } protected boolean hasDividerBeforeChildAt ( int childIndex ) { final View childBefore = getChildAt ( childIndex - <NUM_LIT:1> ) ; final View child = getChildAt ( childIndex ) ; boolean result = false ; if ( childIndex < getChildCount ( ) && childBefore instanceof ActionMenuChildView ) { result |= ( ( ActionMenuChildView ) childBefore ) . needsDividerAfter ( ) ; } if ( childIndex > <NUM_LIT:0> && child instanceof ActionMenuChildView ) { result |= ( ( ActionMenuChildView ) child ) . needsDividerBefore ( ) ; } return result ; } public boolean dispatchPopulateAccessibilityEvent ( AccessibilityEvent event ) { return false ; } public interface ActionMenuChildView { public boolean needsDividerBefore ( ) ; public boolean needsDividerAfter ( ) ; } public static class LayoutParams extends LinearLayout . LayoutParams { public boolean isOverflowButton ; public int cellsUsed ; public int extraPixels ; public boolean expandable ; public boolean preventEdgeOffset ; public boolean expanded ; public LayoutParams ( Context c , AttributeSet attrs ) { super ( c , attrs ) ; } public LayoutParams ( LayoutParams other ) { super ( ( LinearLayout . LayoutParams ) other ) ; isOverflowButton = other . isOverflowButton ; } public LayoutParams ( int width , int height ) { super ( width , height ) ; isOverflowButton = false ; } public LayoutParams ( int width , int height , boolean isOverflowButton ) { super ( width , height ) ; this . isOverflowButton = isOverflowButton ; } } } </s>
|
<s> package com . actionbarsherlock . internal . view . menu ; import java . lang . ref . WeakReference ; import java . util . ArrayList ; import java . util . HashMap ; import java . util . List ; import java . util . concurrent . CopyOnWriteArrayList ; import android . content . ComponentName ; import android . content . Context ; import android . content . Intent ; import android . content . pm . PackageManager ; import android . content . pm . ResolveInfo ; import android . content . res . Configuration ; import android . content . res . Resources ; import android . graphics . drawable . Drawable ; import android . os . Bundle ; import android . os . Parcelable ; import android . util . SparseArray ; import android . view . ContextMenu . ContextMenuInfo ; import android . view . KeyCharacterMap ; import android . view . KeyEvent ; import android . view . View ; import com . actionbarsherlock . R ; import com . actionbarsherlock . view . ActionProvider ; import com . actionbarsherlock . view . Menu ; import com . actionbarsherlock . view . MenuItem ; import com . actionbarsherlock . view . SubMenu ; public class MenuBuilder implements Menu { private static final String PRESENTER_KEY = "<STR_LIT>" ; private static final String ACTION_VIEW_STATES_KEY = "<STR_LIT>" ; private static final String EXPANDED_ACTION_VIEW_ID = "<STR_LIT>" ; private static final int [ ] sCategoryToOrder = new int [ ] { <NUM_LIT:1> , <NUM_LIT:4> , <NUM_LIT:5> , <NUM_LIT:3> , <NUM_LIT:2> , <NUM_LIT:0> , } ; private final Context mContext ; private final Resources mResources ; private boolean mQwertyMode ; private boolean mShortcutsVisible ; private Callback mCallback ; private ArrayList < MenuItemImpl > mItems ; private ArrayList < MenuItemImpl > mVisibleItems ; private boolean mIsVisibleItemsStale ; private ArrayList < MenuItemImpl > mActionItems ; private ArrayList < MenuItemImpl > mNonActionItems ; private boolean mIsActionItemsStale ; private int mDefaultShowAsAction = MenuItem . SHOW_AS_ACTION_NEVER ; private ContextMenuInfo mCurrentMenuInfo ; CharSequence mHeaderTitle ; Drawable mHeaderIcon ; View mHeaderView ; private boolean mPreventDispatchingItemsChanged = false ; private boolean mItemsChangedWhileDispatchPrevented = false ; private boolean mOptionalIconsVisible = false ; private boolean mIsClosing = false ; private ArrayList < MenuItemImpl > mTempShortcutItemList = new ArrayList < MenuItemImpl > ( ) ; private CopyOnWriteArrayList < WeakReference < MenuPresenter > > mPresenters = new CopyOnWriteArrayList < WeakReference < MenuPresenter > > ( ) ; private MenuItemImpl mExpandedItem ; public interface Callback { public boolean onMenuItemSelected ( MenuBuilder menu , MenuItem item ) ; public void onMenuModeChange ( MenuBuilder menu ) ; } public interface ItemInvoker { public boolean invokeItem ( MenuItemImpl item ) ; } public MenuBuilder ( Context context ) { mContext = context ; mResources = context . getResources ( ) ; mItems = new ArrayList < MenuItemImpl > ( ) ; mVisibleItems = new ArrayList < MenuItemImpl > ( ) ; mIsVisibleItemsStale = true ; mActionItems = new ArrayList < MenuItemImpl > ( ) ; mNonActionItems = new ArrayList < MenuItemImpl > ( ) ; mIsActionItemsStale = true ; setShortcutsVisibleInner ( true ) ; } public MenuBuilder setDefaultShowAsAction ( int defaultShowAsAction ) { mDefaultShowAsAction = defaultShowAsAction ; return this ; } public void addMenuPresenter ( MenuPresenter presenter ) { mPresenters . add ( new WeakReference < MenuPresenter > ( presenter ) ) ; presenter . initForMenu ( mContext , this ) ; mIsActionItemsStale = true ; } public void removeMenuPresenter ( MenuPresenter presenter ) { for ( WeakReference < MenuPresenter > ref : mPresenters ) { final MenuPresenter item = ref . get ( ) ; if ( item == null || item == presenter ) { mPresenters . remove ( ref ) ; } } } private void dispatchPresenterUpdate ( boolean cleared ) { if ( mPresenters . isEmpty ( ) ) return ; stopDispatchingItemsChanged ( ) ; for ( WeakReference < MenuPresenter > ref : mPresenters ) { final MenuPresenter presenter = ref . get ( ) ; if ( presenter == null ) { mPresenters . remove ( ref ) ; } else { presenter . updateMenuView ( cleared ) ; } } startDispatchingItemsChanged ( ) ; } private boolean dispatchSubMenuSelected ( SubMenuBuilder subMenu ) { if ( mPresenters . isEmpty ( ) ) return false ; boolean result = false ; for ( WeakReference < MenuPresenter > ref : mPresenters ) { final MenuPresenter presenter = ref . get ( ) ; if ( presenter == null ) { mPresenters . remove ( ref ) ; } else if ( ! result ) { result = presenter . onSubMenuSelected ( subMenu ) ; } } return result ; } private void dispatchSaveInstanceState ( Bundle outState ) { if ( mPresenters . isEmpty ( ) ) return ; SparseArray < Parcelable > presenterStates = new SparseArray < Parcelable > ( ) ; for ( WeakReference < MenuPresenter > ref : mPresenters ) { final MenuPresenter presenter = ref . get ( ) ; if ( presenter == null ) { mPresenters . remove ( ref ) ; } else { final int id = presenter . getId ( ) ; if ( id > <NUM_LIT:0> ) { final Parcelable state = presenter . onSaveInstanceState ( ) ; if ( state != null ) { presenterStates . put ( id , state ) ; } } } } outState . putSparseParcelableArray ( PRESENTER_KEY , presenterStates ) ; } private void dispatchRestoreInstanceState ( Bundle state ) { SparseArray < Parcelable > presenterStates = state . getSparseParcelableArray ( PRESENTER_KEY ) ; if ( presenterStates == null || mPresenters . isEmpty ( ) ) return ; for ( WeakReference < MenuPresenter > ref : mPresenters ) { final MenuPresenter presenter = ref . get ( ) ; if ( presenter == null ) { mPresenters . remove ( ref ) ; } else { final int id = presenter . getId ( ) ; if ( id > <NUM_LIT:0> ) { Parcelable parcel = presenterStates . get ( id ) ; if ( parcel != null ) { presenter . onRestoreInstanceState ( parcel ) ; } } } } } public void savePresenterStates ( Bundle outState ) { dispatchSaveInstanceState ( outState ) ; } public void restorePresenterStates ( Bundle state ) { dispatchRestoreInstanceState ( state ) ; } public void saveActionViewStates ( Bundle outStates ) { SparseArray < Parcelable > viewStates = null ; final int itemCount = size ( ) ; for ( int i = <NUM_LIT:0> ; i < itemCount ; i ++ ) { final MenuItem item = getItem ( i ) ; final View v = item . getActionView ( ) ; if ( v != null && v . getId ( ) != View . NO_ID ) { if ( viewStates == null ) { viewStates = new SparseArray < Parcelable > ( ) ; } v . saveHierarchyState ( viewStates ) ; if ( item . isActionViewExpanded ( ) ) { outStates . putInt ( EXPANDED_ACTION_VIEW_ID , item . getItemId ( ) ) ; } } if ( item . hasSubMenu ( ) ) { final SubMenuBuilder subMenu = ( SubMenuBuilder ) item . getSubMenu ( ) ; subMenu . saveActionViewStates ( outStates ) ; } } if ( viewStates != null ) { outStates . putSparseParcelableArray ( getActionViewStatesKey ( ) , viewStates ) ; } } public void restoreActionViewStates ( Bundle states ) { if ( states == null ) { return ; } SparseArray < Parcelable > viewStates = states . getSparseParcelableArray ( getActionViewStatesKey ( ) ) ; final int itemCount = size ( ) ; for ( int i = <NUM_LIT:0> ; i < itemCount ; i ++ ) { final MenuItem item = getItem ( i ) ; final View v = item . getActionView ( ) ; if ( v != null && v . getId ( ) != View . NO_ID ) { v . restoreHierarchyState ( viewStates ) ; } if ( item . hasSubMenu ( ) ) { final SubMenuBuilder subMenu = ( SubMenuBuilder ) item . getSubMenu ( ) ; subMenu . restoreActionViewStates ( states ) ; } } final int expandedId = states . getInt ( EXPANDED_ACTION_VIEW_ID ) ; if ( expandedId > <NUM_LIT:0> ) { MenuItem itemToExpand = findItem ( expandedId ) ; if ( itemToExpand != null ) { itemToExpand . expandActionView ( ) ; } } } protected String getActionViewStatesKey ( ) { return ACTION_VIEW_STATES_KEY ; } public void setCallback ( Callback cb ) { mCallback = cb ; } private MenuItem addInternal ( int group , int id , int categoryOrder , CharSequence title ) { final int ordering = getOrdering ( categoryOrder ) ; final MenuItemImpl item = new MenuItemImpl ( this , group , id , categoryOrder , ordering , title , mDefaultShowAsAction ) ; if ( mCurrentMenuInfo != null ) { item . setMenuInfo ( mCurrentMenuInfo ) ; } mItems . add ( findInsertIndex ( mItems , ordering ) , item ) ; onItemsChanged ( true ) ; return item ; } public MenuItem add ( CharSequence title ) { return addInternal ( <NUM_LIT:0> , <NUM_LIT:0> , <NUM_LIT:0> , title ) ; } public MenuItem add ( int titleRes ) { return addInternal ( <NUM_LIT:0> , <NUM_LIT:0> , <NUM_LIT:0> , mResources . getString ( titleRes ) ) ; } public MenuItem add ( int group , int id , int categoryOrder , CharSequence title ) { return addInternal ( group , id , categoryOrder , title ) ; } public MenuItem add ( int group , int id , int categoryOrder , int title ) { return addInternal ( group , id , categoryOrder , mResources . getString ( title ) ) ; } public SubMenu addSubMenu ( CharSequence title ) { return addSubMenu ( <NUM_LIT:0> , <NUM_LIT:0> , <NUM_LIT:0> , title ) ; } public SubMenu addSubMenu ( int titleRes ) { return addSubMenu ( <NUM_LIT:0> , <NUM_LIT:0> , <NUM_LIT:0> , mResources . getString ( titleRes ) ) ; } public SubMenu addSubMenu ( int group , int id , int categoryOrder , CharSequence title ) { final MenuItemImpl item = ( MenuItemImpl ) addInternal ( group , id , categoryOrder , title ) ; final SubMenuBuilder subMenu = new SubMenuBuilder ( mContext , this , item ) ; item . setSubMenu ( subMenu ) ; return subMenu ; } public SubMenu addSubMenu ( int group , int id , int categoryOrder , int title ) { return addSubMenu ( group , id , categoryOrder , mResources . getString ( title ) ) ; } public int addIntentOptions ( int group , int id , int categoryOrder , ComponentName caller , Intent [ ] specifics , Intent intent , int flags , MenuItem [ ] outSpecificItems ) { PackageManager pm = mContext . getPackageManager ( ) ; final List < ResolveInfo > lri = pm . queryIntentActivityOptions ( caller , specifics , intent , <NUM_LIT:0> ) ; final int N = lri != null ? lri . size ( ) : <NUM_LIT:0> ; if ( ( flags & FLAG_APPEND_TO_GROUP ) == <NUM_LIT:0> ) { removeGroup ( group ) ; } for ( int i = <NUM_LIT:0> ; i < N ; i ++ ) { final ResolveInfo ri = lri . get ( i ) ; Intent rintent = new Intent ( ri . specificIndex < <NUM_LIT:0> ? intent : specifics [ ri . specificIndex ] ) ; rintent . setComponent ( new ComponentName ( ri . activityInfo . applicationInfo . packageName , ri . activityInfo . name ) ) ; final MenuItem item = add ( group , id , categoryOrder , ri . loadLabel ( pm ) ) . setIcon ( ri . loadIcon ( pm ) ) . setIntent ( rintent ) ; if ( outSpecificItems != null && ri . specificIndex >= <NUM_LIT:0> ) { outSpecificItems [ ri . specificIndex ] = item ; } } return N ; } public void removeItem ( int id ) { removeItemAtInt ( findItemIndex ( id ) , true ) ; } public void removeGroup ( int group ) { final int i = findGroupIndex ( group ) ; if ( i >= <NUM_LIT:0> ) { final int maxRemovable = mItems . size ( ) - i ; int numRemoved = <NUM_LIT:0> ; while ( ( numRemoved ++ < maxRemovable ) && ( mItems . get ( i ) . getGroupId ( ) == group ) ) { removeItemAtInt ( i , false ) ; } onItemsChanged ( true ) ; } } private void removeItemAtInt ( int index , boolean updateChildrenOnMenuViews ) { if ( ( index < <NUM_LIT:0> ) || ( index >= mItems . size ( ) ) ) return ; mItems . remove ( index ) ; if ( updateChildrenOnMenuViews ) onItemsChanged ( true ) ; } public void removeItemAt ( int index ) { removeItemAtInt ( index , true ) ; } public void clearAll ( ) { mPreventDispatchingItemsChanged = true ; clear ( ) ; clearHeader ( ) ; mPreventDispatchingItemsChanged = false ; mItemsChangedWhileDispatchPrevented = false ; onItemsChanged ( true ) ; } public void clear ( ) { if ( mExpandedItem != null ) { collapseItemActionView ( mExpandedItem ) ; } mItems . clear ( ) ; onItemsChanged ( true ) ; } void setExclusiveItemChecked ( MenuItem item ) { final int group = item . getGroupId ( ) ; final int N = mItems . size ( ) ; for ( int i = <NUM_LIT:0> ; i < N ; i ++ ) { MenuItemImpl curItem = mItems . get ( i ) ; if ( curItem . getGroupId ( ) == group ) { if ( ! curItem . isExclusiveCheckable ( ) ) continue ; if ( ! curItem . isCheckable ( ) ) continue ; curItem . setCheckedInt ( curItem == item ) ; } } } public void setGroupCheckable ( int group , boolean checkable , boolean exclusive ) { final int N = mItems . size ( ) ; for ( int i = <NUM_LIT:0> ; i < N ; i ++ ) { MenuItemImpl item = mItems . get ( i ) ; if ( item . getGroupId ( ) == group ) { item . setExclusiveCheckable ( exclusive ) ; item . setCheckable ( checkable ) ; } } } public void setGroupVisible ( int group , boolean visible ) { final int N = mItems . size ( ) ; boolean changedAtLeastOneItem = false ; for ( int i = <NUM_LIT:0> ; i < N ; i ++ ) { MenuItemImpl item = mItems . get ( i ) ; if ( item . getGroupId ( ) == group ) { if ( item . setVisibleInt ( visible ) ) changedAtLeastOneItem = true ; } } if ( changedAtLeastOneItem ) onItemsChanged ( true ) ; } public void setGroupEnabled ( int group , boolean enabled ) { final int N = mItems . size ( ) ; for ( int i = <NUM_LIT:0> ; i < N ; i ++ ) { MenuItemImpl item = mItems . get ( i ) ; if ( item . getGroupId ( ) == group ) { item . setEnabled ( enabled ) ; } } } public boolean hasVisibleItems ( ) { final int size = size ( ) ; for ( int i = <NUM_LIT:0> ; i < size ; i ++ ) { MenuItemImpl item = mItems . get ( i ) ; if ( item . isVisible ( ) ) { return true ; } } return false ; } public MenuItem findItem ( int id ) { final int size = size ( ) ; for ( int i = <NUM_LIT:0> ; i < size ; i ++ ) { MenuItemImpl item = mItems . get ( i ) ; if ( item . getItemId ( ) == id ) { return item ; } else if ( item . hasSubMenu ( ) ) { MenuItem possibleItem = item . getSubMenu ( ) . findItem ( id ) ; if ( possibleItem != null ) { return possibleItem ; } } } return null ; } public int findItemIndex ( int id ) { final int size = size ( ) ; for ( int i = <NUM_LIT:0> ; i < size ; i ++ ) { MenuItemImpl item = mItems . get ( i ) ; if ( item . getItemId ( ) == id ) { return i ; } } return - <NUM_LIT:1> ; } public int findGroupIndex ( int group ) { return findGroupIndex ( group , <NUM_LIT:0> ) ; } public int findGroupIndex ( int group , int start ) { final int size = size ( ) ; if ( start < <NUM_LIT:0> ) { start = <NUM_LIT:0> ; } for ( int i = start ; i < size ; i ++ ) { final MenuItemImpl item = mItems . get ( i ) ; if ( item . getGroupId ( ) == group ) { return i ; } } return - <NUM_LIT:1> ; } public int size ( ) { return mItems . size ( ) ; } public MenuItem getItem ( int index ) { return mItems . get ( index ) ; } public boolean isShortcutKey ( int keyCode , KeyEvent event ) { return findItemWithShortcutForKey ( keyCode , event ) != null ; } public void setQwertyMode ( boolean isQwerty ) { mQwertyMode = isQwerty ; onItemsChanged ( false ) ; } private static int getOrdering ( int categoryOrder ) { final int index = ( categoryOrder & CATEGORY_MASK ) > > CATEGORY_SHIFT ; if ( index < <NUM_LIT:0> || index >= sCategoryToOrder . length ) { throw new IllegalArgumentException ( "<STR_LIT>" ) ; } return ( sCategoryToOrder [ index ] << CATEGORY_SHIFT ) | ( categoryOrder & USER_MASK ) ; } boolean isQwertyMode ( ) { return mQwertyMode ; } public void setShortcutsVisible ( boolean shortcutsVisible ) { if ( mShortcutsVisible == shortcutsVisible ) return ; setShortcutsVisibleInner ( shortcutsVisible ) ; onItemsChanged ( false ) ; } private void setShortcutsVisibleInner ( boolean shortcutsVisible ) { mShortcutsVisible = shortcutsVisible && mResources . getConfiguration ( ) . keyboard != Configuration . KEYBOARD_NOKEYS && mResources . getBoolean ( R . bool . abs__config_showMenuShortcutsWhenKeyboardPresent ) ; } public boolean isShortcutsVisible ( ) { return mShortcutsVisible ; } Resources getResources ( ) { return mResources ; } public Context getContext ( ) { return mContext ; } boolean dispatchMenuItemSelected ( MenuBuilder menu , MenuItem item ) { return mCallback != null && mCallback . onMenuItemSelected ( menu , item ) ; } public void changeMenuMode ( ) { if ( mCallback != null ) { mCallback . onMenuModeChange ( this ) ; } } private static int findInsertIndex ( ArrayList < MenuItemImpl > items , int ordering ) { for ( int i = items . size ( ) - <NUM_LIT:1> ; i >= <NUM_LIT:0> ; i -- ) { MenuItemImpl item = items . get ( i ) ; if ( item . getOrdering ( ) <= ordering ) { return i + <NUM_LIT:1> ; } } return <NUM_LIT:0> ; } public boolean performShortcut ( int keyCode , KeyEvent event , int flags ) { final MenuItemImpl item = findItemWithShortcutForKey ( keyCode , event ) ; boolean handled = false ; if ( item != null ) { handled = performItemAction ( item , flags ) ; } if ( ( flags & FLAG_ALWAYS_PERFORM_CLOSE ) != <NUM_LIT:0> ) { close ( true ) ; } return handled ; } @ SuppressWarnings ( "<STR_LIT:deprecation>" ) void findItemsWithShortcutForKey ( List < MenuItemImpl > items , int keyCode , KeyEvent event ) { final boolean qwerty = isQwertyMode ( ) ; final int metaState = event . getMetaState ( ) ; final KeyCharacterMap . KeyData possibleChars = new KeyCharacterMap . KeyData ( ) ; final boolean isKeyCodeMapped = event . getKeyData ( possibleChars ) ; if ( ! isKeyCodeMapped && ( keyCode != KeyEvent . KEYCODE_DEL ) ) { return ; } final int N = mItems . size ( ) ; for ( int i = <NUM_LIT:0> ; i < N ; i ++ ) { MenuItemImpl item = mItems . get ( i ) ; if ( item . hasSubMenu ( ) ) { ( ( MenuBuilder ) item . getSubMenu ( ) ) . findItemsWithShortcutForKey ( items , keyCode , event ) ; } final char shortcutChar = qwerty ? item . getAlphabeticShortcut ( ) : item . getNumericShortcut ( ) ; if ( ( ( metaState & ( KeyEvent . META_SHIFT_ON | KeyEvent . META_SYM_ON ) ) == <NUM_LIT:0> ) && ( shortcutChar != <NUM_LIT:0> ) && ( shortcutChar == possibleChars . meta [ <NUM_LIT:0> ] || shortcutChar == possibleChars . meta [ <NUM_LIT:2> ] || ( qwerty && shortcutChar == '<STR_LIT>' && keyCode == KeyEvent . KEYCODE_DEL ) ) && item . isEnabled ( ) ) { items . add ( item ) ; } } } @ SuppressWarnings ( "<STR_LIT:deprecation>" ) MenuItemImpl findItemWithShortcutForKey ( int keyCode , KeyEvent event ) { ArrayList < MenuItemImpl > items = mTempShortcutItemList ; items . clear ( ) ; findItemsWithShortcutForKey ( items , keyCode , event ) ; if ( items . isEmpty ( ) ) { return null ; } final int metaState = event . getMetaState ( ) ; final KeyCharacterMap . KeyData possibleChars = new KeyCharacterMap . KeyData ( ) ; event . getKeyData ( possibleChars ) ; final int size = items . size ( ) ; if ( size == <NUM_LIT:1> ) { return items . get ( <NUM_LIT:0> ) ; } final boolean qwerty = isQwertyMode ( ) ; for ( int i = <NUM_LIT:0> ; i < size ; i ++ ) { final MenuItemImpl item = items . get ( i ) ; final char shortcutChar = qwerty ? item . getAlphabeticShortcut ( ) : item . getNumericShortcut ( ) ; if ( ( shortcutChar == possibleChars . meta [ <NUM_LIT:0> ] && ( metaState & KeyEvent . META_ALT_ON ) == <NUM_LIT:0> ) || ( shortcutChar == possibleChars . meta [ <NUM_LIT:2> ] && ( metaState & KeyEvent . META_ALT_ON ) != <NUM_LIT:0> ) || ( qwerty && shortcutChar == '<STR_LIT>' && keyCode == KeyEvent . KEYCODE_DEL ) ) { return item ; } } return null ; } public boolean performIdentifierAction ( int id , int flags ) { return performItemAction ( findItem ( id ) , flags ) ; } public boolean performItemAction ( MenuItem item , int flags ) { MenuItemImpl itemImpl = ( MenuItemImpl ) item ; if ( itemImpl == null || ! itemImpl . isEnabled ( ) ) { return false ; } boolean invoked = itemImpl . invoke ( ) ; if ( itemImpl . hasCollapsibleActionView ( ) ) { invoked |= itemImpl . expandActionView ( ) ; if ( invoked ) close ( true ) ; } else if ( item . hasSubMenu ( ) ) { close ( false ) ; final SubMenuBuilder subMenu = ( SubMenuBuilder ) item . getSubMenu ( ) ; final ActionProvider provider = item . getActionProvider ( ) ; if ( provider != null && provider . hasSubMenu ( ) ) { provider . onPrepareSubMenu ( subMenu ) ; } invoked |= dispatchSubMenuSelected ( subMenu ) ; if ( ! invoked ) close ( true ) ; } else { if ( ( flags & FLAG_PERFORM_NO_CLOSE ) == <NUM_LIT:0> ) { close ( true ) ; } } return invoked ; } final void close ( boolean allMenusAreClosing ) { if ( mIsClosing ) return ; mIsClosing = true ; for ( WeakReference < MenuPresenter > ref : mPresenters ) { final MenuPresenter presenter = ref . get ( ) ; if ( presenter == null ) { mPresenters . remove ( ref ) ; } else { presenter . onCloseMenu ( this , allMenusAreClosing ) ; } } mIsClosing = false ; } public void close ( ) { close ( true ) ; } void onItemsChanged ( boolean structureChanged ) { if ( ! mPreventDispatchingItemsChanged ) { if ( structureChanged ) { mIsVisibleItemsStale = true ; mIsActionItemsStale = true ; } dispatchPresenterUpdate ( structureChanged ) ; } else { mItemsChangedWhileDispatchPrevented = true ; } } public void stopDispatchingItemsChanged ( ) { if ( ! mPreventDispatchingItemsChanged ) { mPreventDispatchingItemsChanged = true ; mItemsChangedWhileDispatchPrevented = false ; } } public void startDispatchingItemsChanged ( ) { mPreventDispatchingItemsChanged = false ; if ( mItemsChangedWhileDispatchPrevented ) { mItemsChangedWhileDispatchPrevented = false ; onItemsChanged ( true ) ; } } void onItemVisibleChanged ( MenuItemImpl item ) { mIsVisibleItemsStale = true ; onItemsChanged ( true ) ; } void onItemActionRequestChanged ( MenuItemImpl item ) { mIsActionItemsStale = true ; onItemsChanged ( true ) ; } ArrayList < MenuItemImpl > getVisibleItems ( ) { if ( ! mIsVisibleItemsStale ) return mVisibleItems ; mVisibleItems . clear ( ) ; final int itemsSize = mItems . size ( ) ; MenuItemImpl item ; for ( int i = <NUM_LIT:0> ; i < itemsSize ; i ++ ) { item = mItems . get ( i ) ; if ( item . isVisible ( ) ) mVisibleItems . add ( item ) ; } mIsVisibleItemsStale = false ; mIsActionItemsStale = true ; return mVisibleItems ; } public void flagActionItems ( ) { if ( ! mIsActionItemsStale ) { return ; } boolean flagged = false ; for ( WeakReference < MenuPresenter > ref : mPresenters ) { final MenuPresenter presenter = ref . get ( ) ; if ( presenter == null ) { mPresenters . remove ( ref ) ; } else { flagged |= presenter . flagActionItems ( ) ; } } if ( flagged ) { mActionItems . clear ( ) ; mNonActionItems . clear ( ) ; ArrayList < MenuItemImpl > visibleItems = getVisibleItems ( ) ; final int itemsSize = visibleItems . size ( ) ; for ( int i = <NUM_LIT:0> ; i < itemsSize ; i ++ ) { MenuItemImpl item = visibleItems . get ( i ) ; if ( item . isActionButton ( ) ) { mActionItems . add ( item ) ; } else { mNonActionItems . add ( item ) ; } } } else { mActionItems . clear ( ) ; mNonActionItems . clear ( ) ; mNonActionItems . addAll ( getVisibleItems ( ) ) ; } mIsActionItemsStale = false ; } ArrayList < MenuItemImpl > getActionItems ( ) { flagActionItems ( ) ; return mActionItems ; } ArrayList < MenuItemImpl > getNonActionItems ( ) { flagActionItems ( ) ; return mNonActionItems ; } public void clearHeader ( ) { mHeaderIcon = null ; mHeaderTitle = null ; mHeaderView = null ; onItemsChanged ( false ) ; } private void setHeaderInternal ( final int titleRes , final CharSequence title , final int iconRes , final Drawable icon , final View view ) { final Resources r = getResources ( ) ; if ( view != null ) { mHeaderView = view ; mHeaderTitle = null ; mHeaderIcon = null ; } else { if ( titleRes > <NUM_LIT:0> ) { mHeaderTitle = r . getText ( titleRes ) ; } else if ( title != null ) { mHeaderTitle = title ; } if ( iconRes > <NUM_LIT:0> ) { mHeaderIcon = r . getDrawable ( iconRes ) ; } else if ( icon != null ) { mHeaderIcon = icon ; } mHeaderView = null ; } onItemsChanged ( false ) ; } protected MenuBuilder setHeaderTitleInt ( CharSequence title ) { setHeaderInternal ( <NUM_LIT:0> , title , <NUM_LIT:0> , null , null ) ; return this ; } protected MenuBuilder setHeaderTitleInt ( int titleRes ) { setHeaderInternal ( titleRes , null , <NUM_LIT:0> , null , null ) ; return this ; } protected MenuBuilder setHeaderIconInt ( Drawable icon ) { setHeaderInternal ( <NUM_LIT:0> , null , <NUM_LIT:0> , icon , null ) ; return this ; } protected MenuBuilder setHeaderIconInt ( int iconRes ) { setHeaderInternal ( <NUM_LIT:0> , null , iconRes , null , null ) ; return this ; } protected MenuBuilder setHeaderViewInt ( View view ) { setHeaderInternal ( <NUM_LIT:0> , null , <NUM_LIT:0> , null , view ) ; return this ; } public CharSequence getHeaderTitle ( ) { return mHeaderTitle ; } public Drawable getHeaderIcon ( ) { return mHeaderIcon ; } public View getHeaderView ( ) { return mHeaderView ; } public MenuBuilder getRootMenu ( ) { return this ; } public void setCurrentMenuInfo ( ContextMenuInfo menuInfo ) { mCurrentMenuInfo = menuInfo ; } void setOptionalIconsVisible ( boolean visible ) { mOptionalIconsVisible = visible ; } boolean getOptionalIconsVisible ( ) { return mOptionalIconsVisible ; } public boolean expandItemActionView ( MenuItemImpl item ) { if ( mPresenters . isEmpty ( ) ) return false ; boolean expanded = false ; stopDispatchingItemsChanged ( ) ; for ( WeakReference < MenuPresenter > ref : mPresenters ) { final MenuPresenter presenter = ref . get ( ) ; if ( presenter == null ) { mPresenters . remove ( ref ) ; } else if ( ( expanded = presenter . expandItemActionView ( this , item ) ) ) { break ; } } startDispatchingItemsChanged ( ) ; if ( expanded ) { mExpandedItem = item ; } return expanded ; } public boolean collapseItemActionView ( MenuItemImpl item ) { if ( mPresenters . isEmpty ( ) || mExpandedItem != item ) return false ; boolean collapsed = false ; stopDispatchingItemsChanged ( ) ; for ( WeakReference < MenuPresenter > ref : mPresenters ) { final MenuPresenter presenter = ref . get ( ) ; if ( presenter == null ) { mPresenters . remove ( ref ) ; } else if ( ( collapsed = presenter . collapseItemActionView ( this , item ) ) ) { break ; } } startDispatchingItemsChanged ( ) ; if ( collapsed ) { mExpandedItem = null ; } return collapsed ; } public MenuItemImpl getExpandedItem ( ) { return mExpandedItem ; } public boolean bindNativeOverflow ( android . view . Menu menu , android . view . MenuItem . OnMenuItemClickListener listener , HashMap < android . view . MenuItem , MenuItemImpl > map ) { final List < MenuItemImpl > nonActionItems = getNonActionItems ( ) ; if ( nonActionItems == null || nonActionItems . size ( ) == <NUM_LIT:0> ) { return false ; } boolean visible = false ; menu . clear ( ) ; for ( MenuItemImpl nonActionItem : nonActionItems ) { if ( ! nonActionItem . isVisible ( ) ) { continue ; } visible = true ; android . view . MenuItem nativeItem ; if ( nonActionItem . hasSubMenu ( ) ) { android . view . SubMenu nativeSub = menu . addSubMenu ( nonActionItem . getGroupId ( ) , nonActionItem . getItemId ( ) , nonActionItem . getOrder ( ) , nonActionItem . getTitle ( ) ) ; SubMenuBuilder subMenu = ( SubMenuBuilder ) nonActionItem . getSubMenu ( ) ; for ( MenuItemImpl subItem : subMenu . getVisibleItems ( ) ) { android . view . MenuItem nativeSubItem = nativeSub . add ( subItem . getGroupId ( ) , subItem . getItemId ( ) , subItem . getOrder ( ) , subItem . getTitle ( ) ) ; nativeSubItem . setIcon ( subItem . getIcon ( ) ) ; nativeSubItem . setOnMenuItemClickListener ( listener ) ; nativeSubItem . setEnabled ( subItem . isEnabled ( ) ) ; nativeSubItem . setIntent ( subItem . getIntent ( ) ) ; nativeSubItem . setNumericShortcut ( subItem . getNumericShortcut ( ) ) ; nativeSubItem . setAlphabeticShortcut ( subItem . getAlphabeticShortcut ( ) ) ; nativeSubItem . setTitleCondensed ( subItem . getTitleCondensed ( ) ) ; nativeSubItem . setCheckable ( subItem . isCheckable ( ) ) ; nativeSubItem . setChecked ( subItem . isChecked ( ) ) ; if ( subItem . isExclusiveCheckable ( ) ) { nativeSub . setGroupCheckable ( subItem . getGroupId ( ) , true , true ) ; } map . put ( nativeSubItem , subItem ) ; } nativeItem = nativeSub . getItem ( ) ; } else { nativeItem = menu . add ( nonActionItem . getGroupId ( ) , nonActionItem . getItemId ( ) , nonActionItem . getOrder ( ) , nonActionItem . getTitle ( ) ) ; } nativeItem . setIcon ( nonActionItem . getIcon ( ) ) ; nativeItem . setOnMenuItemClickListener ( listener ) ; nativeItem . setEnabled ( nonActionItem . isEnabled ( ) ) ; nativeItem . setIntent ( nonActionItem . getIntent ( ) ) ; nativeItem . setNumericShortcut ( nonActionItem . getNumericShortcut ( ) ) ; nativeItem . setAlphabeticShortcut ( nonActionItem . getAlphabeticShortcut ( ) ) ; nativeItem . setTitleCondensed ( nonActionItem . getTitleCondensed ( ) ) ; nativeItem . setCheckable ( nonActionItem . isCheckable ( ) ) ; nativeItem . setChecked ( nonActionItem . isChecked ( ) ) ; if ( nonActionItem . isExclusiveCheckable ( ) ) { menu . setGroupCheckable ( nonActionItem . getGroupId ( ) , true , true ) ; } map . put ( nativeItem , nonActionItem ) ; } return visible ; } } </s>
|
<s> 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 ; } } </s>
|
<s> package com . actionbarsherlock . internal . view . menu ; import java . util . ArrayList ; import android . content . Context ; import android . content . res . Resources ; import android . database . DataSetObserver ; import android . os . Parcelable ; import android . view . KeyEvent ; import android . view . LayoutInflater ; import android . view . View ; import android . view . View . MeasureSpec ; import android . view . ViewGroup ; import android . view . ViewTreeObserver ; import android . widget . AdapterView ; import android . widget . BaseAdapter ; import android . widget . FrameLayout ; import android . widget . ListAdapter ; import android . widget . PopupWindow ; import com . actionbarsherlock . R ; import com . actionbarsherlock . internal . view . View_HasStateListenerSupport ; import com . actionbarsherlock . internal . view . View_OnAttachStateChangeListener ; import com . actionbarsherlock . internal . widget . IcsListPopupWindow ; import com . actionbarsherlock . view . MenuItem ; public class MenuPopupHelper implements AdapterView . OnItemClickListener , View . OnKeyListener , ViewTreeObserver . OnGlobalLayoutListener , PopupWindow . OnDismissListener , View_OnAttachStateChangeListener , MenuPresenter { static final int ITEM_LAYOUT = R . layout . abs__popup_menu_item_layout ; private Context mContext ; private LayoutInflater mInflater ; private IcsListPopupWindow mPopup ; private MenuBuilder mMenu ; private int mPopupMaxWidth ; private View mAnchorView ; private boolean mOverflowOnly ; private ViewTreeObserver mTreeObserver ; private MenuAdapter mAdapter ; private Callback mPresenterCallback ; boolean mForceShowIcon ; private ViewGroup mMeasureParent ; public MenuPopupHelper ( Context context , MenuBuilder menu ) { this ( context , menu , null , false ) ; } public MenuPopupHelper ( Context context , MenuBuilder menu , View anchorView ) { this ( context , menu , anchorView , false ) ; } public MenuPopupHelper ( Context context , MenuBuilder menu , View anchorView , boolean overflowOnly ) { mContext = context ; mInflater = LayoutInflater . from ( context ) ; mMenu = menu ; mOverflowOnly = overflowOnly ; final Resources res = context . getResources ( ) ; mPopupMaxWidth = Math . max ( res . getDisplayMetrics ( ) . widthPixels / <NUM_LIT:2> , res . getDimensionPixelSize ( R . dimen . abs__config_prefDialogWidth ) ) ; mAnchorView = anchorView ; menu . addMenuPresenter ( this ) ; } public void setAnchorView ( View anchor ) { mAnchorView = anchor ; } public void setForceShowIcon ( boolean forceShow ) { mForceShowIcon = forceShow ; } public void show ( ) { if ( ! tryShow ( ) ) { throw new IllegalStateException ( "<STR_LIT>" ) ; } } public boolean tryShow ( ) { mPopup = new IcsListPopupWindow ( mContext , null , R . attr . popupMenuStyle ) ; mPopup . setOnDismissListener ( this ) ; mPopup . setOnItemClickListener ( this ) ; mAdapter = new MenuAdapter ( mMenu ) ; mPopup . setAdapter ( mAdapter ) ; mPopup . setModal ( true ) ; View anchor = mAnchorView ; if ( anchor != null ) { final boolean addGlobalListener = mTreeObserver == null ; mTreeObserver = anchor . getViewTreeObserver ( ) ; if ( addGlobalListener ) mTreeObserver . addOnGlobalLayoutListener ( this ) ; ( ( View_HasStateListenerSupport ) anchor ) . addOnAttachStateChangeListener ( this ) ; mPopup . setAnchorView ( anchor ) ; } else { return false ; } mPopup . setContentWidth ( Math . min ( measureContentWidth ( mAdapter ) , mPopupMaxWidth ) ) ; mPopup . setInputMethodMode ( PopupWindow . INPUT_METHOD_NOT_NEEDED ) ; mPopup . show ( ) ; mPopup . getListView ( ) . setOnKeyListener ( this ) ; return true ; } public void dismiss ( ) { if ( isShowing ( ) ) { mPopup . dismiss ( ) ; } } public void onDismiss ( ) { mPopup = null ; mMenu . close ( ) ; if ( mTreeObserver != null ) { if ( ! mTreeObserver . isAlive ( ) ) mTreeObserver = mAnchorView . getViewTreeObserver ( ) ; mTreeObserver . removeGlobalOnLayoutListener ( this ) ; mTreeObserver = null ; } ( ( View_HasStateListenerSupport ) mAnchorView ) . removeOnAttachStateChangeListener ( this ) ; } public boolean isShowing ( ) { return mPopup != null && mPopup . isShowing ( ) ; } @ Override public void onItemClick ( AdapterView < ? > parent , View view , int position , long id ) { MenuAdapter adapter = mAdapter ; adapter . mAdapterMenu . performItemAction ( adapter . getItem ( position ) , <NUM_LIT:0> ) ; } public boolean onKey ( View v , int keyCode , KeyEvent event ) { if ( event . getAction ( ) == KeyEvent . ACTION_UP && keyCode == KeyEvent . KEYCODE_MENU ) { dismiss ( ) ; return true ; } return false ; } private int measureContentWidth ( ListAdapter adapter ) { int width = <NUM_LIT:0> ; View itemView = null ; int itemType = <NUM_LIT:0> ; final int widthMeasureSpec = MeasureSpec . makeMeasureSpec ( <NUM_LIT:0> , MeasureSpec . UNSPECIFIED ) ; final int heightMeasureSpec = MeasureSpec . makeMeasureSpec ( <NUM_LIT:0> , MeasureSpec . UNSPECIFIED ) ; final int count = adapter . getCount ( ) ; for ( int i = <NUM_LIT:0> ; i < count ; i ++ ) { final int positionType = adapter . getItemViewType ( i ) ; if ( positionType != itemType ) { itemType = positionType ; itemView = null ; } if ( mMeasureParent == null ) { mMeasureParent = new FrameLayout ( mContext ) ; } itemView = adapter . getView ( i , itemView , mMeasureParent ) ; itemView . measure ( widthMeasureSpec , heightMeasureSpec ) ; width = Math . max ( width , itemView . getMeasuredWidth ( ) ) ; } return width ; } @ Override public void onGlobalLayout ( ) { if ( isShowing ( ) ) { final View anchor = mAnchorView ; if ( anchor == null || ! anchor . isShown ( ) ) { dismiss ( ) ; } else if ( isShowing ( ) ) { mPopup . show ( ) ; } } } @ Override public void onViewAttachedToWindow ( View v ) { } @ Override public void onViewDetachedFromWindow ( View v ) { if ( mTreeObserver != null ) { if ( ! mTreeObserver . isAlive ( ) ) mTreeObserver = v . getViewTreeObserver ( ) ; mTreeObserver . removeGlobalOnLayoutListener ( this ) ; } ( ( View_HasStateListenerSupport ) v ) . removeOnAttachStateChangeListener ( this ) ; } @ Override public void initForMenu ( Context context , MenuBuilder menu ) { } @ Override public MenuView getMenuView ( ViewGroup root ) { throw new UnsupportedOperationException ( "<STR_LIT>" ) ; } @ Override public void updateMenuView ( boolean cleared ) { if ( mAdapter != null ) mAdapter . notifyDataSetChanged ( ) ; } @ Override public void setCallback ( Callback cb ) { mPresenterCallback = cb ; } @ Override public boolean onSubMenuSelected ( SubMenuBuilder subMenu ) { if ( subMenu . hasVisibleItems ( ) ) { MenuPopupHelper subPopup = new MenuPopupHelper ( mContext , subMenu , mAnchorView , false ) ; subPopup . setCallback ( mPresenterCallback ) ; boolean preserveIconSpacing = false ; final int count = subMenu . size ( ) ; for ( int i = <NUM_LIT:0> ; i < count ; i ++ ) { MenuItem childItem = subMenu . getItem ( i ) ; if ( childItem . isVisible ( ) && childItem . getIcon ( ) != null ) { preserveIconSpacing = true ; break ; } } subPopup . setForceShowIcon ( preserveIconSpacing ) ; if ( subPopup . tryShow ( ) ) { if ( mPresenterCallback != null ) { mPresenterCallback . onOpenSubMenu ( subMenu ) ; } return true ; } } return false ; } @ Override public void onCloseMenu ( MenuBuilder menu , boolean allMenusAreClosing ) { if ( menu != mMenu ) return ; dismiss ( ) ; if ( mPresenterCallback != null ) { mPresenterCallback . onCloseMenu ( menu , allMenusAreClosing ) ; } } @ Override public boolean flagActionItems ( ) { return false ; } public boolean expandItemActionView ( MenuBuilder menu , MenuItemImpl item ) { return false ; } public boolean collapseItemActionView ( MenuBuilder menu , MenuItemImpl item ) { return false ; } @ Override public int getId ( ) { return <NUM_LIT:0> ; } @ Override public Parcelable onSaveInstanceState ( ) { return null ; } @ Override public void onRestoreInstanceState ( Parcelable state ) { } private class MenuAdapter extends BaseAdapter { private MenuBuilder mAdapterMenu ; private int mExpandedIndex = - <NUM_LIT:1> ; public MenuAdapter ( MenuBuilder menu ) { mAdapterMenu = menu ; registerDataSetObserver ( new ExpandedIndexObserver ( ) ) ; findExpandedIndex ( ) ; } public int getCount ( ) { ArrayList < MenuItemImpl > items = mOverflowOnly ? mAdapterMenu . getNonActionItems ( ) : mAdapterMenu . getVisibleItems ( ) ; if ( mExpandedIndex < <NUM_LIT:0> ) { return items . size ( ) ; } return items . size ( ) - <NUM_LIT:1> ; } public MenuItemImpl getItem ( int position ) { ArrayList < MenuItemImpl > items = mOverflowOnly ? mAdapterMenu . getNonActionItems ( ) : mAdapterMenu . getVisibleItems ( ) ; if ( mExpandedIndex >= <NUM_LIT:0> && position >= mExpandedIndex ) { position ++ ; } return items . get ( position ) ; } public long getItemId ( int position ) { return position ; } public View getView ( int position , View convertView , ViewGroup parent ) { if ( convertView == null ) { convertView = mInflater . inflate ( ITEM_LAYOUT , parent , false ) ; } MenuView . ItemView itemView = ( MenuView . ItemView ) convertView ; if ( mForceShowIcon ) { ( ( ListMenuItemView ) convertView ) . setForceShowIcon ( true ) ; } itemView . initialize ( getItem ( position ) , <NUM_LIT:0> ) ; return convertView ; } void findExpandedIndex ( ) { final MenuItemImpl expandedItem = mMenu . getExpandedItem ( ) ; if ( expandedItem != null ) { final ArrayList < MenuItemImpl > items = mMenu . getNonActionItems ( ) ; final int count = items . size ( ) ; for ( int i = <NUM_LIT:0> ; i < count ; i ++ ) { final MenuItemImpl item = items . get ( i ) ; if ( item == expandedItem ) { mExpandedIndex = i ; return ; } } } mExpandedIndex = - <NUM_LIT:1> ; } } private class ExpandedIndexObserver extends DataSetObserver { @ Override public void onChanged ( ) { mAdapter . findExpandedIndex ( ) ; } } } </s>
|
<s> package com . actionbarsherlock . internal . view . menu ; import java . util . HashSet ; import java . util . Set ; import android . content . Context ; import android . content . res . TypedArray ; import android . graphics . Rect ; import android . graphics . drawable . Drawable ; import android . os . Build ; import android . text . TextUtils ; import android . util . AttributeSet ; import android . view . Gravity ; import android . view . MotionEvent ; import android . view . View ; import android . view . accessibility . AccessibilityEvent ; import android . widget . ImageButton ; import android . widget . LinearLayout ; import android . widget . Toast ; import com . actionbarsherlock . R ; import com . actionbarsherlock . internal . view . View_HasStateListenerSupport ; import com . actionbarsherlock . internal . view . View_OnAttachStateChangeListener ; import com . actionbarsherlock . internal . widget . CapitalizingButton ; import static com . actionbarsherlock . internal . ResourcesCompat . getResources_getBoolean ; public class ActionMenuItemView extends LinearLayout implements MenuView . ItemView , View . OnClickListener , View . OnLongClickListener , ActionMenuView . ActionMenuChildView , View_HasStateListenerSupport { private MenuItemImpl mItemData ; private CharSequence mTitle ; private MenuBuilder . ItemInvoker mItemInvoker ; private ImageButton mImageButton ; private CapitalizingButton mTextButton ; private boolean mAllowTextWithIcon ; private boolean mExpandedFormat ; private int mMinWidth ; private final Set < View_OnAttachStateChangeListener > mListeners = new HashSet < View_OnAttachStateChangeListener > ( ) ; public ActionMenuItemView ( Context context ) { this ( context , null ) ; } public ActionMenuItemView ( Context context , AttributeSet attrs ) { this ( context , attrs , <NUM_LIT:0> ) ; } public ActionMenuItemView ( Context context , AttributeSet attrs , int defStyle ) { super ( context , attrs ) ; mAllowTextWithIcon = getResources_getBoolean ( context , R . bool . abs__config_allowActionMenuItemTextWithIcon ) ; TypedArray a = context . obtainStyledAttributes ( attrs , R . styleable . SherlockActionMenuItemView , <NUM_LIT:0> , <NUM_LIT:0> ) ; mMinWidth = a . getDimensionPixelSize ( R . styleable . SherlockActionMenuItemView_android_minWidth , <NUM_LIT:0> ) ; a . recycle ( ) ; } @ Override public void addOnAttachStateChangeListener ( View_OnAttachStateChangeListener listener ) { mListeners . add ( listener ) ; } @ Override public void removeOnAttachStateChangeListener ( View_OnAttachStateChangeListener listener ) { mListeners . remove ( listener ) ; } @ Override protected void onAttachedToWindow ( ) { super . onAttachedToWindow ( ) ; for ( View_OnAttachStateChangeListener listener : mListeners ) { listener . onViewAttachedToWindow ( this ) ; } } @ Override protected void onDetachedFromWindow ( ) { super . onDetachedFromWindow ( ) ; for ( View_OnAttachStateChangeListener listener : mListeners ) { listener . onViewDetachedFromWindow ( this ) ; } } @ Override public void onFinishInflate ( ) { mImageButton = ( ImageButton ) findViewById ( R . id . abs__imageButton ) ; mTextButton = ( CapitalizingButton ) findViewById ( R . id . abs__textButton ) ; mImageButton . setOnClickListener ( this ) ; mTextButton . setOnClickListener ( this ) ; mImageButton . setOnLongClickListener ( this ) ; setOnClickListener ( this ) ; setOnLongClickListener ( this ) ; } public MenuItemImpl getItemData ( ) { return mItemData ; } public void initialize ( MenuItemImpl itemData , int menuType ) { mItemData = itemData ; setIcon ( itemData . getIcon ( ) ) ; setTitle ( itemData . getTitleForItemView ( this ) ) ; setId ( itemData . getItemId ( ) ) ; setVisibility ( itemData . isVisible ( ) ? View . VISIBLE : View . GONE ) ; setEnabled ( itemData . isEnabled ( ) ) ; } @ Override public void setEnabled ( boolean enabled ) { super . setEnabled ( enabled ) ; mImageButton . setEnabled ( enabled ) ; mTextButton . setEnabled ( enabled ) ; } public void onClick ( View v ) { if ( mItemInvoker != null ) { mItemInvoker . invokeItem ( mItemData ) ; } } public void setItemInvoker ( MenuBuilder . ItemInvoker invoker ) { mItemInvoker = invoker ; } public boolean prefersCondensedTitle ( ) { return true ; } public void setCheckable ( boolean checkable ) { } public void setChecked ( boolean checked ) { } public void setExpandedFormat ( boolean expandedFormat ) { if ( mExpandedFormat != expandedFormat ) { mExpandedFormat = expandedFormat ; if ( mItemData != null ) { mItemData . actionFormatChanged ( ) ; } } } private void updateTextButtonVisibility ( ) { boolean visible = ! TextUtils . isEmpty ( mTextButton . getText ( ) ) ; visible &= mImageButton . getDrawable ( ) == null || ( mItemData . showsTextAsAction ( ) && ( mAllowTextWithIcon || mExpandedFormat ) ) ; mTextButton . setVisibility ( visible ? VISIBLE : GONE ) ; } public void setIcon ( Drawable icon ) { mImageButton . setImageDrawable ( icon ) ; if ( icon != null ) { mImageButton . setVisibility ( VISIBLE ) ; } else { mImageButton . setVisibility ( GONE ) ; } updateTextButtonVisibility ( ) ; } public boolean hasText ( ) { return mTextButton . getVisibility ( ) != GONE ; } public void setShortcut ( boolean showShortcut , char shortcutKey ) { } public void setTitle ( CharSequence title ) { mTitle = title ; mTextButton . setTextCompat ( mTitle ) ; setContentDescription ( mTitle ) ; updateTextButtonVisibility ( ) ; } @ Override public boolean dispatchPopulateAccessibilityEvent ( AccessibilityEvent event ) { onPopulateAccessibilityEvent ( event ) ; return true ; } @ Override public void onPopulateAccessibilityEvent ( AccessibilityEvent event ) { if ( Build . VERSION . SDK_INT >= Build . VERSION_CODES . ICE_CREAM_SANDWICH ) { super . onPopulateAccessibilityEvent ( event ) ; } final CharSequence cdesc = getContentDescription ( ) ; if ( ! TextUtils . isEmpty ( cdesc ) ) { event . getText ( ) . add ( cdesc ) ; } } @ Override public boolean dispatchHoverEvent ( MotionEvent event ) { if ( Build . VERSION . SDK_INT >= Build . VERSION_CODES . ICE_CREAM_SANDWICH ) { return onHoverEvent ( event ) ; } return false ; } public boolean showsIcon ( ) { return true ; } public boolean needsDividerBefore ( ) { return hasText ( ) && mItemData . getIcon ( ) == null ; } public boolean needsDividerAfter ( ) { return hasText ( ) ; } @ Override public boolean onLongClick ( View v ) { if ( hasText ( ) ) { return false ; } final int [ ] screenPos = new int [ <NUM_LIT:2> ] ; final Rect displayFrame = new Rect ( ) ; getLocationOnScreen ( screenPos ) ; getWindowVisibleDisplayFrame ( displayFrame ) ; final Context context = getContext ( ) ; final int width = getWidth ( ) ; final int height = getHeight ( ) ; final int midy = screenPos [ <NUM_LIT:1> ] + height / <NUM_LIT:2> ; final int screenWidth = context . getResources ( ) . getDisplayMetrics ( ) . widthPixels ; Toast cheatSheet = Toast . makeText ( context , mItemData . getTitle ( ) , Toast . LENGTH_SHORT ) ; if ( midy < displayFrame . height ( ) ) { cheatSheet . setGravity ( Gravity . TOP | Gravity . RIGHT , screenWidth - screenPos [ <NUM_LIT:0> ] - width / <NUM_LIT:2> , height ) ; } else { cheatSheet . setGravity ( Gravity . BOTTOM | Gravity . CENTER_HORIZONTAL , <NUM_LIT:0> , height ) ; } cheatSheet . show ( ) ; return true ; } @ Override protected void onMeasure ( int widthMeasureSpec , int heightMeasureSpec ) { super . onMeasure ( widthMeasureSpec , heightMeasureSpec ) ; final int widthMode = MeasureSpec . getMode ( widthMeasureSpec ) ; final int specSize = MeasureSpec . getSize ( widthMeasureSpec ) ; final int oldMeasuredWidth = getMeasuredWidth ( ) ; final int targetWidth = widthMode == MeasureSpec . AT_MOST ? Math . min ( specSize , mMinWidth ) : mMinWidth ; if ( widthMode != MeasureSpec . EXACTLY && mMinWidth > <NUM_LIT:0> && oldMeasuredWidth < targetWidth ) { super . onMeasure ( MeasureSpec . makeMeasureSpec ( targetWidth , MeasureSpec . EXACTLY ) , heightMeasureSpec ) ; } } } </s>
|
<s> 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 ; public class ActionMenuItem implements MenuItem { private final int mId ; private final int mGroup ; private final int mOrdering ; private CharSequence mTitle ; private CharSequence mTitleCondensed ; private Intent mIntent ; private char mShortcutNumericChar ; private char mShortcutAlphabeticChar ; private Drawable mIconDrawable ; private Context mContext ; private MenuItem . OnMenuItemClickListener mClickListener ; private int mFlags = ENABLED ; private static final int CHECKABLE = <NUM_LIT> ; private static final int CHECKED = <NUM_LIT> ; private static final int EXCLUSIVE = <NUM_LIT> ; private static final int HIDDEN = <NUM_LIT> ; private static final int ENABLED = <NUM_LIT> ; public ActionMenuItem ( Context context , int group , int id , int categoryOrder , int ordering , CharSequence title ) { mContext = context ; mId = id ; mGroup = group ; 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 ) != <NUM_LIT:0> ; } public boolean isChecked ( ) { return ( mFlags & CHECKED ) != <NUM_LIT:0> ; } public boolean isEnabled ( ) { return ( mFlags & ENABLED ) != <NUM_LIT:0> ; } public boolean isVisible ( ) { return ( mFlags & HIDDEN ) == <NUM_LIT:0> ; } public MenuItem setAlphabeticShortcut ( char alphaChar ) { mShortcutAlphabeticChar = alphaChar ; return this ; } public MenuItem setCheckable ( boolean checkable ) { mFlags = ( mFlags & ~ CHECKABLE ) | ( checkable ? CHECKABLE : <NUM_LIT:0> ) ; return this ; } public ActionMenuItem setExclusiveCheckable ( boolean exclusive ) { mFlags = ( mFlags & ~ EXCLUSIVE ) | ( exclusive ? EXCLUSIVE : <NUM_LIT:0> ) ; return this ; } public MenuItem setChecked ( boolean checked ) { mFlags = ( mFlags & ~ CHECKED ) | ( checked ? CHECKED : <NUM_LIT:0> ) ; return this ; } public MenuItem setEnabled ( boolean enabled ) { mFlags = ( mFlags & ~ ENABLED ) | ( enabled ? ENABLED : <NUM_LIT:0> ) ; return this ; } public MenuItem setIcon ( Drawable icon ) { mIconDrawable = icon ; return this ; } public MenuItem setIcon ( int 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 ? <NUM_LIT: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 ) { } 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 ) { return this ; } } </s>
|
<s> package com . actionbarsherlock . internal . view . menu ; import android . content . ActivityNotFoundException ; import android . content . Context ; import android . content . Intent ; import android . graphics . drawable . Drawable ; import android . util . Log ; import android . view . ContextMenu . ContextMenuInfo ; import android . view . LayoutInflater ; import android . view . View ; import android . view . ViewDebug ; import android . widget . LinearLayout ; import com . actionbarsherlock . view . ActionProvider ; import com . actionbarsherlock . view . MenuItem ; import com . actionbarsherlock . view . SubMenu ; public final class MenuItemImpl implements MenuItem { private static final String TAG = "<STR_LIT>" ; private static final int SHOW_AS_ACTION_MASK = SHOW_AS_ACTION_NEVER | SHOW_AS_ACTION_IF_ROOM | SHOW_AS_ACTION_ALWAYS ; private final int mId ; private final int mGroup ; private final int mCategoryOrder ; private final int mOrdering ; private CharSequence mTitle ; private CharSequence mTitleCondensed ; private Intent mIntent ; private char mShortcutNumericChar ; private char mShortcutAlphabeticChar ; private Drawable mIconDrawable ; private int mIconResId = NO_ICON ; private MenuBuilder mMenu ; private SubMenuBuilder mSubMenu ; private Runnable mItemCallback ; private MenuItem . OnMenuItemClickListener mClickListener ; private int mFlags = ENABLED ; private static final int CHECKABLE = <NUM_LIT> ; private static final int CHECKED = <NUM_LIT> ; private static final int EXCLUSIVE = <NUM_LIT> ; private static final int HIDDEN = <NUM_LIT> ; private static final int ENABLED = <NUM_LIT> ; private static final int IS_ACTION = <NUM_LIT> ; private int mShowAsAction = SHOW_AS_ACTION_NEVER ; private View mActionView ; private ActionProvider mActionProvider ; private OnActionExpandListener mOnActionExpandListener ; private boolean mIsActionViewExpanded = false ; static final int NO_ICON = <NUM_LIT:0> ; private ContextMenuInfo mMenuInfo ; private static String sPrependShortcutLabel ; private static String sEnterShortcutLabel ; private static String sDeleteShortcutLabel ; private static String sSpaceShortcutLabel ; MenuItemImpl ( MenuBuilder menu , int group , int id , int categoryOrder , int ordering , CharSequence title , int showAsAction ) { mMenu = menu ; mId = id ; mGroup = group ; mCategoryOrder = categoryOrder ; mOrdering = ordering ; mTitle = title ; mShowAsAction = showAsAction ; } public boolean invoke ( ) { if ( mClickListener != null && mClickListener . onMenuItemClick ( this ) ) { return true ; } if ( mMenu . dispatchMenuItemSelected ( mMenu . getRootMenu ( ) , this ) ) { return true ; } if ( mItemCallback != null ) { mItemCallback . run ( ) ; return true ; } if ( mIntent != null ) { try { mMenu . getContext ( ) . startActivity ( mIntent ) ; return true ; } catch ( ActivityNotFoundException e ) { Log . e ( TAG , "<STR_LIT>" , e ) ; } } if ( mActionProvider != null && mActionProvider . onPerformDefaultAction ( ) ) { return true ; } return false ; } public boolean isEnabled ( ) { return ( mFlags & ENABLED ) != <NUM_LIT:0> ; } public MenuItem setEnabled ( boolean enabled ) { if ( enabled ) { mFlags |= ENABLED ; } else { mFlags &= ~ ENABLED ; } mMenu . onItemsChanged ( false ) ; return this ; } public int getGroupId ( ) { return mGroup ; } @ ViewDebug . CapturedViewProperty public int getItemId ( ) { return mId ; } public int getOrder ( ) { return mCategoryOrder ; } public int getOrdering ( ) { return mOrdering ; } public Intent getIntent ( ) { return mIntent ; } public MenuItem setIntent ( Intent intent ) { mIntent = intent ; return this ; } Runnable getCallback ( ) { return mItemCallback ; } public MenuItem setCallback ( Runnable callback ) { mItemCallback = callback ; return this ; } public char getAlphabeticShortcut ( ) { return mShortcutAlphabeticChar ; } public MenuItem setAlphabeticShortcut ( char alphaChar ) { if ( mShortcutAlphabeticChar == alphaChar ) return this ; mShortcutAlphabeticChar = Character . toLowerCase ( alphaChar ) ; mMenu . onItemsChanged ( false ) ; return this ; } public char getNumericShortcut ( ) { return mShortcutNumericChar ; } public MenuItem setNumericShortcut ( char numericChar ) { if ( mShortcutNumericChar == numericChar ) return this ; mShortcutNumericChar = numericChar ; mMenu . onItemsChanged ( false ) ; return this ; } public MenuItem setShortcut ( char numericChar , char alphaChar ) { mShortcutNumericChar = numericChar ; mShortcutAlphabeticChar = Character . toLowerCase ( alphaChar ) ; mMenu . onItemsChanged ( false ) ; return this ; } char getShortcut ( ) { return ( mMenu . isQwertyMode ( ) ? mShortcutAlphabeticChar : mShortcutNumericChar ) ; } String getShortcutLabel ( ) { char shortcut = getShortcut ( ) ; if ( shortcut == <NUM_LIT:0> ) { return "<STR_LIT>" ; } StringBuilder sb = new StringBuilder ( sPrependShortcutLabel ) ; switch ( shortcut ) { case '<STR_LIT:\n>' : sb . append ( sEnterShortcutLabel ) ; break ; case '<STR_LIT>' : sb . append ( sDeleteShortcutLabel ) ; break ; case '<CHAR_LIT:U+0020>' : sb . append ( sSpaceShortcutLabel ) ; break ; default : sb . append ( shortcut ) ; break ; } return sb . toString ( ) ; } boolean shouldShowShortcut ( ) { return mMenu . isShortcutsVisible ( ) && ( getShortcut ( ) != <NUM_LIT:0> ) ; } public SubMenu getSubMenu ( ) { return mSubMenu ; } public boolean hasSubMenu ( ) { return mSubMenu != null ; } void setSubMenu ( SubMenuBuilder subMenu ) { mSubMenu = subMenu ; subMenu . setHeaderTitle ( getTitle ( ) ) ; } @ ViewDebug . CapturedViewProperty public CharSequence getTitle ( ) { return mTitle ; } CharSequence getTitleForItemView ( MenuView . ItemView itemView ) { return ( ( itemView != null ) && itemView . prefersCondensedTitle ( ) ) ? getTitleCondensed ( ) : getTitle ( ) ; } public MenuItem setTitle ( CharSequence title ) { mTitle = title ; mMenu . onItemsChanged ( false ) ; if ( mSubMenu != null ) { mSubMenu . setHeaderTitle ( title ) ; } return this ; } public MenuItem setTitle ( int title ) { return setTitle ( mMenu . getContext ( ) . getString ( title ) ) ; } public CharSequence getTitleCondensed ( ) { return mTitleCondensed != null ? mTitleCondensed : mTitle ; } public MenuItem setTitleCondensed ( CharSequence title ) { mTitleCondensed = title ; if ( title == null ) { title = mTitle ; } mMenu . onItemsChanged ( false ) ; return this ; } public Drawable getIcon ( ) { if ( mIconDrawable != null ) { return mIconDrawable ; } if ( mIconResId != NO_ICON ) { return mMenu . getResources ( ) . getDrawable ( mIconResId ) ; } return null ; } public MenuItem setIcon ( Drawable icon ) { mIconResId = NO_ICON ; mIconDrawable = icon ; mMenu . onItemsChanged ( false ) ; return this ; } public MenuItem setIcon ( int iconResId ) { mIconDrawable = null ; mIconResId = iconResId ; mMenu . onItemsChanged ( false ) ; return this ; } public boolean isCheckable ( ) { return ( mFlags & CHECKABLE ) == CHECKABLE ; } public MenuItem setCheckable ( boolean checkable ) { final int oldFlags = mFlags ; mFlags = ( mFlags & ~ CHECKABLE ) | ( checkable ? CHECKABLE : <NUM_LIT:0> ) ; if ( oldFlags != mFlags ) { mMenu . onItemsChanged ( false ) ; } return this ; } public void setExclusiveCheckable ( boolean exclusive ) { mFlags = ( mFlags & ~ EXCLUSIVE ) | ( exclusive ? EXCLUSIVE : <NUM_LIT:0> ) ; } public boolean isExclusiveCheckable ( ) { return ( mFlags & EXCLUSIVE ) != <NUM_LIT:0> ; } public boolean isChecked ( ) { return ( mFlags & CHECKED ) == CHECKED ; } public MenuItem setChecked ( boolean checked ) { if ( ( mFlags & EXCLUSIVE ) != <NUM_LIT:0> ) { mMenu . setExclusiveItemChecked ( this ) ; } else { setCheckedInt ( checked ) ; } return this ; } void setCheckedInt ( boolean checked ) { final int oldFlags = mFlags ; mFlags = ( mFlags & ~ CHECKED ) | ( checked ? CHECKED : <NUM_LIT:0> ) ; if ( oldFlags != mFlags ) { mMenu . onItemsChanged ( false ) ; } } public boolean isVisible ( ) { return ( mFlags & HIDDEN ) == <NUM_LIT:0> ; } boolean setVisibleInt ( boolean shown ) { final int oldFlags = mFlags ; mFlags = ( mFlags & ~ HIDDEN ) | ( shown ? <NUM_LIT:0> : HIDDEN ) ; return oldFlags != mFlags ; } public MenuItem setVisible ( boolean shown ) { if ( setVisibleInt ( shown ) ) mMenu . onItemVisibleChanged ( this ) ; return this ; } public MenuItem setOnMenuItemClickListener ( MenuItem . OnMenuItemClickListener clickListener ) { mClickListener = clickListener ; return this ; } @ Override public String toString ( ) { return mTitle . toString ( ) ; } void setMenuInfo ( ContextMenuInfo menuInfo ) { mMenuInfo = menuInfo ; } public ContextMenuInfo getMenuInfo ( ) { return mMenuInfo ; } public void actionFormatChanged ( ) { mMenu . onItemActionRequestChanged ( this ) ; } public boolean shouldShowIcon ( ) { return mMenu . getOptionalIconsVisible ( ) ; } public boolean isActionButton ( ) { return ( mFlags & IS_ACTION ) == IS_ACTION ; } public boolean requestsActionButton ( ) { return ( mShowAsAction & SHOW_AS_ACTION_IF_ROOM ) == SHOW_AS_ACTION_IF_ROOM ; } public boolean requiresActionButton ( ) { return ( mShowAsAction & SHOW_AS_ACTION_ALWAYS ) == SHOW_AS_ACTION_ALWAYS ; } public void setIsActionButton ( boolean isActionButton ) { if ( isActionButton ) { mFlags |= IS_ACTION ; } else { mFlags &= ~ IS_ACTION ; } } public boolean showsTextAsAction ( ) { return ( mShowAsAction & SHOW_AS_ACTION_WITH_TEXT ) == SHOW_AS_ACTION_WITH_TEXT ; } public void setShowAsAction ( int actionEnum ) { switch ( actionEnum & SHOW_AS_ACTION_MASK ) { case SHOW_AS_ACTION_ALWAYS : case SHOW_AS_ACTION_IF_ROOM : case SHOW_AS_ACTION_NEVER : break ; default : throw new IllegalArgumentException ( "<STR_LIT>" + "<STR_LIT>" ) ; } mShowAsAction = actionEnum ; mMenu . onItemActionRequestChanged ( this ) ; } public MenuItem setActionView ( View view ) { mActionView = view ; mActionProvider = null ; if ( view != null && view . getId ( ) == View . NO_ID && mId > <NUM_LIT:0> ) { view . setId ( mId ) ; } mMenu . onItemActionRequestChanged ( this ) ; return this ; } public MenuItem setActionView ( int resId ) { final Context context = mMenu . getContext ( ) ; final LayoutInflater inflater = LayoutInflater . from ( context ) ; setActionView ( inflater . inflate ( resId , new LinearLayout ( context ) , false ) ) ; return this ; } public View getActionView ( ) { if ( mActionView != null ) { return mActionView ; } else if ( mActionProvider != null ) { mActionView = mActionProvider . onCreateActionView ( ) ; return mActionView ; } else { return null ; } } public ActionProvider getActionProvider ( ) { return mActionProvider ; } public MenuItem setActionProvider ( ActionProvider actionProvider ) { mActionView = null ; mActionProvider = actionProvider ; mMenu . onItemsChanged ( true ) ; return this ; } @ Override public MenuItem setShowAsActionFlags ( int actionEnum ) { setShowAsAction ( actionEnum ) ; return this ; } @ Override public boolean expandActionView ( ) { if ( ( mShowAsAction & SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW ) == <NUM_LIT:0> || mActionView == null ) { return false ; } if ( mOnActionExpandListener == null || mOnActionExpandListener . onMenuItemActionExpand ( this ) ) { return mMenu . expandItemActionView ( this ) ; } return false ; } @ Override public boolean collapseActionView ( ) { if ( ( mShowAsAction & SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW ) == <NUM_LIT:0> ) { return false ; } if ( mActionView == null ) { return true ; } if ( mOnActionExpandListener == null || mOnActionExpandListener . onMenuItemActionCollapse ( this ) ) { return mMenu . collapseItemActionView ( this ) ; } return false ; } @ Override public MenuItem setOnActionExpandListener ( OnActionExpandListener listener ) { mOnActionExpandListener = listener ; return this ; } public boolean hasCollapsibleActionView ( ) { return ( mShowAsAction & SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW ) != <NUM_LIT:0> && mActionView != null ; } public void setActionViewExpanded ( boolean isExpanded ) { mIsActionViewExpanded = isExpanded ; mMenu . onItemsChanged ( false ) ; } public boolean isActionViewExpanded ( ) { return mIsActionViewExpanded ; } } </s>
|
<s> package com . actionbarsherlock . internal . view . menu ; import android . content . Context ; import android . graphics . drawable . Drawable ; import android . view . View ; import com . actionbarsherlock . view . Menu ; import com . actionbarsherlock . view . MenuItem ; import com . actionbarsherlock . view . SubMenu ; public class SubMenuBuilder extends MenuBuilder implements SubMenu { private MenuBuilder mParentMenu ; private MenuItemImpl mItem ; public SubMenuBuilder ( Context context , MenuBuilder parentMenu , MenuItemImpl item ) { super ( context ) ; mParentMenu = parentMenu ; mItem = item ; } @ Override public void setQwertyMode ( boolean isQwerty ) { mParentMenu . setQwertyMode ( isQwerty ) ; } @ Override public boolean isQwertyMode ( ) { return mParentMenu . isQwertyMode ( ) ; } @ Override public void setShortcutsVisible ( boolean shortcutsVisible ) { mParentMenu . setShortcutsVisible ( shortcutsVisible ) ; } @ Override public boolean isShortcutsVisible ( ) { return mParentMenu . isShortcutsVisible ( ) ; } public Menu getParentMenu ( ) { return mParentMenu ; } public MenuItem getItem ( ) { return mItem ; } @ Override public void setCallback ( Callback callback ) { mParentMenu . setCallback ( callback ) ; } @ Override public MenuBuilder getRootMenu ( ) { return mParentMenu ; } @ Override boolean dispatchMenuItemSelected ( MenuBuilder menu , MenuItem item ) { return super . dispatchMenuItemSelected ( menu , item ) || mParentMenu . dispatchMenuItemSelected ( menu , item ) ; } public SubMenu setIcon ( Drawable icon ) { mItem . setIcon ( icon ) ; return this ; } public SubMenu setIcon ( int iconRes ) { mItem . setIcon ( iconRes ) ; return this ; } public SubMenu setHeaderIcon ( Drawable icon ) { return ( SubMenu ) super . setHeaderIconInt ( icon ) ; } public SubMenu setHeaderIcon ( int iconRes ) { return ( SubMenu ) super . setHeaderIconInt ( iconRes ) ; } public SubMenu setHeaderTitle ( CharSequence title ) { return ( SubMenu ) super . setHeaderTitleInt ( title ) ; } public SubMenu setHeaderTitle ( int titleRes ) { return ( SubMenu ) super . setHeaderTitleInt ( titleRes ) ; } public SubMenu setHeaderView ( View view ) { return ( SubMenu ) super . setHeaderViewInt ( view ) ; } @ Override public boolean expandItemActionView ( MenuItemImpl item ) { return mParentMenu . expandItemActionView ( item ) ; } @ Override public boolean collapseItemActionView ( MenuItemImpl item ) { return mParentMenu . collapseItemActionView ( item ) ; } @ Override public String getActionViewStatesKey ( ) { final int itemId = mItem != null ? mItem . getItemId ( ) : <NUM_LIT:0> ; if ( itemId == <NUM_LIT:0> ) { return null ; } return super . getActionViewStatesKey ( ) + "<STR_LIT::>" + itemId ; } } </s>
|
<s> 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 ; 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 ; 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 , <NUM_LIT:0> ) ; mBackground = a . getDrawable ( R . styleable . SherlockMenuView_itemBackground ) ; mTextAppearance = a . getResourceId ( R . styleable . SherlockMenuView_itemTextAppearance , - <NUM_LIT:1> ) ; mPreserveIconSpacing = a . getBoolean ( R . styleable . SherlockMenuView_preserveIconSpacing , false ) ; mTextAppearanceContext = context ; a . recycle ( ) ; } public ListMenuItemView ( Context context , AttributeSet attrs ) { this ( context , attrs , <NUM_LIT:0> ) ; } @ Override protected void onFinishInflate ( ) { super . onFinishInflate ( ) ; setBackgroundDrawable ( mBackground ) ; mTitleView = ( TextView ) findViewById ( R . id . abs__title ) ; if ( mTextAppearance != - <NUM_LIT:1> ) { mTitleView . setTextAppearance ( mTextAppearanceContext , mTextAppearance ) ; } mShortcutView = ( TextView ) findViewById ( R . id . abs__shortcut ) ; } public void initialize ( MenuItemImpl itemData , int menuType ) { mItemData = itemData ; 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 ( ) ; } 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 ) ; } 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 ) { ViewGroup . LayoutParams lp = getLayoutParams ( ) ; LayoutParams iconLp = ( LayoutParams ) mIconView . getLayoutParams ( ) ; if ( lp . height > <NUM_LIT:0> && iconLp . width <= <NUM_LIT: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 , <NUM_LIT: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 ; } } </s>
|
<s> package com . actionbarsherlock . internal . view . menu ; import static com . actionbarsherlock . internal . ResourcesCompat . getResources_getInteger ; import java . util . ArrayList ; import java . util . HashSet ; import java . util . Set ; import android . content . Context ; import android . content . res . Configuration ; import android . content . res . Resources ; import android . content . res . TypedArray ; import android . os . Build ; import android . os . Parcel ; import android . os . Parcelable ; import android . util . SparseBooleanArray ; import android . view . SoundEffectConstants ; import android . view . View ; import android . view . View . MeasureSpec ; import android . view . ViewConfiguration ; import android . view . ViewGroup ; import android . widget . ImageButton ; import com . actionbarsherlock . R ; import com . actionbarsherlock . internal . view . View_HasStateListenerSupport ; import com . actionbarsherlock . internal . view . View_OnAttachStateChangeListener ; import com . actionbarsherlock . internal . view . menu . ActionMenuView . ActionMenuChildView ; import com . actionbarsherlock . view . ActionProvider ; import com . actionbarsherlock . view . MenuItem ; public class ActionMenuPresenter extends BaseMenuPresenter implements ActionProvider . SubUiVisibilityListener { private View mOverflowButton ; private boolean mReserveOverflow ; private boolean mReserveOverflowSet ; private int mWidthLimit ; private int mActionItemWidthLimit ; private int mMaxItems ; private boolean mMaxItemsSet ; private boolean mStrictWidthLimit ; private boolean mWidthLimitSet ; private boolean mExpandedActionViewsExclusive ; private int mMinCellSize ; private final SparseBooleanArray mActionButtonGroups = new SparseBooleanArray ( ) ; private View mScrapActionButtonView ; private OverflowPopup mOverflowPopup ; private ActionButtonSubmenu mActionButtonPopup ; private OpenOverflowRunnable mPostedOpenRunnable ; final PopupPresenterCallback mPopupPresenterCallback = new PopupPresenterCallback ( ) ; int mOpenSubMenuId ; public ActionMenuPresenter ( Context context ) { super ( context , R . layout . abs__action_menu_layout , R . layout . abs__action_menu_item_layout ) ; } @ Override public void initForMenu ( Context context , MenuBuilder menu ) { super . initForMenu ( context , menu ) ; final Resources res = context . getResources ( ) ; if ( ! mReserveOverflowSet ) { mReserveOverflow = reserveOverflow ( mContext ) ; } if ( ! mWidthLimitSet ) { mWidthLimit = res . getDisplayMetrics ( ) . widthPixels / <NUM_LIT:2> ; } if ( ! mMaxItemsSet ) { mMaxItems = getResources_getInteger ( context , R . integer . abs__max_action_buttons ) ; } int width = mWidthLimit ; if ( mReserveOverflow ) { if ( mOverflowButton == null ) { mOverflowButton = new OverflowMenuButton ( mSystemContext ) ; final int spec = MeasureSpec . makeMeasureSpec ( <NUM_LIT:0> , MeasureSpec . UNSPECIFIED ) ; mOverflowButton . measure ( spec , spec ) ; } width -= mOverflowButton . getMeasuredWidth ( ) ; } else { mOverflowButton = null ; } mActionItemWidthLimit = width ; mMinCellSize = ( int ) ( ActionMenuView . MIN_CELL_SIZE * res . getDisplayMetrics ( ) . density ) ; mScrapActionButtonView = null ; } public static boolean reserveOverflow ( Context context ) { TypedArray a = context . getTheme ( ) . obtainStyledAttributes ( R . styleable . SherlockTheme ) ; boolean result = a . getBoolean ( R . styleable . SherlockTheme_absForceOverflow , false ) ; a . recycle ( ) ; if ( result ) { return true ; } if ( Build . VERSION . SDK_INT < Build . VERSION_CODES . ICE_CREAM_SANDWICH ) { return ( Build . VERSION . SDK_INT >= Build . VERSION_CODES . HONEYCOMB ) ; } else { return ! HasPermanentMenuKey . get ( context ) ; } } private static class HasPermanentMenuKey { public static boolean get ( Context context ) { return ViewConfiguration . get ( context ) . hasPermanentMenuKey ( ) ; } } public void onConfigurationChanged ( Configuration newConfig ) { if ( ! mMaxItemsSet ) { mMaxItems = getResources_getInteger ( mContext , R . integer . abs__max_action_buttons ) ; if ( mMenu != null ) { mMenu . onItemsChanged ( true ) ; } } } public void setWidthLimit ( int width , boolean strict ) { mWidthLimit = width ; mStrictWidthLimit = strict ; mWidthLimitSet = true ; } public void setReserveOverflow ( boolean reserveOverflow ) { mReserveOverflow = reserveOverflow ; mReserveOverflowSet = true ; } public void setItemLimit ( int itemCount ) { mMaxItems = itemCount ; mMaxItemsSet = true ; } public void setExpandedActionViewsExclusive ( boolean isExclusive ) { mExpandedActionViewsExclusive = isExclusive ; } @ Override public MenuView getMenuView ( ViewGroup root ) { MenuView result = super . getMenuView ( root ) ; ( ( ActionMenuView ) result ) . setPresenter ( this ) ; return result ; } @ Override public View getItemView ( MenuItemImpl item , View convertView , ViewGroup parent ) { View actionView = item . getActionView ( ) ; if ( actionView == null || item . hasCollapsibleActionView ( ) ) { if ( ! ( convertView instanceof ActionMenuItemView ) ) { convertView = null ; } actionView = super . getItemView ( item , convertView , parent ) ; } actionView . setVisibility ( item . isActionViewExpanded ( ) ? View . GONE : View . VISIBLE ) ; final ActionMenuView menuParent = ( ActionMenuView ) parent ; final ViewGroup . LayoutParams lp = actionView . getLayoutParams ( ) ; if ( ! menuParent . checkLayoutParams ( lp ) ) { actionView . setLayoutParams ( menuParent . generateLayoutParams ( lp ) ) ; } return actionView ; } @ Override public void bindItemView ( MenuItemImpl item , MenuView . ItemView itemView ) { itemView . initialize ( item , <NUM_LIT:0> ) ; final ActionMenuView menuView = ( ActionMenuView ) mMenuView ; ActionMenuItemView actionItemView = ( ActionMenuItemView ) itemView ; actionItemView . setItemInvoker ( menuView ) ; } @ Override public boolean shouldIncludeItem ( int childIndex , MenuItemImpl item ) { return item . isActionButton ( ) ; } @ Override public void updateMenuView ( boolean cleared ) { super . updateMenuView ( cleared ) ; if ( mMenu != null ) { final ArrayList < MenuItemImpl > actionItems = mMenu . getActionItems ( ) ; final int count = actionItems . size ( ) ; for ( int i = <NUM_LIT:0> ; i < count ; i ++ ) { final ActionProvider provider = actionItems . get ( i ) . getActionProvider ( ) ; if ( provider != null ) { provider . setSubUiVisibilityListener ( this ) ; } } } final ArrayList < MenuItemImpl > nonActionItems = mMenu != null ? mMenu . getNonActionItems ( ) : null ; boolean hasOverflow = false ; if ( mReserveOverflow && nonActionItems != null ) { final int count = nonActionItems . size ( ) ; if ( count == <NUM_LIT:1> ) { hasOverflow = ! nonActionItems . get ( <NUM_LIT:0> ) . isActionViewExpanded ( ) ; } else { hasOverflow = count > <NUM_LIT:0> ; } } if ( hasOverflow ) { if ( mOverflowButton == null ) { mOverflowButton = new OverflowMenuButton ( mSystemContext ) ; } ViewGroup parent = ( ViewGroup ) mOverflowButton . getParent ( ) ; if ( parent != mMenuView ) { if ( parent != null ) { parent . removeView ( mOverflowButton ) ; } ActionMenuView menuView = ( ActionMenuView ) mMenuView ; menuView . addView ( mOverflowButton , menuView . generateOverflowButtonLayoutParams ( ) ) ; } } else if ( mOverflowButton != null && mOverflowButton . getParent ( ) == mMenuView ) { ( ( ViewGroup ) mMenuView ) . removeView ( mOverflowButton ) ; } ( ( ActionMenuView ) mMenuView ) . setOverflowReserved ( mReserveOverflow ) ; } @ Override public boolean filterLeftoverView ( ViewGroup parent , int childIndex ) { if ( parent . getChildAt ( childIndex ) == mOverflowButton ) return false ; return super . filterLeftoverView ( parent , childIndex ) ; } public boolean onSubMenuSelected ( SubMenuBuilder subMenu ) { if ( ! subMenu . hasVisibleItems ( ) ) return false ; SubMenuBuilder topSubMenu = subMenu ; while ( topSubMenu . getParentMenu ( ) != mMenu ) { topSubMenu = ( SubMenuBuilder ) topSubMenu . getParentMenu ( ) ; } View anchor = findViewForItem ( topSubMenu . getItem ( ) ) ; if ( anchor == null ) { if ( mOverflowButton == null ) return false ; anchor = mOverflowButton ; } mOpenSubMenuId = subMenu . getItem ( ) . getItemId ( ) ; mActionButtonPopup = new ActionButtonSubmenu ( mContext , subMenu ) ; mActionButtonPopup . setAnchorView ( anchor ) ; mActionButtonPopup . show ( ) ; super . onSubMenuSelected ( subMenu ) ; return true ; } private View findViewForItem ( MenuItem item ) { final ViewGroup parent = ( ViewGroup ) mMenuView ; if ( parent == null ) return null ; final int count = parent . getChildCount ( ) ; for ( int i = <NUM_LIT:0> ; i < count ; i ++ ) { final View child = parent . getChildAt ( i ) ; if ( child instanceof MenuView . ItemView && ( ( MenuView . ItemView ) child ) . getItemData ( ) == item ) { return child ; } } return null ; } public boolean showOverflowMenu ( ) { if ( mReserveOverflow && ! isOverflowMenuShowing ( ) && mMenu != null && mMenuView != null && mPostedOpenRunnable == null && ! mMenu . getNonActionItems ( ) . isEmpty ( ) ) { OverflowPopup popup = new OverflowPopup ( mContext , mMenu , mOverflowButton , true ) ; mPostedOpenRunnable = new OpenOverflowRunnable ( popup ) ; ( ( View ) mMenuView ) . post ( mPostedOpenRunnable ) ; super . onSubMenuSelected ( null ) ; return true ; } return false ; } public boolean hideOverflowMenu ( ) { if ( mPostedOpenRunnable != null && mMenuView != null ) { ( ( View ) mMenuView ) . removeCallbacks ( mPostedOpenRunnable ) ; mPostedOpenRunnable = null ; return true ; } MenuPopupHelper popup = mOverflowPopup ; if ( popup != null ) { popup . dismiss ( ) ; return true ; } return false ; } public boolean dismissPopupMenus ( ) { boolean result = hideOverflowMenu ( ) ; result |= hideSubMenus ( ) ; return result ; } public boolean hideSubMenus ( ) { if ( mActionButtonPopup != null ) { mActionButtonPopup . dismiss ( ) ; return true ; } return false ; } public boolean isOverflowMenuShowing ( ) { return mOverflowPopup != null && mOverflowPopup . isShowing ( ) ; } public boolean isOverflowReserved ( ) { return mReserveOverflow ; } public boolean flagActionItems ( ) { final ArrayList < MenuItemImpl > visibleItems = mMenu . getVisibleItems ( ) ; final int itemsSize = visibleItems . size ( ) ; int maxActions = mMaxItems ; int widthLimit = mActionItemWidthLimit ; final int querySpec = MeasureSpec . makeMeasureSpec ( <NUM_LIT:0> , MeasureSpec . UNSPECIFIED ) ; final ViewGroup parent = ( ViewGroup ) mMenuView ; int requiredItems = <NUM_LIT:0> ; int requestedItems = <NUM_LIT:0> ; int firstActionWidth = <NUM_LIT:0> ; boolean hasOverflow = false ; for ( int i = <NUM_LIT:0> ; i < itemsSize ; i ++ ) { MenuItemImpl item = visibleItems . get ( i ) ; if ( item . requiresActionButton ( ) ) { requiredItems ++ ; } else if ( item . requestsActionButton ( ) ) { requestedItems ++ ; } else { hasOverflow = true ; } if ( mExpandedActionViewsExclusive && item . isActionViewExpanded ( ) ) { maxActions = <NUM_LIT:0> ; } } if ( mReserveOverflow && ( hasOverflow || requiredItems + requestedItems > maxActions ) ) { maxActions -- ; } maxActions -= requiredItems ; final SparseBooleanArray seenGroups = mActionButtonGroups ; seenGroups . clear ( ) ; int cellSize = <NUM_LIT:0> ; int cellsRemaining = <NUM_LIT:0> ; if ( mStrictWidthLimit ) { cellsRemaining = widthLimit / mMinCellSize ; final int cellSizeRemaining = widthLimit % mMinCellSize ; cellSize = mMinCellSize + cellSizeRemaining / cellsRemaining ; } for ( int i = <NUM_LIT:0> ; i < itemsSize ; i ++ ) { MenuItemImpl item = visibleItems . get ( i ) ; if ( item . requiresActionButton ( ) ) { View v = getItemView ( item , mScrapActionButtonView , parent ) ; if ( mScrapActionButtonView == null ) { mScrapActionButtonView = v ; } if ( mStrictWidthLimit ) { cellsRemaining -= ActionMenuView . measureChildForCells ( v , cellSize , cellsRemaining , querySpec , <NUM_LIT:0> ) ; } else { v . measure ( querySpec , querySpec ) ; } final int measuredWidth = v . getMeasuredWidth ( ) ; widthLimit -= measuredWidth ; if ( firstActionWidth == <NUM_LIT:0> ) { firstActionWidth = measuredWidth ; } final int groupId = item . getGroupId ( ) ; if ( groupId != <NUM_LIT:0> ) { seenGroups . put ( groupId , true ) ; } item . setIsActionButton ( true ) ; } else if ( item . requestsActionButton ( ) ) { final int groupId = item . getGroupId ( ) ; final boolean inGroup = seenGroups . get ( groupId ) ; boolean isAction = ( maxActions > <NUM_LIT:0> || inGroup ) && widthLimit > <NUM_LIT:0> && ( ! mStrictWidthLimit || cellsRemaining > <NUM_LIT:0> ) ; if ( isAction ) { View v = getItemView ( item , mScrapActionButtonView , parent ) ; if ( mScrapActionButtonView == null ) { mScrapActionButtonView = v ; } if ( mStrictWidthLimit ) { final int cells = ActionMenuView . measureChildForCells ( v , cellSize , cellsRemaining , querySpec , <NUM_LIT:0> ) ; cellsRemaining -= cells ; if ( cells == <NUM_LIT:0> ) { isAction = false ; } } else { v . measure ( querySpec , querySpec ) ; } final int measuredWidth = v . getMeasuredWidth ( ) ; widthLimit -= measuredWidth ; if ( firstActionWidth == <NUM_LIT:0> ) { firstActionWidth = measuredWidth ; } if ( mStrictWidthLimit ) { isAction &= widthLimit >= <NUM_LIT:0> ; } else { isAction &= widthLimit + firstActionWidth > <NUM_LIT:0> ; } } if ( isAction && groupId != <NUM_LIT:0> ) { seenGroups . put ( groupId , true ) ; } else if ( inGroup ) { seenGroups . put ( groupId , false ) ; for ( int j = <NUM_LIT:0> ; j < i ; j ++ ) { MenuItemImpl areYouMyGroupie = visibleItems . get ( j ) ; if ( areYouMyGroupie . getGroupId ( ) == groupId ) { if ( areYouMyGroupie . isActionButton ( ) ) maxActions ++ ; areYouMyGroupie . setIsActionButton ( false ) ; } } } if ( isAction ) maxActions -- ; item . setIsActionButton ( isAction ) ; } } return true ; } @ Override public void onCloseMenu ( MenuBuilder menu , boolean allMenusAreClosing ) { dismissPopupMenus ( ) ; super . onCloseMenu ( menu , allMenusAreClosing ) ; } @ Override public Parcelable onSaveInstanceState ( ) { SavedState state = new SavedState ( ) ; state . openSubMenuId = mOpenSubMenuId ; return state ; } @ Override public void onRestoreInstanceState ( Parcelable state ) { SavedState saved = ( SavedState ) state ; if ( saved . openSubMenuId > <NUM_LIT:0> ) { MenuItem item = mMenu . findItem ( saved . openSubMenuId ) ; if ( item != null ) { SubMenuBuilder subMenu = ( SubMenuBuilder ) item . getSubMenu ( ) ; onSubMenuSelected ( subMenu ) ; } } } @ Override public void onSubUiVisibilityChanged ( boolean isVisible ) { if ( isVisible ) { super . onSubMenuSelected ( null ) ; } else { mMenu . close ( false ) ; } } private static class SavedState implements Parcelable { public int openSubMenuId ; SavedState ( ) { } SavedState ( Parcel in ) { openSubMenuId = in . readInt ( ) ; } @ Override public int describeContents ( ) { return <NUM_LIT:0> ; } @ Override public void writeToParcel ( Parcel dest , int flags ) { dest . writeInt ( openSubMenuId ) ; } @ SuppressWarnings ( "<STR_LIT:unused>" ) public static final Parcelable . Creator < SavedState > CREATOR = new Parcelable . Creator < SavedState > ( ) { public SavedState createFromParcel ( Parcel in ) { return new SavedState ( in ) ; } public SavedState [ ] newArray ( int size ) { return new SavedState [ size ] ; } } ; } private class OverflowMenuButton extends ImageButton implements ActionMenuChildView , View_HasStateListenerSupport { private final Set < View_OnAttachStateChangeListener > mListeners = new HashSet < View_OnAttachStateChangeListener > ( ) ; public OverflowMenuButton ( Context context ) { super ( context , null , R . attr . actionOverflowButtonStyle ) ; setClickable ( true ) ; setFocusable ( true ) ; setVisibility ( VISIBLE ) ; setEnabled ( true ) ; } @ Override public boolean performClick ( ) { if ( super . performClick ( ) ) { return true ; } playSoundEffect ( SoundEffectConstants . CLICK ) ; showOverflowMenu ( ) ; return true ; } public boolean needsDividerBefore ( ) { return false ; } public boolean needsDividerAfter ( ) { return false ; } @ Override protected void onAttachedToWindow ( ) { super . onAttachedToWindow ( ) ; for ( View_OnAttachStateChangeListener listener : mListeners ) { listener . onViewAttachedToWindow ( this ) ; } } @ Override protected void onDetachedFromWindow ( ) { super . onDetachedFromWindow ( ) ; for ( View_OnAttachStateChangeListener listener : mListeners ) { listener . onViewDetachedFromWindow ( this ) ; } } @ Override public void addOnAttachStateChangeListener ( View_OnAttachStateChangeListener listener ) { mListeners . add ( listener ) ; } @ Override public void removeOnAttachStateChangeListener ( View_OnAttachStateChangeListener listener ) { mListeners . remove ( listener ) ; } } private class OverflowPopup extends MenuPopupHelper { public OverflowPopup ( Context context , MenuBuilder menu , View anchorView , boolean overflowOnly ) { super ( context , menu , anchorView , overflowOnly ) ; setCallback ( mPopupPresenterCallback ) ; } @ Override public void onDismiss ( ) { super . onDismiss ( ) ; mMenu . close ( ) ; mOverflowPopup = null ; } } private class ActionButtonSubmenu extends MenuPopupHelper { public ActionButtonSubmenu ( Context context , SubMenuBuilder subMenu ) { super ( context , subMenu ) ; MenuItemImpl item = ( MenuItemImpl ) subMenu . getItem ( ) ; if ( ! item . isActionButton ( ) ) { setAnchorView ( mOverflowButton == null ? ( View ) mMenuView : mOverflowButton ) ; } setCallback ( mPopupPresenterCallback ) ; boolean preserveIconSpacing = false ; final int count = subMenu . size ( ) ; for ( int i = <NUM_LIT:0> ; i < count ; i ++ ) { MenuItem childItem = subMenu . getItem ( i ) ; if ( childItem . isVisible ( ) && childItem . getIcon ( ) != null ) { preserveIconSpacing = true ; break ; } } setForceShowIcon ( preserveIconSpacing ) ; } @ Override public void onDismiss ( ) { super . onDismiss ( ) ; mActionButtonPopup = null ; mOpenSubMenuId = <NUM_LIT:0> ; } } private class PopupPresenterCallback implements MenuPresenter . Callback { @ Override public boolean onOpenSubMenu ( MenuBuilder subMenu ) { if ( subMenu == null ) return false ; mOpenSubMenuId = ( ( SubMenuBuilder ) subMenu ) . getItem ( ) . getItemId ( ) ; return false ; } @ Override public void onCloseMenu ( MenuBuilder menu , boolean allMenusAreClosing ) { if ( menu instanceof SubMenuBuilder ) { ( ( SubMenuBuilder ) menu ) . getRootMenu ( ) . close ( false ) ; } } } private class OpenOverflowRunnable implements Runnable { private OverflowPopup mPopup ; public OpenOverflowRunnable ( OverflowPopup popup ) { mPopup = popup ; } public void run ( ) { mMenu . changeMenuMode ( ) ; final View menuView = ( View ) mMenuView ; if ( menuView != null && menuView . getWindowToken ( ) != null && mPopup . tryShow ( ) ) { mOverflowPopup = mPopup ; } mPostedOpenRunnable = null ; } } } </s>
|
<s> package com . actionbarsherlock . internal . view . menu ; import android . graphics . drawable . Drawable ; public interface MenuView { public void initialize ( MenuBuilder menu ) ; public int getWindowAnimations ( ) ; public interface ItemView { public void initialize ( MenuItemImpl itemData , int menuType ) ; public MenuItemImpl getItemData ( ) ; public void setTitle ( CharSequence title ) ; public void setEnabled ( boolean enabled ) ; public void setCheckable ( boolean checkable ) ; public void setChecked ( boolean checked ) ; public void setShortcut ( boolean showShortcut , char shortcutKey ) ; public void setIcon ( Drawable icon ) ; public boolean prefersCondensedTitle ( ) ; public boolean showsIcon ( ) ; } } </s>
|
<s> package com . actionbarsherlock . internal . view ; public interface View_HasStateListenerSupport { void addOnAttachStateChangeListener ( View_OnAttachStateChangeListener listener ) ; void removeOnAttachStateChangeListener ( View_OnAttachStateChangeListener listener ) ; } </s>
|
<s> 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 ; } } </s>
|
<s> package com . actionbarsherlock . internal . view ; import android . view . View ; public interface View_OnAttachStateChangeListener { void onViewAttachedToWindow ( View v ) ; void onViewDetachedFromWindow ( View v ) ; } </s>
|
<s> package com . actionbarsherlock . internal ; import static android . view . ViewGroup . LayoutParams . MATCH_PARENT ; import static com . actionbarsherlock . internal . ResourcesCompat . getResources_getBoolean ; import java . util . ArrayList ; import java . util . HashMap ; import java . util . List ; import org . xmlpull . v1 . XmlPullParser ; import android . app . Activity ; import android . content . Context ; import android . content . pm . ActivityInfo ; import android . content . res . AssetManager ; import android . content . res . Configuration ; import android . content . res . Resources ; import android . content . res . TypedArray ; import android . content . res . XmlResourceParser ; import android . os . Bundle ; import android . util . AndroidRuntimeException ; import android . util . Log ; import android . util . TypedValue ; import android . view . ContextThemeWrapper ; import android . view . KeyCharacterMap ; import android . view . KeyEvent ; import android . view . View ; import android . view . ViewGroup ; import android . view . ViewStub ; import android . view . Window ; import android . view . accessibility . AccessibilityEvent ; import android . view . animation . Animation ; import android . view . animation . AnimationUtils ; import android . widget . FrameLayout ; import android . widget . TextView ; import com . actionbarsherlock . ActionBarSherlock ; import com . actionbarsherlock . R ; import com . actionbarsherlock . app . ActionBar ; import com . actionbarsherlock . internal . app . ActionBarImpl ; import com . actionbarsherlock . internal . view . StandaloneActionMode ; import com . actionbarsherlock . internal . view . menu . ActionMenuPresenter ; 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 . widget . ActionBarContainer ; import com . actionbarsherlock . internal . widget . ActionBarContextView ; import com . actionbarsherlock . internal . widget . ActionBarView ; import com . actionbarsherlock . internal . widget . IcsProgressBar ; import com . actionbarsherlock . view . ActionMode ; import com . actionbarsherlock . view . Menu ; import com . actionbarsherlock . view . MenuItem ; @ ActionBarSherlock . Implementation ( api = <NUM_LIT:7> ) public class ActionBarSherlockCompat extends ActionBarSherlock implements MenuBuilder . Callback , com . actionbarsherlock . view . Window . Callback , MenuPresenter . Callback , android . view . MenuItem . OnMenuItemClickListener { protected static final int DEFAULT_FEATURES = <NUM_LIT:0> ; public ActionBarSherlockCompat ( Activity activity , int flags ) { super ( activity , flags ) ; } private boolean mReserveOverflow ; private boolean mReserveOverflowSet = false ; private MenuBuilder mMenu ; protected HashMap < android . view . MenuItem , MenuItemImpl > mNativeItemMap ; private boolean mMenuKeyIsLongPress = false ; private ViewGroup mDecor ; private ViewGroup mContentParent ; private boolean mIsTitleReady = false ; private boolean mIsDestroyed = false ; private boolean mClosingActionMenu ; private boolean mMenuIsPrepared ; private boolean mMenuRefreshContent ; private Bundle mMenuFrozenActionViewState ; private ActionBarImpl aActionBar ; private ActionBarView wActionBar ; private int mFeatures = DEFAULT_FEATURES ; private int mUiOptions = <NUM_LIT:0> ; private IcsProgressBar mCircularProgressBar ; private IcsProgressBar mHorizontalProgressBar ; private ActionMode mActionMode ; private ActionBarContextView mActionModeView ; private TextView mTitleView ; private CharSequence mTitle = null ; private boolean mIsFloating ; @ Override public ActionBar getActionBar ( ) { if ( DEBUG ) Log . d ( TAG , "<STR_LIT>" ) ; initActionBar ( ) ; return aActionBar ; } private void initActionBar ( ) { if ( DEBUG ) Log . d ( TAG , "<STR_LIT>" ) ; if ( mDecor == null ) { installDecor ( ) ; } if ( ( aActionBar != null ) || ! hasFeature ( Window . FEATURE_ACTION_BAR ) || hasFeature ( Window . FEATURE_NO_TITLE ) || mActivity . isChild ( ) ) { return ; } aActionBar = new ActionBarImpl ( mActivity , mFeatures ) ; if ( ! mIsDelegate ) { wActionBar . setWindowTitle ( mActivity . getTitle ( ) ) ; } } @ Override protected Context getThemedContext ( ) { return aActionBar . getThemedContext ( ) ; } @ Override public void setTitle ( CharSequence title ) { if ( DEBUG ) Log . d ( TAG , "<STR_LIT>" + title ) ; dispatchTitleChanged ( title , <NUM_LIT:0> ) ; } @ Override public ActionMode startActionMode ( ActionMode . Callback callback ) { if ( DEBUG ) Log . d ( TAG , "<STR_LIT>" + callback ) ; if ( mActionMode != null ) { mActionMode . finish ( ) ; } final ActionMode . Callback wrappedCallback = new ActionModeCallbackWrapper ( callback ) ; ActionMode mode = null ; initActionBar ( ) ; if ( aActionBar != null ) { mode = aActionBar . startActionMode ( wrappedCallback ) ; } if ( mode != null ) { mActionMode = mode ; } else { if ( mActionModeView == null ) { ViewStub stub = ( ViewStub ) mDecor . findViewById ( R . id . abs__action_mode_bar_stub ) ; if ( stub != null ) { mActionModeView = ( ActionBarContextView ) stub . inflate ( ) ; } } if ( mActionModeView != null ) { mActionModeView . killMode ( ) ; mode = new StandaloneActionMode ( mActivity , mActionModeView , wrappedCallback , true ) ; if ( callback . onCreateActionMode ( mode , mode . getMenu ( ) ) ) { mode . invalidate ( ) ; mActionModeView . initForMode ( mode ) ; mActionModeView . setVisibility ( View . VISIBLE ) ; mActionMode = mode ; mActionModeView . sendAccessibilityEvent ( AccessibilityEvent . TYPE_WINDOW_STATE_CHANGED ) ; } else { mActionMode = null ; } } } if ( mActionMode != null && mActivity instanceof OnActionModeStartedListener ) { ( ( OnActionModeStartedListener ) mActivity ) . onActionModeStarted ( mActionMode ) ; } return mActionMode ; } @ Override public void dispatchConfigurationChanged ( Configuration newConfig ) { if ( DEBUG ) Log . d ( TAG , "<STR_LIT>" + newConfig ) ; if ( aActionBar != null ) { aActionBar . onConfigurationChanged ( newConfig ) ; } } @ Override public void dispatchPostResume ( ) { if ( DEBUG ) Log . d ( TAG , "<STR_LIT>" ) ; if ( aActionBar != null ) { aActionBar . setShowHideAnimationEnabled ( true ) ; } } @ Override public void dispatchPause ( ) { if ( DEBUG ) Log . d ( TAG , "<STR_LIT>" ) ; if ( wActionBar != null && wActionBar . isOverflowMenuShowing ( ) ) { wActionBar . hideOverflowMenu ( ) ; } } @ Override public void dispatchStop ( ) { if ( DEBUG ) Log . d ( TAG , "<STR_LIT>" ) ; if ( aActionBar != null ) { aActionBar . setShowHideAnimationEnabled ( false ) ; } } @ Override public void dispatchInvalidateOptionsMenu ( ) { if ( DEBUG ) Log . d ( TAG , "<STR_LIT>" ) ; Bundle savedActionViewStates = null ; if ( mMenu != null ) { savedActionViewStates = new Bundle ( ) ; mMenu . saveActionViewStates ( savedActionViewStates ) ; if ( savedActionViewStates . size ( ) > <NUM_LIT:0> ) { mMenuFrozenActionViewState = savedActionViewStates ; } mMenu . stopDispatchingItemsChanged ( ) ; mMenu . clear ( ) ; } mMenuRefreshContent = true ; if ( wActionBar != null ) { mMenuIsPrepared = false ; preparePanel ( ) ; } } @ Override public boolean dispatchOpenOptionsMenu ( ) { if ( DEBUG ) Log . d ( TAG , "<STR_LIT>" ) ; if ( ! isReservingOverflow ( ) ) { return false ; } return wActionBar . showOverflowMenu ( ) ; } @ Override public boolean dispatchCloseOptionsMenu ( ) { if ( DEBUG ) Log . d ( TAG , "<STR_LIT>" ) ; if ( ! isReservingOverflow ( ) ) { return false ; } return wActionBar . hideOverflowMenu ( ) ; } @ Override public void dispatchPostCreate ( Bundle savedInstanceState ) { if ( DEBUG ) Log . d ( TAG , "<STR_LIT>" ) ; if ( mIsDelegate ) { mIsTitleReady = true ; } if ( mDecor == null ) { initActionBar ( ) ; } } @ Override public boolean dispatchCreateOptionsMenu ( android . view . Menu menu ) { if ( DEBUG ) { Log . d ( TAG , "<STR_LIT>" + menu ) ; Log . d ( TAG , "<STR_LIT>" ) ; } return true ; } @ Override public boolean dispatchPrepareOptionsMenu ( android . view . Menu menu ) { if ( DEBUG ) Log . d ( TAG , "<STR_LIT>" + menu ) ; if ( mActionMode != null ) { return false ; } mMenuIsPrepared = false ; if ( ! preparePanel ( ) ) { return false ; } if ( isReservingOverflow ( ) ) { return false ; } if ( mNativeItemMap == null ) { mNativeItemMap = new HashMap < android . view . MenuItem , MenuItemImpl > ( ) ; } else { mNativeItemMap . clear ( ) ; } if ( mMenu == null ) { return false ; } boolean result = mMenu . bindNativeOverflow ( menu , this , mNativeItemMap ) ; if ( DEBUG ) Log . d ( TAG , "<STR_LIT>" + result ) ; return result ; } @ Override public boolean dispatchOptionsItemSelected ( android . view . MenuItem item ) { throw new IllegalStateException ( "<STR_LIT>" ) ; } @ Override public boolean dispatchMenuOpened ( int featureId , android . view . Menu menu ) { if ( DEBUG ) Log . d ( TAG , "<STR_LIT>" + featureId + "<STR_LIT>" + menu ) ; if ( featureId == Window . FEATURE_ACTION_BAR || featureId == Window . FEATURE_OPTIONS_PANEL ) { if ( aActionBar != null ) { aActionBar . dispatchMenuVisibilityChanged ( true ) ; } return true ; } return false ; } @ Override public void dispatchPanelClosed ( int featureId , android . view . Menu menu ) { if ( DEBUG ) Log . d ( TAG , "<STR_LIT>" + featureId + "<STR_LIT>" + menu ) ; if ( featureId == Window . FEATURE_ACTION_BAR || featureId == Window . FEATURE_OPTIONS_PANEL ) { if ( aActionBar != null ) { aActionBar . dispatchMenuVisibilityChanged ( false ) ; } } } @ Override public void dispatchTitleChanged ( CharSequence title , int color ) { if ( DEBUG ) Log . d ( TAG , "<STR_LIT>" + title + "<STR_LIT>" + color ) ; if ( ! mIsDelegate || mIsTitleReady ) { if ( mTitleView != null ) { mTitleView . setText ( title ) ; } else if ( wActionBar != null ) { wActionBar . setWindowTitle ( title ) ; } } mTitle = title ; } @ Override public boolean dispatchKeyEvent ( KeyEvent event ) { if ( DEBUG ) Log . d ( TAG , "<STR_LIT>" + event ) ; final int keyCode = event . getKeyCode ( ) ; if ( keyCode == KeyEvent . KEYCODE_BACK ) { final int action = event . getAction ( ) ; if ( mActionMode != null ) { if ( action == KeyEvent . ACTION_UP ) { mActionMode . finish ( ) ; } if ( DEBUG ) Log . d ( TAG , "<STR_LIT>" ) ; return true ; } if ( wActionBar != null && wActionBar . hasExpandedActionView ( ) ) { if ( action == KeyEvent . ACTION_UP ) { wActionBar . collapseActionView ( ) ; } if ( DEBUG ) Log . d ( TAG , "<STR_LIT>" ) ; return true ; } } boolean result = false ; if ( keyCode == KeyEvent . KEYCODE_MENU && isReservingOverflow ( ) ) { if ( event . getAction ( ) == KeyEvent . ACTION_DOWN && event . isLongPress ( ) ) { mMenuKeyIsLongPress = true ; } else if ( event . getAction ( ) == KeyEvent . ACTION_UP ) { if ( ! mMenuKeyIsLongPress ) { if ( mActionMode == null && wActionBar != null ) { if ( wActionBar . isOverflowMenuShowing ( ) ) { wActionBar . hideOverflowMenu ( ) ; } else { wActionBar . showOverflowMenu ( ) ; } } result = true ; } mMenuKeyIsLongPress = false ; } } if ( DEBUG ) Log . d ( TAG , "<STR_LIT>" + result ) ; return result ; } @ Override public void dispatchDestroy ( ) { mIsDestroyed = true ; } private boolean preparePanel ( ) { if ( mMenuIsPrepared ) { return true ; } if ( mMenu == null || mMenuRefreshContent ) { if ( mMenu == null ) { if ( ! initializePanelMenu ( ) || ( mMenu == null ) ) { return false ; } } if ( wActionBar != null ) { wActionBar . setMenu ( mMenu , this ) ; } mMenu . stopDispatchingItemsChanged ( ) ; if ( ! callbackCreateOptionsMenu ( mMenu ) ) { mMenu = null ; if ( wActionBar != null ) { wActionBar . setMenu ( null , this ) ; } return false ; } mMenuRefreshContent = false ; } mMenu . stopDispatchingItemsChanged ( ) ; if ( mMenuFrozenActionViewState != null ) { mMenu . restoreActionViewStates ( mMenuFrozenActionViewState ) ; mMenuFrozenActionViewState = null ; } if ( ! callbackPrepareOptionsMenu ( mMenu ) ) { if ( wActionBar != null ) { wActionBar . setMenu ( null , this ) ; } mMenu . startDispatchingItemsChanged ( ) ; return false ; } KeyCharacterMap kmap = KeyCharacterMap . load ( KeyCharacterMap . VIRTUAL_KEYBOARD ) ; mMenu . setQwertyMode ( kmap . getKeyboardType ( ) != KeyCharacterMap . NUMERIC ) ; mMenu . startDispatchingItemsChanged ( ) ; mMenuIsPrepared = true ; return true ; } public boolean onMenuItemSelected ( MenuBuilder menu , MenuItem item ) { return callbackOptionsItemSelected ( item ) ; } public void onMenuModeChange ( MenuBuilder menu ) { reopenMenu ( true ) ; } private void reopenMenu ( boolean toggleMenuMode ) { if ( wActionBar != null && wActionBar . isOverflowReserved ( ) ) { if ( ! wActionBar . isOverflowMenuShowing ( ) || ! toggleMenuMode ) { if ( wActionBar . getVisibility ( ) == View . VISIBLE ) { if ( callbackPrepareOptionsMenu ( mMenu ) ) { wActionBar . showOverflowMenu ( ) ; } } } else { wActionBar . hideOverflowMenu ( ) ; } return ; } } private boolean initializePanelMenu ( ) { Context context = mActivity ; if ( wActionBar != null ) { TypedValue outValue = new TypedValue ( ) ; Resources . Theme currentTheme = context . getTheme ( ) ; currentTheme . resolveAttribute ( R . attr . actionBarWidgetTheme , outValue , true ) ; final int targetThemeRes = outValue . resourceId ; if ( targetThemeRes != <NUM_LIT:0> ) { context = new ContextThemeWrapper ( context , targetThemeRes ) ; } } mMenu = new MenuBuilder ( context ) ; mMenu . setCallback ( this ) ; return true ; } void checkCloseActionMenu ( Menu menu ) { if ( mClosingActionMenu ) { return ; } mClosingActionMenu = true ; wActionBar . dismissPopupMenus ( ) ; mClosingActionMenu = false ; } @ Override public boolean onOpenSubMenu ( MenuBuilder subMenu ) { return true ; } @ Override public void onCloseMenu ( MenuBuilder menu , boolean allMenusAreClosing ) { checkCloseActionMenu ( menu ) ; } @ Override public boolean onMenuItemClick ( android . view . MenuItem item ) { if ( DEBUG ) Log . d ( TAG , "<STR_LIT>" + item ) ; final MenuItemImpl sherlockItem = mNativeItemMap . get ( item ) ; if ( sherlockItem != null ) { sherlockItem . invoke ( ) ; } else { Log . e ( TAG , "<STR_LIT>" + item + "<STR_LIT>" ) ; } return true ; } @ Override public boolean onMenuItemSelected ( int featureId , MenuItem item ) { return callbackOptionsItemSelected ( item ) ; } @ Override public void setProgressBarVisibility ( boolean visible ) { if ( DEBUG ) Log . d ( TAG , "<STR_LIT>" + visible ) ; setFeatureInt ( Window . FEATURE_PROGRESS , visible ? Window . PROGRESS_VISIBILITY_ON : Window . PROGRESS_VISIBILITY_OFF ) ; } @ Override public void setProgressBarIndeterminateVisibility ( boolean visible ) { if ( DEBUG ) Log . d ( TAG , "<STR_LIT>" + visible ) ; setFeatureInt ( Window . FEATURE_INDETERMINATE_PROGRESS , visible ? Window . PROGRESS_VISIBILITY_ON : Window . PROGRESS_VISIBILITY_OFF ) ; } @ Override public void setProgressBarIndeterminate ( boolean indeterminate ) { if ( DEBUG ) Log . d ( TAG , "<STR_LIT>" + indeterminate ) ; setFeatureInt ( Window . FEATURE_PROGRESS , indeterminate ? Window . PROGRESS_INDETERMINATE_ON : Window . PROGRESS_INDETERMINATE_OFF ) ; } @ Override public void setProgress ( int progress ) { if ( DEBUG ) Log . d ( TAG , "<STR_LIT>" + progress ) ; setFeatureInt ( Window . FEATURE_PROGRESS , progress + Window . PROGRESS_START ) ; } @ Override public void setSecondaryProgress ( int secondaryProgress ) { if ( DEBUG ) Log . d ( TAG , "<STR_LIT>" + secondaryProgress ) ; setFeatureInt ( Window . FEATURE_PROGRESS , secondaryProgress + Window . PROGRESS_SECONDARY_START ) ; } private void setFeatureInt ( int featureId , int value ) { updateInt ( featureId , value , false ) ; } private void updateInt ( int featureId , int value , boolean fromResume ) { if ( mContentParent == null ) { return ; } final int featureMask = <NUM_LIT:1> << featureId ; if ( ( getFeatures ( ) & featureMask ) == <NUM_LIT:0> && ! fromResume ) { return ; } onIntChanged ( featureId , value ) ; } private void onIntChanged ( int featureId , int value ) { if ( featureId == Window . FEATURE_PROGRESS || featureId == Window . FEATURE_INDETERMINATE_PROGRESS ) { updateProgressBars ( value ) ; } } private void updateProgressBars ( int value ) { IcsProgressBar circularProgressBar = getCircularProgressBar ( true ) ; IcsProgressBar horizontalProgressBar = getHorizontalProgressBar ( true ) ; final int features = mFeatures ; if ( value == Window . PROGRESS_VISIBILITY_ON ) { if ( ( features & ( <NUM_LIT:1> << Window . FEATURE_PROGRESS ) ) != <NUM_LIT:0> ) { int level = horizontalProgressBar . getProgress ( ) ; int visibility = ( horizontalProgressBar . isIndeterminate ( ) || level < <NUM_LIT> ) ? View . VISIBLE : View . INVISIBLE ; horizontalProgressBar . setVisibility ( visibility ) ; } if ( ( features & ( <NUM_LIT:1> << Window . FEATURE_INDETERMINATE_PROGRESS ) ) != <NUM_LIT:0> ) { circularProgressBar . setVisibility ( View . VISIBLE ) ; } } else if ( value == Window . PROGRESS_VISIBILITY_OFF ) { if ( ( features & ( <NUM_LIT:1> << Window . FEATURE_PROGRESS ) ) != <NUM_LIT:0> ) { horizontalProgressBar . setVisibility ( View . GONE ) ; } if ( ( features & ( <NUM_LIT:1> << Window . FEATURE_INDETERMINATE_PROGRESS ) ) != <NUM_LIT:0> ) { circularProgressBar . setVisibility ( View . GONE ) ; } } else if ( value == Window . PROGRESS_INDETERMINATE_ON ) { horizontalProgressBar . setIndeterminate ( true ) ; } else if ( value == Window . PROGRESS_INDETERMINATE_OFF ) { horizontalProgressBar . setIndeterminate ( false ) ; } else if ( Window . PROGRESS_START <= value && value <= Window . PROGRESS_END ) { horizontalProgressBar . setProgress ( value - Window . PROGRESS_START ) ; if ( value < Window . PROGRESS_END ) { showProgressBars ( horizontalProgressBar , circularProgressBar ) ; } else { hideProgressBars ( horizontalProgressBar , circularProgressBar ) ; } } else if ( Window . PROGRESS_SECONDARY_START <= value && value <= Window . PROGRESS_SECONDARY_END ) { horizontalProgressBar . setSecondaryProgress ( value - Window . PROGRESS_SECONDARY_START ) ; showProgressBars ( horizontalProgressBar , circularProgressBar ) ; } } private void showProgressBars ( IcsProgressBar horizontalProgressBar , IcsProgressBar spinnyProgressBar ) { final int features = mFeatures ; if ( ( features & ( <NUM_LIT:1> << Window . FEATURE_INDETERMINATE_PROGRESS ) ) != <NUM_LIT:0> && spinnyProgressBar . getVisibility ( ) == View . INVISIBLE ) { spinnyProgressBar . setVisibility ( View . VISIBLE ) ; } if ( ( features & ( <NUM_LIT:1> << Window . FEATURE_PROGRESS ) ) != <NUM_LIT:0> && horizontalProgressBar . getProgress ( ) < <NUM_LIT> ) { horizontalProgressBar . setVisibility ( View . VISIBLE ) ; } } private void hideProgressBars ( IcsProgressBar horizontalProgressBar , IcsProgressBar spinnyProgressBar ) { final int features = mFeatures ; Animation anim = AnimationUtils . loadAnimation ( mActivity , android . R . anim . fade_out ) ; anim . setDuration ( <NUM_LIT:1000> ) ; if ( ( features & ( <NUM_LIT:1> << Window . FEATURE_INDETERMINATE_PROGRESS ) ) != <NUM_LIT:0> && spinnyProgressBar . getVisibility ( ) == View . VISIBLE ) { spinnyProgressBar . startAnimation ( anim ) ; spinnyProgressBar . setVisibility ( View . INVISIBLE ) ; } if ( ( features & ( <NUM_LIT:1> << Window . FEATURE_PROGRESS ) ) != <NUM_LIT:0> && horizontalProgressBar . getVisibility ( ) == View . VISIBLE ) { horizontalProgressBar . startAnimation ( anim ) ; horizontalProgressBar . setVisibility ( View . INVISIBLE ) ; } } private IcsProgressBar getCircularProgressBar ( boolean shouldInstallDecor ) { if ( mCircularProgressBar != null ) { return mCircularProgressBar ; } if ( mContentParent == null && shouldInstallDecor ) { installDecor ( ) ; } mCircularProgressBar = ( IcsProgressBar ) mDecor . findViewById ( R . id . abs__progress_circular ) ; if ( mCircularProgressBar != null ) { mCircularProgressBar . setVisibility ( View . INVISIBLE ) ; } return mCircularProgressBar ; } private IcsProgressBar getHorizontalProgressBar ( boolean shouldInstallDecor ) { if ( mHorizontalProgressBar != null ) { return mHorizontalProgressBar ; } if ( mContentParent == null && shouldInstallDecor ) { installDecor ( ) ; } mHorizontalProgressBar = ( IcsProgressBar ) mDecor . findViewById ( R . id . abs__progress_horizontal ) ; if ( mHorizontalProgressBar != null ) { mHorizontalProgressBar . setVisibility ( View . INVISIBLE ) ; } return mHorizontalProgressBar ; } private int getFeatures ( ) { if ( DEBUG ) Log . d ( TAG , "<STR_LIT>" + mFeatures ) ; return mFeatures ; } @ Override public boolean hasFeature ( int featureId ) { if ( DEBUG ) Log . d ( TAG , "<STR_LIT>" + featureId ) ; boolean result = ( mFeatures & ( <NUM_LIT:1> << featureId ) ) != <NUM_LIT:0> ; if ( DEBUG ) Log . d ( TAG , "<STR_LIT>" + result ) ; return result ; } @ Override public boolean requestFeature ( int featureId ) { if ( DEBUG ) Log . d ( TAG , "<STR_LIT>" + featureId ) ; if ( mContentParent != null ) { throw new AndroidRuntimeException ( "<STR_LIT>" ) ; } switch ( featureId ) { case Window . FEATURE_ACTION_BAR : case Window . FEATURE_ACTION_BAR_OVERLAY : case Window . FEATURE_ACTION_MODE_OVERLAY : case Window . FEATURE_INDETERMINATE_PROGRESS : case Window . FEATURE_NO_TITLE : case Window . FEATURE_PROGRESS : mFeatures |= ( <NUM_LIT:1> << featureId ) ; return true ; default : return false ; } } @ Override public void setUiOptions ( int uiOptions ) { if ( DEBUG ) Log . d ( TAG , "<STR_LIT>" + uiOptions ) ; mUiOptions = uiOptions ; } @ Override public void setUiOptions ( int uiOptions , int mask ) { if ( DEBUG ) Log . d ( TAG , "<STR_LIT>" + uiOptions + "<STR_LIT>" + mask ) ; mUiOptions = ( mUiOptions & ~ mask ) | ( uiOptions & mask ) ; } @ Override public void setContentView ( int layoutResId ) { if ( DEBUG ) Log . d ( TAG , "<STR_LIT>" + layoutResId ) ; if ( mContentParent == null ) { installDecor ( ) ; } else { mContentParent . removeAllViews ( ) ; } mActivity . getLayoutInflater ( ) . inflate ( layoutResId , mContentParent ) ; android . view . Window . Callback callback = mActivity . getWindow ( ) . getCallback ( ) ; if ( callback != null ) { callback . onContentChanged ( ) ; } initActionBar ( ) ; } @ Override public void setContentView ( View view , ViewGroup . LayoutParams params ) { if ( DEBUG ) Log . d ( TAG , "<STR_LIT>" + view + "<STR_LIT>" + params ) ; if ( mContentParent == null ) { installDecor ( ) ; } else { mContentParent . removeAllViews ( ) ; } mContentParent . addView ( view , params ) ; android . view . Window . Callback callback = mActivity . getWindow ( ) . getCallback ( ) ; if ( callback != null ) { callback . onContentChanged ( ) ; } initActionBar ( ) ; } @ Override public void addContentView ( View view , ViewGroup . LayoutParams params ) { if ( DEBUG ) Log . d ( TAG , "<STR_LIT>" + view + "<STR_LIT>" + params ) ; if ( mContentParent == null ) { installDecor ( ) ; } mContentParent . addView ( view , params ) ; initActionBar ( ) ; } private void installDecor ( ) { if ( DEBUG ) Log . d ( TAG , "<STR_LIT>" ) ; if ( mDecor == null ) { mDecor = ( ViewGroup ) mActivity . getWindow ( ) . getDecorView ( ) . findViewById ( android . R . id . content ) ; } if ( mContentParent == null ) { List < View > views = null ; if ( mDecor . getChildCount ( ) > <NUM_LIT:0> ) { views = new ArrayList < View > ( <NUM_LIT:1> ) ; for ( int i = <NUM_LIT:0> , children = mDecor . getChildCount ( ) ; i < children ; i ++ ) { View child = mDecor . getChildAt ( <NUM_LIT:0> ) ; mDecor . removeView ( child ) ; views . add ( child ) ; } } mContentParent = generateLayout ( ) ; if ( views != null ) { for ( View child : views ) { mContentParent . addView ( child ) ; } } mTitleView = ( TextView ) mDecor . findViewById ( android . R . id . title ) ; if ( mTitleView != null ) { if ( hasFeature ( Window . FEATURE_NO_TITLE ) ) { mTitleView . setVisibility ( View . GONE ) ; if ( mContentParent instanceof FrameLayout ) { ( ( FrameLayout ) mContentParent ) . setForeground ( null ) ; } } else { mTitleView . setText ( mTitle ) ; } } else { wActionBar = ( ActionBarView ) mDecor . findViewById ( R . id . abs__action_bar ) ; if ( wActionBar != null ) { wActionBar . setWindowCallback ( this ) ; if ( wActionBar . getTitle ( ) == null ) { wActionBar . setWindowTitle ( mActivity . getTitle ( ) ) ; } if ( hasFeature ( Window . FEATURE_PROGRESS ) ) { wActionBar . initProgress ( ) ; } if ( hasFeature ( Window . FEATURE_INDETERMINATE_PROGRESS ) ) { wActionBar . initIndeterminateProgress ( ) ; } int uiOptions = loadUiOptionsFromManifest ( mActivity ) ; if ( uiOptions != <NUM_LIT:0> ) { mUiOptions = uiOptions ; } boolean splitActionBar = false ; final boolean splitWhenNarrow = ( mUiOptions & ActivityInfo . UIOPTION_SPLIT_ACTION_BAR_WHEN_NARROW ) != <NUM_LIT:0> ; if ( splitWhenNarrow ) { splitActionBar = getResources_getBoolean ( mActivity , R . bool . abs__split_action_bar_is_narrow ) ; } else { splitActionBar = mActivity . getTheme ( ) . obtainStyledAttributes ( R . styleable . SherlockTheme ) . getBoolean ( R . styleable . SherlockTheme_windowSplitActionBar , false ) ; } final ActionBarContainer splitView = ( ActionBarContainer ) mDecor . findViewById ( R . id . abs__split_action_bar ) ; if ( splitView != null ) { wActionBar . setSplitView ( splitView ) ; wActionBar . setSplitActionBar ( splitActionBar ) ; wActionBar . setSplitWhenNarrow ( splitWhenNarrow ) ; mActionModeView = ( ActionBarContextView ) mDecor . findViewById ( R . id . abs__action_context_bar ) ; mActionModeView . setSplitView ( splitView ) ; mActionModeView . setSplitActionBar ( splitActionBar ) ; mActionModeView . setSplitWhenNarrow ( splitWhenNarrow ) ; } else if ( splitActionBar ) { Log . e ( TAG , "<STR_LIT>" ) ; } mDecor . post ( new Runnable ( ) { @ Override public void run ( ) { if ( ! mIsDestroyed && ! mActivity . isFinishing ( ) && mMenu == null ) { dispatchInvalidateOptionsMenu ( ) ; } } } ) ; } } } } private ViewGroup generateLayout ( ) { if ( DEBUG ) Log . d ( TAG , "<STR_LIT>" ) ; TypedArray a = mActivity . getTheme ( ) . obtainStyledAttributes ( R . styleable . SherlockTheme ) ; mIsFloating = a . getBoolean ( R . styleable . SherlockTheme_android_windowIsFloating , false ) ; if ( ! a . hasValue ( R . styleable . SherlockTheme_windowActionBar ) ) { throw new IllegalStateException ( "<STR_LIT>" ) ; } if ( a . getBoolean ( R . styleable . SherlockTheme_windowNoTitle , false ) ) { requestFeature ( Window . FEATURE_NO_TITLE ) ; } else if ( a . getBoolean ( R . styleable . SherlockTheme_windowActionBar , false ) ) { requestFeature ( Window . FEATURE_ACTION_BAR ) ; } if ( a . getBoolean ( R . styleable . SherlockTheme_windowActionBarOverlay , false ) ) { requestFeature ( Window . FEATURE_ACTION_BAR_OVERLAY ) ; } if ( a . getBoolean ( R . styleable . SherlockTheme_windowActionModeOverlay , false ) ) { requestFeature ( Window . FEATURE_ACTION_MODE_OVERLAY ) ; } a . recycle ( ) ; int layoutResource ; if ( ! hasFeature ( Window . FEATURE_NO_TITLE ) ) { if ( mIsFloating ) { mDecor = ( ViewGroup ) mDecor . getParent ( ) ; mDecor . removeAllViews ( ) ; layoutResource = R . layout . abs__dialog_title_holo ; } else { if ( hasFeature ( Window . FEATURE_ACTION_BAR_OVERLAY ) ) { layoutResource = R . layout . abs__screen_action_bar_overlay ; } else { layoutResource = R . layout . abs__screen_action_bar ; } } } else if ( hasFeature ( Window . FEATURE_ACTION_MODE_OVERLAY ) && ! hasFeature ( Window . FEATURE_NO_TITLE ) ) { layoutResource = R . layout . abs__screen_simple_overlay_action_mode ; } else { layoutResource = R . layout . abs__screen_simple ; } if ( DEBUG ) Log . d ( TAG , "<STR_LIT>" + mActivity . getResources ( ) . getString ( layoutResource ) ) ; View in = mActivity . getLayoutInflater ( ) . inflate ( layoutResource , null ) ; mDecor . addView ( in , new ViewGroup . LayoutParams ( MATCH_PARENT , MATCH_PARENT ) ) ; ViewGroup contentParent = ( ViewGroup ) mDecor . findViewById ( R . id . abs__content ) ; if ( contentParent == null ) { throw new RuntimeException ( "<STR_LIT>" ) ; } mDecor . setId ( View . NO_ID ) ; contentParent . setId ( android . R . id . content ) ; if ( hasFeature ( Window . FEATURE_INDETERMINATE_PROGRESS ) ) { IcsProgressBar progress = getCircularProgressBar ( false ) ; if ( progress != null ) { progress . setIndeterminate ( true ) ; } } return contentParent ; } private boolean isReservingOverflow ( ) { if ( ! mReserveOverflowSet ) { mReserveOverflow = ActionMenuPresenter . reserveOverflow ( mActivity ) ; mReserveOverflowSet = true ; } return mReserveOverflow ; } private static int loadUiOptionsFromManifest ( Activity activity ) { int uiOptions = <NUM_LIT:0> ; try { final String thisPackage = activity . getClass ( ) . getName ( ) ; if ( DEBUG ) Log . i ( TAG , "<STR_LIT>" + thisPackage ) ; final String packageName = activity . getApplicationInfo ( ) . packageName ; final AssetManager am = activity . createPackageContext ( packageName , <NUM_LIT:0> ) . getAssets ( ) ; final XmlResourceParser xml = am . openXmlResourceParser ( "<STR_LIT>" ) ; int eventType = xml . getEventType ( ) ; while ( eventType != XmlPullParser . END_DOCUMENT ) { if ( eventType == XmlPullParser . START_TAG ) { String name = xml . getName ( ) ; if ( "<STR_LIT>" . equals ( name ) ) { if ( DEBUG ) Log . d ( TAG , "<STR_LIT>" ) ; for ( int i = xml . getAttributeCount ( ) - <NUM_LIT:1> ; i >= <NUM_LIT:0> ; i -- ) { if ( DEBUG ) Log . d ( TAG , xml . getAttributeName ( i ) + "<STR_LIT::U+0020>" + xml . getAttributeValue ( i ) ) ; if ( "<STR_LIT>" . equals ( xml . getAttributeName ( i ) ) ) { uiOptions = xml . getAttributeIntValue ( i , <NUM_LIT:0> ) ; break ; } } } else if ( "<STR_LIT>" . equals ( name ) ) { if ( DEBUG ) Log . d ( TAG , "<STR_LIT>" ) ; Integer activityUiOptions = null ; String activityPackage = null ; boolean isOurActivity = false ; for ( int i = xml . getAttributeCount ( ) - <NUM_LIT:1> ; i >= <NUM_LIT:0> ; i -- ) { if ( DEBUG ) Log . d ( TAG , xml . getAttributeName ( i ) + "<STR_LIT::U+0020>" + xml . getAttributeValue ( i ) ) ; String attrName = xml . getAttributeName ( i ) ; if ( "<STR_LIT>" . equals ( attrName ) ) { activityUiOptions = xml . getAttributeIntValue ( i , <NUM_LIT:0> ) ; } else if ( "<STR_LIT:name>" . equals ( attrName ) ) { activityPackage = cleanActivityName ( packageName , xml . getAttributeValue ( i ) ) ; if ( ! thisPackage . equals ( activityPackage ) ) { break ; } isOurActivity = true ; } if ( ( activityUiOptions != null ) && ( activityPackage != null ) ) { uiOptions = activityUiOptions . intValue ( ) ; } } if ( isOurActivity ) { break ; } } } eventType = xml . nextToken ( ) ; } } catch ( Exception e ) { e . printStackTrace ( ) ; } if ( DEBUG ) Log . i ( TAG , "<STR_LIT>" + Integer . toHexString ( uiOptions ) ) ; return uiOptions ; } public static String cleanActivityName ( String manifestPackage , String activityName ) { if ( activityName . charAt ( <NUM_LIT:0> ) == '<CHAR_LIT:.>' ) { return manifestPackage + activityName ; } if ( activityName . indexOf ( '<CHAR_LIT:.>' , <NUM_LIT:1> ) == - <NUM_LIT:1> ) { return manifestPackage + "<STR_LIT:.>" + activityName ; } return activityName ; } private class ActionModeCallbackWrapper implements ActionMode . Callback { private final ActionMode . Callback mWrapped ; public ActionModeCallbackWrapper ( ActionMode . Callback wrapped ) { mWrapped = wrapped ; } public boolean onCreateActionMode ( ActionMode mode , Menu menu ) { return mWrapped . onCreateActionMode ( mode , menu ) ; } public boolean onPrepareActionMode ( ActionMode mode , Menu menu ) { return mWrapped . onPrepareActionMode ( mode , menu ) ; } public boolean onActionItemClicked ( ActionMode mode , MenuItem item ) { return mWrapped . onActionItemClicked ( mode , item ) ; } public void onDestroyActionMode ( ActionMode mode ) { mWrapped . onDestroyActionMode ( mode ) ; if ( mActionModeView != null ) { mActionModeView . setVisibility ( View . GONE ) ; mActionModeView . removeAllViews ( ) ; } if ( mActivity instanceof OnActionModeFinishedListener ) { ( ( OnActionModeFinishedListener ) mActivity ) . onActionModeFinished ( mActionMode ) ; } mActionMode = null ; } } } </s>
|
<s> package com . actionbarsherlock . internal . nineoldandroids . widget ; import android . content . Context ; import android . util . AttributeSet ; import android . widget . LinearLayout ; import com . actionbarsherlock . internal . nineoldandroids . view . animation . AnimatorProxy ; public class NineLinearLayout extends LinearLayout { private final AnimatorProxy mProxy ; public NineLinearLayout ( Context context ) { super ( context ) ; mProxy = AnimatorProxy . NEEDS_PROXY ? AnimatorProxy . wrap ( this ) : null ; } public NineLinearLayout ( Context context , AttributeSet attrs ) { super ( context , attrs ) ; mProxy = AnimatorProxy . NEEDS_PROXY ? AnimatorProxy . wrap ( this ) : null ; } public NineLinearLayout ( Context context , AttributeSet attrs , int defStyle ) { super ( context , attrs , defStyle ) ; mProxy = AnimatorProxy . NEEDS_PROXY ? AnimatorProxy . wrap ( this ) : null ; } @ Override public void setVisibility ( int visibility ) { if ( mProxy != null ) { if ( visibility == GONE ) { clearAnimation ( ) ; } else if ( visibility == VISIBLE ) { setAnimation ( mProxy ) ; } } super . setVisibility ( visibility ) ; } public float getAlpha ( ) { if ( AnimatorProxy . NEEDS_PROXY ) { return mProxy . getAlpha ( ) ; } else { return super . getAlpha ( ) ; } } public void setAlpha ( float alpha ) { if ( AnimatorProxy . NEEDS_PROXY ) { mProxy . setAlpha ( alpha ) ; } else { super . setAlpha ( alpha ) ; } } public float getTranslationX ( ) { if ( AnimatorProxy . NEEDS_PROXY ) { return mProxy . getTranslationX ( ) ; } else { return super . getTranslationX ( ) ; } } public void setTranslationX ( float translationX ) { if ( AnimatorProxy . NEEDS_PROXY ) { mProxy . setTranslationX ( translationX ) ; } else { super . setTranslationX ( translationX ) ; } } } </s>
|
<s> package com . actionbarsherlock . internal . nineoldandroids . widget ; import android . content . Context ; import android . widget . HorizontalScrollView ; import com . actionbarsherlock . internal . nineoldandroids . view . animation . AnimatorProxy ; public class NineHorizontalScrollView extends HorizontalScrollView { private final AnimatorProxy mProxy ; public NineHorizontalScrollView ( Context context ) { super ( context ) ; mProxy = AnimatorProxy . NEEDS_PROXY ? AnimatorProxy . wrap ( this ) : null ; } @ Override public void setVisibility ( int visibility ) { if ( mProxy != null ) { if ( visibility == GONE ) { clearAnimation ( ) ; } else if ( visibility == VISIBLE ) { setAnimation ( mProxy ) ; } } super . setVisibility ( visibility ) ; } public float getAlpha ( ) { if ( AnimatorProxy . NEEDS_PROXY ) { return mProxy . getAlpha ( ) ; } else { return super . getAlpha ( ) ; } } public void setAlpha ( float alpha ) { if ( AnimatorProxy . NEEDS_PROXY ) { mProxy . setAlpha ( alpha ) ; } else { super . setAlpha ( alpha ) ; } } } </s>
|
<s> package com . actionbarsherlock . internal . nineoldandroids . widget ; import android . content . Context ; import android . util . AttributeSet ; import android . widget . FrameLayout ; import com . actionbarsherlock . internal . nineoldandroids . view . animation . AnimatorProxy ; public class NineFrameLayout extends FrameLayout { private final AnimatorProxy mProxy ; public NineFrameLayout ( Context context ) { super ( context ) ; mProxy = AnimatorProxy . NEEDS_PROXY ? AnimatorProxy . wrap ( this ) : null ; } public NineFrameLayout ( Context context , AttributeSet attrs ) { super ( context , attrs ) ; mProxy = AnimatorProxy . NEEDS_PROXY ? AnimatorProxy . wrap ( this ) : null ; } public NineFrameLayout ( Context context , AttributeSet attrs , int defStyle ) { super ( context , attrs , defStyle ) ; mProxy = AnimatorProxy . NEEDS_PROXY ? AnimatorProxy . wrap ( this ) : null ; } @ Override public void setVisibility ( int visibility ) { if ( mProxy != null ) { if ( visibility == GONE ) { clearAnimation ( ) ; } else if ( visibility == VISIBLE ) { setAnimation ( mProxy ) ; } } super . setVisibility ( visibility ) ; } public float getAlpha ( ) { if ( AnimatorProxy . NEEDS_PROXY ) { return mProxy . getAlpha ( ) ; } else { return super . getAlpha ( ) ; } } public void setAlpha ( float alpha ) { if ( AnimatorProxy . NEEDS_PROXY ) { mProxy . setAlpha ( alpha ) ; } else { super . setAlpha ( alpha ) ; } } public float getTranslationY ( ) { if ( AnimatorProxy . NEEDS_PROXY ) { return mProxy . getTranslationY ( ) ; } else { return super . getTranslationY ( ) ; } } public void setTranslationY ( float translationY ) { if ( AnimatorProxy . NEEDS_PROXY ) { mProxy . setTranslationY ( translationY ) ; } else { super . setTranslationY ( translationY ) ; } } } </s>
|
<s> package com . actionbarsherlock . internal . nineoldandroids . animation ; import java . util . ArrayList ; import android . view . animation . Interpolator ; public abstract class Animator implements Cloneable { ArrayList < AnimatorListener > mListeners = null ; public void start ( ) { } public void cancel ( ) { } public void end ( ) { } public abstract long getStartDelay ( ) ; public abstract void setStartDelay ( long startDelay ) ; public abstract Animator setDuration ( long duration ) ; public abstract long getDuration ( ) ; public abstract void setInterpolator ( Interpolator value ) ; public abstract boolean isRunning ( ) ; public boolean isStarted ( ) { return isRunning ( ) ; } public void addListener ( AnimatorListener listener ) { if ( mListeners == null ) { mListeners = new ArrayList < AnimatorListener > ( ) ; } mListeners . add ( listener ) ; } public void removeListener ( AnimatorListener listener ) { if ( mListeners == null ) { return ; } mListeners . remove ( listener ) ; if ( mListeners . size ( ) == <NUM_LIT:0> ) { mListeners = null ; } } public ArrayList < AnimatorListener > getListeners ( ) { return mListeners ; } public void removeAllListeners ( ) { if ( mListeners != null ) { mListeners . clear ( ) ; mListeners = null ; } } @ Override public Animator clone ( ) { try { final Animator anim = ( Animator ) super . clone ( ) ; if ( mListeners != null ) { ArrayList < AnimatorListener > oldListeners = mListeners ; anim . mListeners = new ArrayList < AnimatorListener > ( ) ; int numListeners = oldListeners . size ( ) ; for ( int i = <NUM_LIT:0> ; i < numListeners ; ++ i ) { anim . mListeners . add ( oldListeners . get ( i ) ) ; } } return anim ; } catch ( CloneNotSupportedException e ) { throw new AssertionError ( ) ; } } public void setupStartValues ( ) { } public void setupEndValues ( ) { } public void setTarget ( Object target ) { } public static interface AnimatorListener { void onAnimationStart ( Animator animation ) ; void onAnimationEnd ( Animator animation ) ; void onAnimationCancel ( Animator animation ) ; void onAnimationRepeat ( Animator animation ) ; } } </s>
|
<s> package com . actionbarsherlock . internal . nineoldandroids . animation ; import android . util . Log ; import java . lang . reflect . InvocationTargetException ; import java . lang . reflect . Method ; import java . util . HashMap ; import java . util . concurrent . locks . ReentrantReadWriteLock ; @ SuppressWarnings ( { "<STR_LIT:rawtypes>" , "<STR_LIT:unchecked>" } ) public class PropertyValuesHolder implements Cloneable { String mPropertyName ; Method mSetter = null ; private Method mGetter = null ; Class mValueType ; KeyframeSet mKeyframeSet = null ; private static final TypeEvaluator sIntEvaluator = new IntEvaluator ( ) ; private static final TypeEvaluator sFloatEvaluator = new FloatEvaluator ( ) ; private static Class [ ] FLOAT_VARIANTS = { float . class , Float . class , double . class , int . class , Double . class , Integer . class } ; private static Class [ ] INTEGER_VARIANTS = { int . class , Integer . class , float . class , double . class , Float . class , Double . class } ; private static Class [ ] DOUBLE_VARIANTS = { double . class , Double . class , float . class , int . class , Float . class , Integer . class } ; private static final HashMap < Class , HashMap < String , Method > > sSetterPropertyMap = new HashMap < Class , HashMap < String , Method > > ( ) ; private static final HashMap < Class , HashMap < String , Method > > sGetterPropertyMap = new HashMap < Class , HashMap < String , Method > > ( ) ; final ReentrantReadWriteLock mPropertyMapLock = new ReentrantReadWriteLock ( ) ; final Object [ ] mTmpValueArray = new Object [ <NUM_LIT:1> ] ; private TypeEvaluator mEvaluator ; private Object mAnimatedValue ; private PropertyValuesHolder ( String propertyName ) { mPropertyName = propertyName ; } public static PropertyValuesHolder ofInt ( String propertyName , int ... values ) { return new IntPropertyValuesHolder ( propertyName , values ) ; } public static PropertyValuesHolder ofFloat ( String propertyName , float ... values ) { return new FloatPropertyValuesHolder ( propertyName , values ) ; } public static PropertyValuesHolder ofObject ( String propertyName , TypeEvaluator evaluator , Object ... values ) { PropertyValuesHolder pvh = new PropertyValuesHolder ( propertyName ) ; pvh . setObjectValues ( values ) ; pvh . setEvaluator ( evaluator ) ; return pvh ; } public static PropertyValuesHolder ofKeyframe ( String propertyName , Keyframe ... values ) { KeyframeSet keyframeSet = KeyframeSet . ofKeyframe ( values ) ; if ( keyframeSet instanceof IntKeyframeSet ) { return new IntPropertyValuesHolder ( propertyName , ( IntKeyframeSet ) keyframeSet ) ; } else if ( keyframeSet instanceof FloatKeyframeSet ) { return new FloatPropertyValuesHolder ( propertyName , ( FloatKeyframeSet ) keyframeSet ) ; } else { PropertyValuesHolder pvh = new PropertyValuesHolder ( propertyName ) ; pvh . mKeyframeSet = keyframeSet ; pvh . mValueType = values [ <NUM_LIT:0> ] . getType ( ) ; return pvh ; } } public void setIntValues ( int ... values ) { mValueType = int . class ; mKeyframeSet = KeyframeSet . ofInt ( values ) ; } public void setFloatValues ( float ... values ) { mValueType = float . class ; mKeyframeSet = KeyframeSet . ofFloat ( values ) ; } public void setKeyframes ( Keyframe ... values ) { int numKeyframes = values . length ; Keyframe keyframes [ ] = new Keyframe [ Math . max ( numKeyframes , <NUM_LIT:2> ) ] ; mValueType = values [ <NUM_LIT:0> ] . getType ( ) ; for ( int i = <NUM_LIT:0> ; i < numKeyframes ; ++ i ) { keyframes [ i ] = values [ i ] ; } mKeyframeSet = new KeyframeSet ( keyframes ) ; } public void setObjectValues ( Object ... values ) { mValueType = values [ <NUM_LIT:0> ] . getClass ( ) ; mKeyframeSet = KeyframeSet . ofObject ( values ) ; } private Method getPropertyFunction ( Class targetClass , String prefix , Class valueType ) { Method returnVal = null ; String methodName = getMethodName ( prefix , mPropertyName ) ; Class args [ ] = null ; if ( valueType == null ) { try { returnVal = targetClass . getMethod ( methodName , args ) ; } catch ( NoSuchMethodException e ) { Log . e ( "<STR_LIT>" , targetClass . getSimpleName ( ) + "<STR_LIT:U+0020-U+0020>" + "<STR_LIT>" + mPropertyName + "<STR_LIT::U+0020>" + e ) ; } } else { args = new Class [ <NUM_LIT:1> ] ; Class typeVariants [ ] ; if ( mValueType . equals ( Float . class ) ) { typeVariants = FLOAT_VARIANTS ; } else if ( mValueType . equals ( Integer . class ) ) { typeVariants = INTEGER_VARIANTS ; } else if ( mValueType . equals ( Double . class ) ) { typeVariants = DOUBLE_VARIANTS ; } else { typeVariants = new Class [ <NUM_LIT:1> ] ; typeVariants [ <NUM_LIT:0> ] = mValueType ; } for ( Class typeVariant : typeVariants ) { args [ <NUM_LIT:0> ] = typeVariant ; try { returnVal = targetClass . getMethod ( methodName , args ) ; mValueType = typeVariant ; return returnVal ; } catch ( NoSuchMethodException e ) { } } Log . e ( "<STR_LIT>" , "<STR_LIT>" + prefix + "<STR_LIT>" + mPropertyName + "<STR_LIT>" + targetClass . getSimpleName ( ) + "<STR_LIT>" + mValueType ) ; } return returnVal ; } private Method setupSetterOrGetter ( Class targetClass , HashMap < Class , HashMap < String , Method > > propertyMapMap , String prefix , Class valueType ) { Method setterOrGetter = null ; try { mPropertyMapLock . writeLock ( ) . lock ( ) ; HashMap < String , Method > propertyMap = propertyMapMap . get ( targetClass ) ; if ( propertyMap != null ) { setterOrGetter = propertyMap . get ( mPropertyName ) ; } if ( setterOrGetter == null ) { setterOrGetter = getPropertyFunction ( targetClass , prefix , valueType ) ; if ( propertyMap == null ) { propertyMap = new HashMap < String , Method > ( ) ; propertyMapMap . put ( targetClass , propertyMap ) ; } propertyMap . put ( mPropertyName , setterOrGetter ) ; } } finally { mPropertyMapLock . writeLock ( ) . unlock ( ) ; } return setterOrGetter ; } void setupSetter ( Class targetClass ) { mSetter = setupSetterOrGetter ( targetClass , sSetterPropertyMap , "<STR_LIT>" , mValueType ) ; } private void setupGetter ( Class targetClass ) { mGetter = setupSetterOrGetter ( targetClass , sGetterPropertyMap , "<STR_LIT:get>" , null ) ; } void setupSetterAndGetter ( Object target ) { Class targetClass = target . getClass ( ) ; if ( mSetter == null ) { setupSetter ( targetClass ) ; } for ( Keyframe kf : mKeyframeSet . mKeyframes ) { if ( ! kf . hasValue ( ) ) { if ( mGetter == null ) { setupGetter ( targetClass ) ; } try { kf . setValue ( mGetter . invoke ( target ) ) ; } catch ( InvocationTargetException e ) { Log . e ( "<STR_LIT>" , e . toString ( ) ) ; } catch ( IllegalAccessException e ) { Log . e ( "<STR_LIT>" , e . toString ( ) ) ; } } } } private void setupValue ( Object target , Keyframe kf ) { try { if ( mGetter == null ) { Class targetClass = target . getClass ( ) ; setupGetter ( targetClass ) ; } kf . setValue ( mGetter . invoke ( target ) ) ; } catch ( InvocationTargetException e ) { Log . e ( "<STR_LIT>" , e . toString ( ) ) ; } catch ( IllegalAccessException e ) { Log . e ( "<STR_LIT>" , e . toString ( ) ) ; } } void setupStartValue ( Object target ) { setupValue ( target , mKeyframeSet . mKeyframes . get ( <NUM_LIT:0> ) ) ; } void setupEndValue ( Object target ) { setupValue ( target , mKeyframeSet . mKeyframes . get ( mKeyframeSet . mKeyframes . size ( ) - <NUM_LIT:1> ) ) ; } @ Override public PropertyValuesHolder clone ( ) { try { PropertyValuesHolder newPVH = ( PropertyValuesHolder ) super . clone ( ) ; newPVH . mPropertyName = mPropertyName ; newPVH . mKeyframeSet = mKeyframeSet . clone ( ) ; newPVH . mEvaluator = mEvaluator ; return newPVH ; } catch ( CloneNotSupportedException e ) { return null ; } } void setAnimatedValue ( Object target ) { if ( mSetter != null ) { try { mTmpValueArray [ <NUM_LIT:0> ] = getAnimatedValue ( ) ; mSetter . invoke ( target , mTmpValueArray ) ; } catch ( InvocationTargetException e ) { Log . e ( "<STR_LIT>" , e . toString ( ) ) ; } catch ( IllegalAccessException e ) { Log . e ( "<STR_LIT>" , e . toString ( ) ) ; } } } void init ( ) { if ( mEvaluator == null ) { mEvaluator = ( mValueType == Integer . class ) ? sIntEvaluator : ( mValueType == Float . class ) ? sFloatEvaluator : null ; } if ( mEvaluator != null ) { mKeyframeSet . setEvaluator ( mEvaluator ) ; } } public void setEvaluator ( TypeEvaluator evaluator ) { mEvaluator = evaluator ; mKeyframeSet . setEvaluator ( evaluator ) ; } void calculateValue ( float fraction ) { mAnimatedValue = mKeyframeSet . getValue ( fraction ) ; } public void setPropertyName ( String propertyName ) { mPropertyName = propertyName ; } public String getPropertyName ( ) { return mPropertyName ; } Object getAnimatedValue ( ) { return mAnimatedValue ; } @ Override public String toString ( ) { return mPropertyName + "<STR_LIT::U+0020>" + mKeyframeSet . toString ( ) ; } static String getMethodName ( String prefix , String propertyName ) { if ( propertyName == null || propertyName . length ( ) == <NUM_LIT:0> ) { return prefix ; } char firstLetter = Character . toUpperCase ( propertyName . charAt ( <NUM_LIT:0> ) ) ; String theRest = propertyName . substring ( <NUM_LIT:1> ) ; return prefix + firstLetter + theRest ; } static class IntPropertyValuesHolder extends PropertyValuesHolder { IntKeyframeSet mIntKeyframeSet ; int mIntAnimatedValue ; public IntPropertyValuesHolder ( String propertyName , IntKeyframeSet keyframeSet ) { super ( propertyName ) ; mValueType = int . class ; mKeyframeSet = keyframeSet ; mIntKeyframeSet = ( IntKeyframeSet ) mKeyframeSet ; } public IntPropertyValuesHolder ( String propertyName , int ... values ) { super ( propertyName ) ; setIntValues ( values ) ; } @ Override public void setIntValues ( int ... values ) { super . setIntValues ( values ) ; mIntKeyframeSet = ( IntKeyframeSet ) mKeyframeSet ; } @ Override void calculateValue ( float fraction ) { mIntAnimatedValue = mIntKeyframeSet . getIntValue ( fraction ) ; } @ Override Object getAnimatedValue ( ) { return mIntAnimatedValue ; } @ Override public IntPropertyValuesHolder clone ( ) { IntPropertyValuesHolder newPVH = ( IntPropertyValuesHolder ) super . clone ( ) ; newPVH . mIntKeyframeSet = ( IntKeyframeSet ) newPVH . mKeyframeSet ; return newPVH ; } @ Override void setAnimatedValue ( Object target ) { if ( mSetter != null ) { try { mTmpValueArray [ <NUM_LIT:0> ] = mIntAnimatedValue ; mSetter . invoke ( target , mTmpValueArray ) ; } catch ( InvocationTargetException e ) { Log . e ( "<STR_LIT>" , e . toString ( ) ) ; } catch ( IllegalAccessException e ) { Log . e ( "<STR_LIT>" , e . toString ( ) ) ; } } } @ Override void setupSetter ( Class targetClass ) { super . setupSetter ( targetClass ) ; } } static class FloatPropertyValuesHolder extends PropertyValuesHolder { FloatKeyframeSet mFloatKeyframeSet ; float mFloatAnimatedValue ; public FloatPropertyValuesHolder ( String propertyName , FloatKeyframeSet keyframeSet ) { super ( propertyName ) ; mValueType = float . class ; mKeyframeSet = keyframeSet ; mFloatKeyframeSet = ( FloatKeyframeSet ) mKeyframeSet ; } public FloatPropertyValuesHolder ( String propertyName , float ... values ) { super ( propertyName ) ; setFloatValues ( values ) ; } @ Override public void setFloatValues ( float ... values ) { super . setFloatValues ( values ) ; mFloatKeyframeSet = ( FloatKeyframeSet ) mKeyframeSet ; } @ Override void calculateValue ( float fraction ) { mFloatAnimatedValue = mFloatKeyframeSet . getFloatValue ( fraction ) ; } @ Override Object getAnimatedValue ( ) { return mFloatAnimatedValue ; } @ Override public FloatPropertyValuesHolder clone ( ) { FloatPropertyValuesHolder newPVH = ( FloatPropertyValuesHolder ) super . clone ( ) ; newPVH . mFloatKeyframeSet = ( FloatKeyframeSet ) newPVH . mKeyframeSet ; return newPVH ; } @ Override void setAnimatedValue ( Object target ) { if ( mSetter != null ) { try { mTmpValueArray [ <NUM_LIT:0> ] = mFloatAnimatedValue ; mSetter . invoke ( target , mTmpValueArray ) ; } catch ( InvocationTargetException e ) { Log . e ( "<STR_LIT>" , e . toString ( ) ) ; } catch ( IllegalAccessException e ) { Log . e ( "<STR_LIT>" , e . toString ( ) ) ; } } } @ Override void setupSetter ( Class targetClass ) { super . setupSetter ( targetClass ) ; } } } </s>
|
<s> package com . actionbarsherlock . internal . nineoldandroids . animation ; import java . util . ArrayList ; import java . util . Arrays ; import android . view . animation . Interpolator ; import com . actionbarsherlock . internal . nineoldandroids . animation . Keyframe . FloatKeyframe ; import com . actionbarsherlock . internal . nineoldandroids . animation . Keyframe . IntKeyframe ; import com . actionbarsherlock . internal . nineoldandroids . animation . Keyframe . ObjectKeyframe ; @ SuppressWarnings ( { "<STR_LIT:rawtypes>" , "<STR_LIT:unchecked>" } ) class KeyframeSet { int mNumKeyframes ; Keyframe mFirstKeyframe ; Keyframe mLastKeyframe ; Interpolator mInterpolator ; ArrayList < Keyframe > mKeyframes ; TypeEvaluator mEvaluator ; public KeyframeSet ( Keyframe ... keyframes ) { mNumKeyframes = keyframes . length ; mKeyframes = new ArrayList < Keyframe > ( ) ; mKeyframes . addAll ( Arrays . asList ( keyframes ) ) ; mFirstKeyframe = mKeyframes . get ( <NUM_LIT:0> ) ; mLastKeyframe = mKeyframes . get ( mNumKeyframes - <NUM_LIT:1> ) ; mInterpolator = mLastKeyframe . getInterpolator ( ) ; } public static KeyframeSet ofInt ( int ... values ) { int numKeyframes = values . length ; IntKeyframe keyframes [ ] = new IntKeyframe [ Math . max ( numKeyframes , <NUM_LIT:2> ) ] ; if ( numKeyframes == <NUM_LIT:1> ) { keyframes [ <NUM_LIT:0> ] = ( IntKeyframe ) Keyframe . ofInt ( <NUM_LIT> ) ; keyframes [ <NUM_LIT:1> ] = ( IntKeyframe ) Keyframe . ofInt ( <NUM_LIT> , values [ <NUM_LIT:0> ] ) ; } else { keyframes [ <NUM_LIT:0> ] = ( IntKeyframe ) Keyframe . ofInt ( <NUM_LIT> , values [ <NUM_LIT:0> ] ) ; for ( int i = <NUM_LIT:1> ; i < numKeyframes ; ++ i ) { keyframes [ i ] = ( IntKeyframe ) Keyframe . ofInt ( ( float ) i / ( numKeyframes - <NUM_LIT:1> ) , values [ i ] ) ; } } return new IntKeyframeSet ( keyframes ) ; } public static KeyframeSet ofFloat ( float ... values ) { int numKeyframes = values . length ; FloatKeyframe keyframes [ ] = new FloatKeyframe [ Math . max ( numKeyframes , <NUM_LIT:2> ) ] ; if ( numKeyframes == <NUM_LIT:1> ) { keyframes [ <NUM_LIT:0> ] = ( FloatKeyframe ) Keyframe . ofFloat ( <NUM_LIT> ) ; keyframes [ <NUM_LIT:1> ] = ( FloatKeyframe ) Keyframe . ofFloat ( <NUM_LIT> , values [ <NUM_LIT:0> ] ) ; } else { keyframes [ <NUM_LIT:0> ] = ( FloatKeyframe ) Keyframe . ofFloat ( <NUM_LIT> , values [ <NUM_LIT:0> ] ) ; for ( int i = <NUM_LIT:1> ; i < numKeyframes ; ++ i ) { keyframes [ i ] = ( FloatKeyframe ) Keyframe . ofFloat ( ( float ) i / ( numKeyframes - <NUM_LIT:1> ) , values [ i ] ) ; } } return new FloatKeyframeSet ( keyframes ) ; } public static KeyframeSet ofKeyframe ( Keyframe ... keyframes ) { int numKeyframes = keyframes . length ; boolean hasFloat = false ; boolean hasInt = false ; boolean hasOther = false ; for ( int i = <NUM_LIT:0> ; i < numKeyframes ; ++ i ) { if ( keyframes [ i ] instanceof FloatKeyframe ) { hasFloat = true ; } else if ( keyframes [ i ] instanceof IntKeyframe ) { hasInt = true ; } else { hasOther = true ; } } if ( hasFloat && ! hasInt && ! hasOther ) { FloatKeyframe floatKeyframes [ ] = new FloatKeyframe [ numKeyframes ] ; for ( int i = <NUM_LIT:0> ; i < numKeyframes ; ++ i ) { floatKeyframes [ i ] = ( FloatKeyframe ) keyframes [ i ] ; } return new FloatKeyframeSet ( floatKeyframes ) ; } else if ( hasInt && ! hasFloat && ! hasOther ) { IntKeyframe intKeyframes [ ] = new IntKeyframe [ numKeyframes ] ; for ( int i = <NUM_LIT:0> ; i < numKeyframes ; ++ i ) { intKeyframes [ i ] = ( IntKeyframe ) keyframes [ i ] ; } return new IntKeyframeSet ( intKeyframes ) ; } else { return new KeyframeSet ( keyframes ) ; } } public static KeyframeSet ofObject ( Object ... values ) { int numKeyframes = values . length ; ObjectKeyframe keyframes [ ] = new ObjectKeyframe [ Math . max ( numKeyframes , <NUM_LIT:2> ) ] ; if ( numKeyframes == <NUM_LIT:1> ) { keyframes [ <NUM_LIT:0> ] = ( ObjectKeyframe ) Keyframe . ofObject ( <NUM_LIT> ) ; keyframes [ <NUM_LIT:1> ] = ( ObjectKeyframe ) Keyframe . ofObject ( <NUM_LIT> , values [ <NUM_LIT:0> ] ) ; } else { keyframes [ <NUM_LIT:0> ] = ( ObjectKeyframe ) Keyframe . ofObject ( <NUM_LIT> , values [ <NUM_LIT:0> ] ) ; for ( int i = <NUM_LIT:1> ; i < numKeyframes ; ++ i ) { keyframes [ i ] = ( ObjectKeyframe ) Keyframe . ofObject ( ( float ) i / ( numKeyframes - <NUM_LIT:1> ) , values [ i ] ) ; } } return new KeyframeSet ( keyframes ) ; } public void setEvaluator ( TypeEvaluator evaluator ) { mEvaluator = evaluator ; } @ Override public KeyframeSet clone ( ) { ArrayList < Keyframe > keyframes = mKeyframes ; int numKeyframes = mKeyframes . size ( ) ; Keyframe [ ] newKeyframes = new Keyframe [ numKeyframes ] ; for ( int i = <NUM_LIT:0> ; i < numKeyframes ; ++ i ) { newKeyframes [ i ] = keyframes . get ( i ) . clone ( ) ; } KeyframeSet newSet = new KeyframeSet ( newKeyframes ) ; return newSet ; } public Object getValue ( float fraction ) { if ( mNumKeyframes == <NUM_LIT:2> ) { if ( mInterpolator != null ) { fraction = mInterpolator . getInterpolation ( fraction ) ; } return mEvaluator . evaluate ( fraction , mFirstKeyframe . getValue ( ) , mLastKeyframe . getValue ( ) ) ; } if ( fraction <= <NUM_LIT> ) { final Keyframe nextKeyframe = mKeyframes . get ( <NUM_LIT:1> ) ; final Interpolator interpolator = nextKeyframe . getInterpolator ( ) ; if ( interpolator != null ) { fraction = interpolator . getInterpolation ( fraction ) ; } final float prevFraction = mFirstKeyframe . getFraction ( ) ; float intervalFraction = ( fraction - prevFraction ) / ( nextKeyframe . getFraction ( ) - prevFraction ) ; return mEvaluator . evaluate ( intervalFraction , mFirstKeyframe . getValue ( ) , nextKeyframe . getValue ( ) ) ; } else if ( fraction >= <NUM_LIT> ) { final Keyframe prevKeyframe = mKeyframes . get ( mNumKeyframes - <NUM_LIT:2> ) ; final Interpolator interpolator = mLastKeyframe . getInterpolator ( ) ; if ( interpolator != null ) { fraction = interpolator . getInterpolation ( fraction ) ; } final float prevFraction = prevKeyframe . getFraction ( ) ; float intervalFraction = ( fraction - prevFraction ) / ( mLastKeyframe . getFraction ( ) - prevFraction ) ; return mEvaluator . evaluate ( intervalFraction , prevKeyframe . getValue ( ) , mLastKeyframe . getValue ( ) ) ; } Keyframe prevKeyframe = mFirstKeyframe ; for ( int i = <NUM_LIT:1> ; i < mNumKeyframes ; ++ i ) { Keyframe nextKeyframe = mKeyframes . get ( i ) ; if ( fraction < nextKeyframe . getFraction ( ) ) { final Interpolator interpolator = nextKeyframe . getInterpolator ( ) ; if ( interpolator != null ) { fraction = interpolator . getInterpolation ( fraction ) ; } final float prevFraction = prevKeyframe . getFraction ( ) ; float intervalFraction = ( fraction - prevFraction ) / ( nextKeyframe . getFraction ( ) - prevFraction ) ; return mEvaluator . evaluate ( intervalFraction , prevKeyframe . getValue ( ) , nextKeyframe . getValue ( ) ) ; } prevKeyframe = nextKeyframe ; } return mLastKeyframe . getValue ( ) ; } @ Override public String toString ( ) { String returnVal = "<STR_LIT:U+0020>" ; for ( int i = <NUM_LIT:0> ; i < mNumKeyframes ; ++ i ) { returnVal += mKeyframes . get ( i ) . getValue ( ) + "<STR_LIT:U+0020U+0020>" ; } return returnVal ; } } </s>
|
<s> package com . actionbarsherlock . internal . nineoldandroids . animation ; public class IntEvaluator implements TypeEvaluator < Integer > { public Integer evaluate ( float fraction , Integer startValue , Integer endValue ) { int startInt = startValue ; return ( int ) ( startInt + fraction * ( endValue - startInt ) ) ; } } </s>
|
<s> package com . actionbarsherlock . internal . nineoldandroids . animation ; import java . util . ArrayList ; import android . view . animation . Interpolator ; import com . actionbarsherlock . internal . nineoldandroids . animation . Keyframe . IntKeyframe ; @ SuppressWarnings ( "<STR_LIT:unchecked>" ) class IntKeyframeSet extends KeyframeSet { private int firstValue ; private int lastValue ; private int deltaValue ; private boolean firstTime = true ; public IntKeyframeSet ( IntKeyframe ... keyframes ) { super ( keyframes ) ; } @ Override public Object getValue ( float fraction ) { return getIntValue ( fraction ) ; } @ Override public IntKeyframeSet clone ( ) { ArrayList < Keyframe > keyframes = mKeyframes ; int numKeyframes = mKeyframes . size ( ) ; IntKeyframe [ ] newKeyframes = new IntKeyframe [ numKeyframes ] ; for ( int i = <NUM_LIT:0> ; i < numKeyframes ; ++ i ) { newKeyframes [ i ] = ( IntKeyframe ) keyframes . get ( i ) . clone ( ) ; } IntKeyframeSet newSet = new IntKeyframeSet ( newKeyframes ) ; return newSet ; } public int getIntValue ( float fraction ) { if ( mNumKeyframes == <NUM_LIT:2> ) { if ( firstTime ) { firstTime = false ; firstValue = ( ( IntKeyframe ) mKeyframes . get ( <NUM_LIT:0> ) ) . getIntValue ( ) ; lastValue = ( ( IntKeyframe ) mKeyframes . get ( <NUM_LIT:1> ) ) . getIntValue ( ) ; deltaValue = lastValue - firstValue ; } if ( mInterpolator != null ) { fraction = mInterpolator . getInterpolation ( fraction ) ; } if ( mEvaluator == null ) { return firstValue + ( int ) ( fraction * deltaValue ) ; } else { return ( ( Number ) mEvaluator . evaluate ( fraction , firstValue , lastValue ) ) . intValue ( ) ; } } if ( fraction <= <NUM_LIT> ) { final IntKeyframe prevKeyframe = ( IntKeyframe ) mKeyframes . get ( <NUM_LIT:0> ) ; final IntKeyframe nextKeyframe = ( IntKeyframe ) mKeyframes . get ( <NUM_LIT:1> ) ; int prevValue = prevKeyframe . getIntValue ( ) ; int nextValue = nextKeyframe . getIntValue ( ) ; float prevFraction = prevKeyframe . getFraction ( ) ; float nextFraction = nextKeyframe . getFraction ( ) ; final Interpolator interpolator = nextKeyframe . getInterpolator ( ) ; if ( interpolator != null ) { fraction = interpolator . getInterpolation ( fraction ) ; } float intervalFraction = ( fraction - prevFraction ) / ( nextFraction - prevFraction ) ; return mEvaluator == null ? prevValue + ( int ) ( intervalFraction * ( nextValue - prevValue ) ) : ( ( Number ) mEvaluator . evaluate ( intervalFraction , prevValue , nextValue ) ) . intValue ( ) ; } else if ( fraction >= <NUM_LIT> ) { final IntKeyframe prevKeyframe = ( IntKeyframe ) mKeyframes . get ( mNumKeyframes - <NUM_LIT:2> ) ; final IntKeyframe nextKeyframe = ( IntKeyframe ) mKeyframes . get ( mNumKeyframes - <NUM_LIT:1> ) ; int prevValue = prevKeyframe . getIntValue ( ) ; int nextValue = nextKeyframe . getIntValue ( ) ; float prevFraction = prevKeyframe . getFraction ( ) ; float nextFraction = nextKeyframe . getFraction ( ) ; final Interpolator interpolator = nextKeyframe . getInterpolator ( ) ; if ( interpolator != null ) { fraction = interpolator . getInterpolation ( fraction ) ; } float intervalFraction = ( fraction - prevFraction ) / ( nextFraction - prevFraction ) ; return mEvaluator == null ? prevValue + ( int ) ( intervalFraction * ( nextValue - prevValue ) ) : ( ( Number ) mEvaluator . evaluate ( intervalFraction , prevValue , nextValue ) ) . intValue ( ) ; } IntKeyframe prevKeyframe = ( IntKeyframe ) mKeyframes . get ( <NUM_LIT:0> ) ; for ( int i = <NUM_LIT:1> ; i < mNumKeyframes ; ++ i ) { IntKeyframe nextKeyframe = ( IntKeyframe ) mKeyframes . get ( i ) ; if ( fraction < nextKeyframe . getFraction ( ) ) { final Interpolator interpolator = nextKeyframe . getInterpolator ( ) ; if ( interpolator != null ) { fraction = interpolator . getInterpolation ( fraction ) ; } float intervalFraction = ( fraction - prevKeyframe . getFraction ( ) ) / ( nextKeyframe . getFraction ( ) - prevKeyframe . getFraction ( ) ) ; int prevValue = prevKeyframe . getIntValue ( ) ; int nextValue = nextKeyframe . getIntValue ( ) ; return mEvaluator == null ? prevValue + ( int ) ( intervalFraction * ( nextValue - prevValue ) ) : ( ( Number ) mEvaluator . evaluate ( intervalFraction , prevValue , nextValue ) ) . intValue ( ) ; } prevKeyframe = nextKeyframe ; } return ( ( Number ) mKeyframes . get ( mNumKeyframes - <NUM_LIT:1> ) . getValue ( ) ) . intValue ( ) ; } } </s>
|
<s> package com . actionbarsherlock . internal . nineoldandroids . animation ; public abstract class AnimatorListenerAdapter implements Animator . AnimatorListener { @ Override public void onAnimationCancel ( Animator animation ) { } @ Override public void onAnimationEnd ( Animator animation ) { } @ Override public void onAnimationRepeat ( Animator animation ) { } @ Override public void onAnimationStart ( Animator animation ) { } } </s>
|
<s> package com . actionbarsherlock . internal . nineoldandroids . animation ; import android . os . Handler ; import android . os . Looper ; import android . os . Message ; import android . util . AndroidRuntimeException ; import android . view . animation . AccelerateDecelerateInterpolator ; import android . view . animation . AnimationUtils ; import android . view . animation . Interpolator ; import android . view . animation . LinearInterpolator ; import java . util . ArrayList ; import java . util . HashMap ; @ SuppressWarnings ( { "<STR_LIT:rawtypes>" , "<STR_LIT:unchecked>" } ) public class ValueAnimator extends Animator { private static final long DEFAULT_FRAME_DELAY = <NUM_LIT:10> ; static final int ANIMATION_START = <NUM_LIT:0> ; static final int ANIMATION_FRAME = <NUM_LIT:1> ; static final int STOPPED = <NUM_LIT:0> ; static final int RUNNING = <NUM_LIT:1> ; static final int SEEKED = <NUM_LIT:2> ; long mStartTime ; long mSeekTime = - <NUM_LIT:1> ; private static ThreadLocal < AnimationHandler > sAnimationHandler = new ThreadLocal < AnimationHandler > ( ) ; private static final ThreadLocal < ArrayList < ValueAnimator > > sAnimations = new ThreadLocal < ArrayList < ValueAnimator > > ( ) { @ Override protected ArrayList < ValueAnimator > initialValue ( ) { return new ArrayList < ValueAnimator > ( ) ; } } ; private static final ThreadLocal < ArrayList < ValueAnimator > > sPendingAnimations = new ThreadLocal < ArrayList < ValueAnimator > > ( ) { @ Override protected ArrayList < ValueAnimator > initialValue ( ) { return new ArrayList < ValueAnimator > ( ) ; } } ; private static final ThreadLocal < ArrayList < ValueAnimator > > sDelayedAnims = new ThreadLocal < ArrayList < ValueAnimator > > ( ) { @ Override protected ArrayList < ValueAnimator > initialValue ( ) { return new ArrayList < ValueAnimator > ( ) ; } } ; private static final ThreadLocal < ArrayList < ValueAnimator > > sEndingAnims = new ThreadLocal < ArrayList < ValueAnimator > > ( ) { @ Override protected ArrayList < ValueAnimator > initialValue ( ) { return new ArrayList < ValueAnimator > ( ) ; } } ; private static final ThreadLocal < ArrayList < ValueAnimator > > sReadyAnims = new ThreadLocal < ArrayList < ValueAnimator > > ( ) { @ Override protected ArrayList < ValueAnimator > initialValue ( ) { return new ArrayList < ValueAnimator > ( ) ; } } ; private static final Interpolator sDefaultInterpolator = new AccelerateDecelerateInterpolator ( ) ; private boolean mPlayingBackwards = false ; private int mCurrentIteration = <NUM_LIT:0> ; private float mCurrentFraction = <NUM_LIT> ; private boolean mStartedDelay = false ; private long mDelayStartTime ; int mPlayingState = STOPPED ; private boolean mRunning = false ; private boolean mStarted = false ; boolean mInitialized = false ; private long mDuration = <NUM_LIT> ; private long mStartDelay = <NUM_LIT:0> ; private static long sFrameDelay = DEFAULT_FRAME_DELAY ; private int mRepeatCount = <NUM_LIT:0> ; private int mRepeatMode = RESTART ; private Interpolator mInterpolator = sDefaultInterpolator ; private ArrayList < AnimatorUpdateListener > mUpdateListeners = null ; PropertyValuesHolder [ ] mValues ; HashMap < String , PropertyValuesHolder > mValuesMap ; public static final int RESTART = <NUM_LIT:1> ; public static final int REVERSE = <NUM_LIT:2> ; public static final int INFINITE = - <NUM_LIT:1> ; public ValueAnimator ( ) { } public static ValueAnimator ofInt ( int ... values ) { ValueAnimator anim = new ValueAnimator ( ) ; anim . setIntValues ( values ) ; return anim ; } public static ValueAnimator ofFloat ( float ... values ) { ValueAnimator anim = new ValueAnimator ( ) ; anim . setFloatValues ( values ) ; return anim ; } public static ValueAnimator ofPropertyValuesHolder ( PropertyValuesHolder ... values ) { ValueAnimator anim = new ValueAnimator ( ) ; anim . setValues ( values ) ; return anim ; } public static ValueAnimator ofObject ( TypeEvaluator evaluator , Object ... values ) { ValueAnimator anim = new ValueAnimator ( ) ; anim . setObjectValues ( values ) ; anim . setEvaluator ( evaluator ) ; return anim ; } public void setIntValues ( int ... values ) { if ( values == null || values . length == <NUM_LIT:0> ) { return ; } if ( mValues == null || mValues . length == <NUM_LIT:0> ) { setValues ( new PropertyValuesHolder [ ] { PropertyValuesHolder . ofInt ( "<STR_LIT>" , values ) } ) ; } else { PropertyValuesHolder valuesHolder = mValues [ <NUM_LIT:0> ] ; valuesHolder . setIntValues ( values ) ; } mInitialized = false ; } public void setFloatValues ( float ... values ) { if ( values == null || values . length == <NUM_LIT:0> ) { return ; } if ( mValues == null || mValues . length == <NUM_LIT:0> ) { setValues ( new PropertyValuesHolder [ ] { PropertyValuesHolder . ofFloat ( "<STR_LIT>" , values ) } ) ; } else { PropertyValuesHolder valuesHolder = mValues [ <NUM_LIT:0> ] ; valuesHolder . setFloatValues ( values ) ; } mInitialized = false ; } public void setObjectValues ( Object ... values ) { if ( values == null || values . length == <NUM_LIT:0> ) { return ; } if ( mValues == null || mValues . length == <NUM_LIT:0> ) { setValues ( new PropertyValuesHolder [ ] { PropertyValuesHolder . ofObject ( "<STR_LIT>" , ( TypeEvaluator ) null , values ) } ) ; } else { PropertyValuesHolder valuesHolder = mValues [ <NUM_LIT:0> ] ; valuesHolder . setObjectValues ( values ) ; } mInitialized = false ; } public void setValues ( PropertyValuesHolder ... values ) { int numValues = values . length ; mValues = values ; mValuesMap = new HashMap < String , PropertyValuesHolder > ( numValues ) ; for ( int i = <NUM_LIT:0> ; i < numValues ; ++ i ) { PropertyValuesHolder valuesHolder = values [ i ] ; mValuesMap . put ( valuesHolder . getPropertyName ( ) , valuesHolder ) ; } mInitialized = false ; } public PropertyValuesHolder [ ] getValues ( ) { return mValues ; } void initAnimation ( ) { if ( ! mInitialized ) { int numValues = mValues . length ; for ( int i = <NUM_LIT:0> ; i < numValues ; ++ i ) { mValues [ i ] . init ( ) ; } mInitialized = true ; } } public ValueAnimator setDuration ( long duration ) { if ( duration < <NUM_LIT:0> ) { throw new IllegalArgumentException ( "<STR_LIT>" + duration ) ; } mDuration = duration ; return this ; } public long getDuration ( ) { return mDuration ; } public void setCurrentPlayTime ( long playTime ) { initAnimation ( ) ; long currentTime = AnimationUtils . currentAnimationTimeMillis ( ) ; if ( mPlayingState != RUNNING ) { mSeekTime = playTime ; mPlayingState = SEEKED ; } mStartTime = currentTime - playTime ; animationFrame ( currentTime ) ; } public long getCurrentPlayTime ( ) { if ( ! mInitialized || mPlayingState == STOPPED ) { return <NUM_LIT:0> ; } return AnimationUtils . currentAnimationTimeMillis ( ) - mStartTime ; } private static class AnimationHandler extends Handler { @ Override public void handleMessage ( Message msg ) { boolean callAgain = true ; ArrayList < ValueAnimator > animations = sAnimations . get ( ) ; ArrayList < ValueAnimator > delayedAnims = sDelayedAnims . get ( ) ; switch ( msg . what ) { case ANIMATION_START : ArrayList < ValueAnimator > pendingAnimations = sPendingAnimations . get ( ) ; if ( animations . size ( ) > <NUM_LIT:0> || delayedAnims . size ( ) > <NUM_LIT:0> ) { callAgain = false ; } while ( pendingAnimations . size ( ) > <NUM_LIT:0> ) { ArrayList < ValueAnimator > pendingCopy = ( ArrayList < ValueAnimator > ) pendingAnimations . clone ( ) ; pendingAnimations . clear ( ) ; int count = pendingCopy . size ( ) ; for ( int i = <NUM_LIT:0> ; i < count ; ++ i ) { ValueAnimator anim = pendingCopy . get ( i ) ; if ( anim . mStartDelay == <NUM_LIT:0> ) { anim . startAnimation ( ) ; } else { delayedAnims . add ( anim ) ; } } } case ANIMATION_FRAME : long currentTime = AnimationUtils . currentAnimationTimeMillis ( ) ; ArrayList < ValueAnimator > readyAnims = sReadyAnims . get ( ) ; ArrayList < ValueAnimator > endingAnims = sEndingAnims . get ( ) ; int numDelayedAnims = delayedAnims . size ( ) ; for ( int i = <NUM_LIT:0> ; i < numDelayedAnims ; ++ i ) { ValueAnimator anim = delayedAnims . get ( i ) ; if ( anim . delayedAnimationFrame ( currentTime ) ) { readyAnims . add ( anim ) ; } } int numReadyAnims = readyAnims . size ( ) ; if ( numReadyAnims > <NUM_LIT:0> ) { for ( int i = <NUM_LIT:0> ; i < numReadyAnims ; ++ i ) { ValueAnimator anim = readyAnims . get ( i ) ; anim . startAnimation ( ) ; anim . mRunning = true ; delayedAnims . remove ( anim ) ; } readyAnims . clear ( ) ; } int numAnims = animations . size ( ) ; int i = <NUM_LIT:0> ; while ( i < numAnims ) { ValueAnimator anim = animations . get ( i ) ; if ( anim . animationFrame ( currentTime ) ) { endingAnims . add ( anim ) ; } if ( animations . size ( ) == numAnims ) { ++ i ; } else { -- numAnims ; endingAnims . remove ( anim ) ; } } if ( endingAnims . size ( ) > <NUM_LIT:0> ) { for ( i = <NUM_LIT:0> ; i < endingAnims . size ( ) ; ++ i ) { endingAnims . get ( i ) . endAnimation ( ) ; } endingAnims . clear ( ) ; } if ( callAgain && ( ! animations . isEmpty ( ) || ! delayedAnims . isEmpty ( ) ) ) { sendEmptyMessageDelayed ( ANIMATION_FRAME , Math . max ( <NUM_LIT:0> , sFrameDelay - ( AnimationUtils . currentAnimationTimeMillis ( ) - currentTime ) ) ) ; } break ; } } } public long getStartDelay ( ) { return mStartDelay ; } public void setStartDelay ( long startDelay ) { this . mStartDelay = startDelay ; } public static long getFrameDelay ( ) { return sFrameDelay ; } public static void setFrameDelay ( long frameDelay ) { sFrameDelay = frameDelay ; } public Object getAnimatedValue ( ) { if ( mValues != null && mValues . length > <NUM_LIT:0> ) { return mValues [ <NUM_LIT:0> ] . getAnimatedValue ( ) ; } return null ; } public Object getAnimatedValue ( String propertyName ) { PropertyValuesHolder valuesHolder = mValuesMap . get ( propertyName ) ; if ( valuesHolder != null ) { return valuesHolder . getAnimatedValue ( ) ; } else { return null ; } } public void setRepeatCount ( int value ) { mRepeatCount = value ; } public int getRepeatCount ( ) { return mRepeatCount ; } public void setRepeatMode ( int value ) { mRepeatMode = value ; } public int getRepeatMode ( ) { return mRepeatMode ; } public void addUpdateListener ( AnimatorUpdateListener listener ) { if ( mUpdateListeners == null ) { mUpdateListeners = new ArrayList < AnimatorUpdateListener > ( ) ; } mUpdateListeners . add ( listener ) ; } public void removeAllUpdateListeners ( ) { if ( mUpdateListeners == null ) { return ; } mUpdateListeners . clear ( ) ; mUpdateListeners = null ; } public void removeUpdateListener ( AnimatorUpdateListener listener ) { if ( mUpdateListeners == null ) { return ; } mUpdateListeners . remove ( listener ) ; if ( mUpdateListeners . size ( ) == <NUM_LIT:0> ) { mUpdateListeners = null ; } } @ Override public void setInterpolator ( Interpolator value ) { if ( value != null ) { mInterpolator = value ; } else { mInterpolator = new LinearInterpolator ( ) ; } } public Interpolator getInterpolator ( ) { return mInterpolator ; } public void setEvaluator ( TypeEvaluator value ) { if ( value != null && mValues != null && mValues . length > <NUM_LIT:0> ) { mValues [ <NUM_LIT:0> ] . setEvaluator ( value ) ; } } private void start ( boolean playBackwards ) { if ( Looper . myLooper ( ) == null ) { throw new AndroidRuntimeException ( "<STR_LIT>" ) ; } mPlayingBackwards = playBackwards ; mCurrentIteration = <NUM_LIT:0> ; mPlayingState = STOPPED ; mStarted = true ; mStartedDelay = false ; sPendingAnimations . get ( ) . add ( this ) ; if ( mStartDelay == <NUM_LIT:0> ) { setCurrentPlayTime ( getCurrentPlayTime ( ) ) ; mPlayingState = STOPPED ; mRunning = true ; if ( mListeners != null ) { ArrayList < AnimatorListener > tmpListeners = ( ArrayList < AnimatorListener > ) mListeners . clone ( ) ; int numListeners = tmpListeners . size ( ) ; for ( int i = <NUM_LIT:0> ; i < numListeners ; ++ i ) { tmpListeners . get ( i ) . onAnimationStart ( this ) ; } } } AnimationHandler animationHandler = sAnimationHandler . get ( ) ; if ( animationHandler == null ) { animationHandler = new AnimationHandler ( ) ; sAnimationHandler . set ( animationHandler ) ; } animationHandler . sendEmptyMessage ( ANIMATION_START ) ; } @ Override public void start ( ) { start ( false ) ; } @ Override public void cancel ( ) { if ( mPlayingState != STOPPED || sPendingAnimations . get ( ) . contains ( this ) || sDelayedAnims . get ( ) . contains ( this ) ) { if ( mRunning && mListeners != null ) { ArrayList < AnimatorListener > tmpListeners = ( ArrayList < AnimatorListener > ) mListeners . clone ( ) ; for ( AnimatorListener listener : tmpListeners ) { listener . onAnimationCancel ( this ) ; } } endAnimation ( ) ; } } @ Override public void end ( ) { if ( ! sAnimations . get ( ) . contains ( this ) && ! sPendingAnimations . get ( ) . contains ( this ) ) { mStartedDelay = false ; startAnimation ( ) ; } else if ( ! mInitialized ) { initAnimation ( ) ; } if ( mRepeatCount > <NUM_LIT:0> && ( mRepeatCount & <NUM_LIT> ) == <NUM_LIT:1> ) { animateValue ( <NUM_LIT> ) ; } else { animateValue ( <NUM_LIT> ) ; } endAnimation ( ) ; } @ Override public boolean isRunning ( ) { return ( mPlayingState == RUNNING || mRunning ) ; } @ Override public boolean isStarted ( ) { return mStarted ; } public void reverse ( ) { mPlayingBackwards = ! mPlayingBackwards ; if ( mPlayingState == RUNNING ) { long currentTime = AnimationUtils . currentAnimationTimeMillis ( ) ; long currentPlayTime = currentTime - mStartTime ; long timeLeft = mDuration - currentPlayTime ; mStartTime = currentTime - timeLeft ; } else { start ( true ) ; } } private void endAnimation ( ) { sAnimations . get ( ) . remove ( this ) ; sPendingAnimations . get ( ) . remove ( this ) ; sDelayedAnims . get ( ) . remove ( this ) ; mPlayingState = STOPPED ; if ( mRunning && mListeners != null ) { ArrayList < AnimatorListener > tmpListeners = ( ArrayList < AnimatorListener > ) mListeners . clone ( ) ; int numListeners = tmpListeners . size ( ) ; for ( int i = <NUM_LIT:0> ; i < numListeners ; ++ i ) { tmpListeners . get ( i ) . onAnimationEnd ( this ) ; } } mRunning = false ; mStarted = false ; } private void startAnimation ( ) { initAnimation ( ) ; sAnimations . get ( ) . add ( this ) ; if ( mStartDelay > <NUM_LIT:0> && mListeners != null ) { ArrayList < AnimatorListener > tmpListeners = ( ArrayList < AnimatorListener > ) mListeners . clone ( ) ; int numListeners = tmpListeners . size ( ) ; for ( int i = <NUM_LIT:0> ; i < numListeners ; ++ i ) { tmpListeners . get ( i ) . onAnimationStart ( this ) ; } } } private boolean delayedAnimationFrame ( long currentTime ) { if ( ! mStartedDelay ) { mStartedDelay = true ; mDelayStartTime = currentTime ; } else { long deltaTime = currentTime - mDelayStartTime ; if ( deltaTime > mStartDelay ) { mStartTime = currentTime - ( deltaTime - mStartDelay ) ; mPlayingState = RUNNING ; return true ; } } return false ; } boolean animationFrame ( long currentTime ) { boolean done = false ; if ( mPlayingState == STOPPED ) { mPlayingState = RUNNING ; if ( mSeekTime < <NUM_LIT:0> ) { mStartTime = currentTime ; } else { mStartTime = currentTime - mSeekTime ; mSeekTime = - <NUM_LIT:1> ; } } switch ( mPlayingState ) { case RUNNING : case SEEKED : float fraction = mDuration > <NUM_LIT:0> ? ( float ) ( currentTime - mStartTime ) / mDuration : <NUM_LIT> ; if ( fraction >= <NUM_LIT> ) { if ( mCurrentIteration < mRepeatCount || mRepeatCount == INFINITE ) { if ( mListeners != null ) { int numListeners = mListeners . size ( ) ; for ( int i = <NUM_LIT:0> ; i < numListeners ; ++ i ) { mListeners . get ( i ) . onAnimationRepeat ( this ) ; } } if ( mRepeatMode == REVERSE ) { mPlayingBackwards = mPlayingBackwards ? false : true ; } mCurrentIteration += ( int ) fraction ; fraction = fraction % <NUM_LIT> ; mStartTime += mDuration ; } else { done = true ; fraction = Math . min ( fraction , <NUM_LIT:1.0f> ) ; } } if ( mPlayingBackwards ) { fraction = <NUM_LIT> - fraction ; } animateValue ( fraction ) ; break ; } return done ; } public float getAnimatedFraction ( ) { return mCurrentFraction ; } void animateValue ( float fraction ) { fraction = mInterpolator . getInterpolation ( fraction ) ; mCurrentFraction = fraction ; int numValues = mValues . length ; for ( int i = <NUM_LIT:0> ; i < numValues ; ++ i ) { mValues [ i ] . calculateValue ( fraction ) ; } if ( mUpdateListeners != null ) { int numListeners = mUpdateListeners . size ( ) ; for ( int i = <NUM_LIT:0> ; i < numListeners ; ++ i ) { mUpdateListeners . get ( i ) . onAnimationUpdate ( this ) ; } } } @ Override public ValueAnimator clone ( ) { final ValueAnimator anim = ( ValueAnimator ) super . clone ( ) ; if ( mUpdateListeners != null ) { ArrayList < AnimatorUpdateListener > oldListeners = mUpdateListeners ; anim . mUpdateListeners = new ArrayList < AnimatorUpdateListener > ( ) ; int numListeners = oldListeners . size ( ) ; for ( int i = <NUM_LIT:0> ; i < numListeners ; ++ i ) { anim . mUpdateListeners . add ( oldListeners . get ( i ) ) ; } } anim . mSeekTime = - <NUM_LIT:1> ; anim . mPlayingBackwards = false ; anim . mCurrentIteration = <NUM_LIT:0> ; anim . mInitialized = false ; anim . mPlayingState = STOPPED ; anim . mStartedDelay = false ; PropertyValuesHolder [ ] oldValues = mValues ; if ( oldValues != null ) { int numValues = oldValues . length ; anim . mValues = new PropertyValuesHolder [ numValues ] ; anim . mValuesMap = new HashMap < String , PropertyValuesHolder > ( numValues ) ; for ( int i = <NUM_LIT:0> ; i < numValues ; ++ i ) { PropertyValuesHolder newValuesHolder = oldValues [ i ] . clone ( ) ; anim . mValues [ i ] = newValuesHolder ; anim . mValuesMap . put ( newValuesHolder . getPropertyName ( ) , newValuesHolder ) ; } } return anim ; } public static interface AnimatorUpdateListener { void onAnimationUpdate ( ValueAnimator animation ) ; } public static int getCurrentAnimationsCount ( ) { return sAnimations . get ( ) . size ( ) ; } public static void clearAllAnimations ( ) { sAnimations . get ( ) . clear ( ) ; sPendingAnimations . get ( ) . clear ( ) ; sDelayedAnims . get ( ) . clear ( ) ; } @ Override public String toString ( ) { String returnVal = "<STR_LIT>" + Integer . toHexString ( hashCode ( ) ) ; if ( mValues != null ) { for ( int i = <NUM_LIT:0> ; i < mValues . length ; ++ i ) { returnVal += "<STR_LIT>" + mValues [ i ] . toString ( ) ; } } return returnVal ; } } </s>
|
<s> package com . actionbarsherlock . internal . nineoldandroids . animation ; public interface TypeEvaluator < T > { public T evaluate ( float fraction , T startValue , T endValue ) ; } </s>
|
<s> package com . actionbarsherlock . internal . nineoldandroids . animation ; import android . util . Log ; import java . util . ArrayList ; @ SuppressWarnings ( "<STR_LIT:rawtypes>" ) public final class ObjectAnimator extends ValueAnimator { private static final boolean DBG = false ; private Object mTarget ; private String mPropertyName ; public void setPropertyName ( String propertyName ) { if ( mValues != null ) { PropertyValuesHolder valuesHolder = mValues [ <NUM_LIT:0> ] ; String oldName = valuesHolder . getPropertyName ( ) ; valuesHolder . setPropertyName ( propertyName ) ; mValuesMap . remove ( oldName ) ; mValuesMap . put ( propertyName , valuesHolder ) ; } mPropertyName = propertyName ; mInitialized = false ; } public String getPropertyName ( ) { return mPropertyName ; } public ObjectAnimator ( ) { } private ObjectAnimator ( Object target , String propertyName ) { mTarget = target ; setPropertyName ( propertyName ) ; } public static ObjectAnimator ofInt ( Object target , String propertyName , int ... values ) { ObjectAnimator anim = new ObjectAnimator ( target , propertyName ) ; anim . setIntValues ( values ) ; return anim ; } public static ObjectAnimator ofFloat ( Object target , String propertyName , float ... values ) { ObjectAnimator anim = new ObjectAnimator ( target , propertyName ) ; anim . setFloatValues ( values ) ; return anim ; } public static ObjectAnimator ofObject ( Object target , String propertyName , TypeEvaluator evaluator , Object ... values ) { ObjectAnimator anim = new ObjectAnimator ( target , propertyName ) ; anim . setObjectValues ( values ) ; anim . setEvaluator ( evaluator ) ; return anim ; } public static ObjectAnimator ofPropertyValuesHolder ( Object target , PropertyValuesHolder ... values ) { ObjectAnimator anim = new ObjectAnimator ( ) ; anim . mTarget = target ; anim . setValues ( values ) ; return anim ; } @ Override public void setIntValues ( int ... values ) { if ( mValues == null || mValues . length == <NUM_LIT:0> ) { setValues ( PropertyValuesHolder . ofInt ( mPropertyName , values ) ) ; } else { super . setIntValues ( values ) ; } } @ Override public void setFloatValues ( float ... values ) { if ( mValues == null || mValues . length == <NUM_LIT:0> ) { setValues ( PropertyValuesHolder . ofFloat ( mPropertyName , values ) ) ; } else { super . setFloatValues ( values ) ; } } @ Override public void setObjectValues ( Object ... values ) { if ( mValues == null || mValues . length == <NUM_LIT:0> ) { setValues ( PropertyValuesHolder . ofObject ( mPropertyName , ( TypeEvaluator ) null , values ) ) ; } else { super . setObjectValues ( values ) ; } } @ Override public void start ( ) { if ( DBG ) { Log . d ( "<STR_LIT>" , "<STR_LIT>" + mTarget + "<STR_LIT:U+002CU+0020>" + getDuration ( ) ) ; for ( int i = <NUM_LIT:0> ; i < mValues . length ; ++ i ) { PropertyValuesHolder pvh = mValues [ i ] ; ArrayList < Keyframe > keyframes = pvh . mKeyframeSet . mKeyframes ; Log . d ( "<STR_LIT>" , "<STR_LIT>" + i + "<STR_LIT>" + pvh . getPropertyName ( ) + "<STR_LIT:U+002CU+0020>" + keyframes . get ( <NUM_LIT:0> ) . getValue ( ) + "<STR_LIT:U+002CU+0020>" + keyframes . get ( pvh . mKeyframeSet . mNumKeyframes - <NUM_LIT:1> ) . getValue ( ) ) ; } } super . start ( ) ; } @ Override void initAnimation ( ) { if ( ! mInitialized ) { int numValues = mValues . length ; for ( int i = <NUM_LIT:0> ; i < numValues ; ++ i ) { mValues [ i ] . setupSetterAndGetter ( mTarget ) ; } super . initAnimation ( ) ; } } @ Override public ObjectAnimator setDuration ( long duration ) { super . setDuration ( duration ) ; return this ; } public Object getTarget ( ) { return mTarget ; } @ Override public void setTarget ( Object target ) { if ( mTarget != target ) { final Object oldTarget = mTarget ; mTarget = target ; if ( oldTarget != null && target != null && oldTarget . getClass ( ) == target . getClass ( ) ) { return ; } mInitialized = false ; } } @ Override public void setupStartValues ( ) { initAnimation ( ) ; int numValues = mValues . length ; for ( int i = <NUM_LIT:0> ; i < numValues ; ++ i ) { mValues [ i ] . setupStartValue ( mTarget ) ; } } @ Override public void setupEndValues ( ) { initAnimation ( ) ; int numValues = mValues . length ; for ( int i = <NUM_LIT:0> ; i < numValues ; ++ i ) { mValues [ i ] . setupEndValue ( mTarget ) ; } } @ Override void animateValue ( float fraction ) { super . animateValue ( fraction ) ; int numValues = mValues . length ; for ( int i = <NUM_LIT:0> ; i < numValues ; ++ i ) { mValues [ i ] . setAnimatedValue ( mTarget ) ; } } @ Override public ObjectAnimator clone ( ) { final ObjectAnimator anim = ( ObjectAnimator ) super . clone ( ) ; return anim ; } @ Override public String toString ( ) { String returnVal = "<STR_LIT>" + Integer . toHexString ( hashCode ( ) ) + "<STR_LIT>" + mTarget ; if ( mValues != null ) { for ( int i = <NUM_LIT:0> ; i < mValues . length ; ++ i ) { returnVal += "<STR_LIT>" + mValues [ i ] . toString ( ) ; } } return returnVal ; } } </s>
|
<s> package com . actionbarsherlock . internal . nineoldandroids . animation ; import java . util . ArrayList ; import android . view . animation . Interpolator ; import com . actionbarsherlock . internal . nineoldandroids . animation . Keyframe . FloatKeyframe ; @ SuppressWarnings ( "<STR_LIT:unchecked>" ) class FloatKeyframeSet extends KeyframeSet { private float firstValue ; private float lastValue ; private float deltaValue ; private boolean firstTime = true ; public FloatKeyframeSet ( FloatKeyframe ... keyframes ) { super ( keyframes ) ; } @ Override public Object getValue ( float fraction ) { return getFloatValue ( fraction ) ; } @ Override public FloatKeyframeSet clone ( ) { ArrayList < Keyframe > keyframes = mKeyframes ; int numKeyframes = mKeyframes . size ( ) ; FloatKeyframe [ ] newKeyframes = new FloatKeyframe [ numKeyframes ] ; for ( int i = <NUM_LIT:0> ; i < numKeyframes ; ++ i ) { newKeyframes [ i ] = ( FloatKeyframe ) keyframes . get ( i ) . clone ( ) ; } FloatKeyframeSet newSet = new FloatKeyframeSet ( newKeyframes ) ; return newSet ; } public float getFloatValue ( float fraction ) { if ( mNumKeyframes == <NUM_LIT:2> ) { if ( firstTime ) { firstTime = false ; firstValue = ( ( FloatKeyframe ) mKeyframes . get ( <NUM_LIT:0> ) ) . getFloatValue ( ) ; lastValue = ( ( FloatKeyframe ) mKeyframes . get ( <NUM_LIT:1> ) ) . getFloatValue ( ) ; deltaValue = lastValue - firstValue ; } if ( mInterpolator != null ) { fraction = mInterpolator . getInterpolation ( fraction ) ; } if ( mEvaluator == null ) { return firstValue + fraction * deltaValue ; } else { return ( ( Number ) mEvaluator . evaluate ( fraction , firstValue , lastValue ) ) . floatValue ( ) ; } } if ( fraction <= <NUM_LIT> ) { final FloatKeyframe prevKeyframe = ( FloatKeyframe ) mKeyframes . get ( <NUM_LIT:0> ) ; final FloatKeyframe nextKeyframe = ( FloatKeyframe ) mKeyframes . get ( <NUM_LIT:1> ) ; float prevValue = prevKeyframe . getFloatValue ( ) ; float nextValue = nextKeyframe . getFloatValue ( ) ; float prevFraction = prevKeyframe . getFraction ( ) ; float nextFraction = nextKeyframe . getFraction ( ) ; final Interpolator interpolator = nextKeyframe . getInterpolator ( ) ; if ( interpolator != null ) { fraction = interpolator . getInterpolation ( fraction ) ; } float intervalFraction = ( fraction - prevFraction ) / ( nextFraction - prevFraction ) ; return mEvaluator == null ? prevValue + intervalFraction * ( nextValue - prevValue ) : ( ( Number ) mEvaluator . evaluate ( intervalFraction , prevValue , nextValue ) ) . floatValue ( ) ; } else if ( fraction >= <NUM_LIT> ) { final FloatKeyframe prevKeyframe = ( FloatKeyframe ) mKeyframes . get ( mNumKeyframes - <NUM_LIT:2> ) ; final FloatKeyframe nextKeyframe = ( FloatKeyframe ) mKeyframes . get ( mNumKeyframes - <NUM_LIT:1> ) ; float prevValue = prevKeyframe . getFloatValue ( ) ; float nextValue = nextKeyframe . getFloatValue ( ) ; float prevFraction = prevKeyframe . getFraction ( ) ; float nextFraction = nextKeyframe . getFraction ( ) ; final Interpolator interpolator = nextKeyframe . getInterpolator ( ) ; if ( interpolator != null ) { fraction = interpolator . getInterpolation ( fraction ) ; } float intervalFraction = ( fraction - prevFraction ) / ( nextFraction - prevFraction ) ; return mEvaluator == null ? prevValue + intervalFraction * ( nextValue - prevValue ) : ( ( Number ) mEvaluator . evaluate ( intervalFraction , prevValue , nextValue ) ) . floatValue ( ) ; } FloatKeyframe prevKeyframe = ( FloatKeyframe ) mKeyframes . get ( <NUM_LIT:0> ) ; for ( int i = <NUM_LIT:1> ; i < mNumKeyframes ; ++ i ) { FloatKeyframe nextKeyframe = ( FloatKeyframe ) mKeyframes . get ( i ) ; if ( fraction < nextKeyframe . getFraction ( ) ) { final Interpolator interpolator = nextKeyframe . getInterpolator ( ) ; if ( interpolator != null ) { fraction = interpolator . getInterpolation ( fraction ) ; } float intervalFraction = ( fraction - prevKeyframe . getFraction ( ) ) / ( nextKeyframe . getFraction ( ) - prevKeyframe . getFraction ( ) ) ; float prevValue = prevKeyframe . getFloatValue ( ) ; float nextValue = nextKeyframe . getFloatValue ( ) ; return mEvaluator == null ? prevValue + intervalFraction * ( nextValue - prevValue ) : ( ( Number ) mEvaluator . evaluate ( intervalFraction , prevValue , nextValue ) ) . floatValue ( ) ; } prevKeyframe = nextKeyframe ; } return ( ( Number ) mKeyframes . get ( mNumKeyframes - <NUM_LIT:1> ) . getValue ( ) ) . floatValue ( ) ; } } </s>
|
<s> package com . actionbarsherlock . internal . nineoldandroids . animation ; import android . view . animation . Interpolator ; @ SuppressWarnings ( "<STR_LIT:rawtypes>" ) public abstract class Keyframe implements Cloneable { float mFraction ; Class mValueType ; private Interpolator mInterpolator = null ; boolean mHasValue = false ; public static Keyframe ofInt ( float fraction , int value ) { return new IntKeyframe ( fraction , value ) ; } public static Keyframe ofInt ( float fraction ) { return new IntKeyframe ( fraction ) ; } public static Keyframe ofFloat ( float fraction , float value ) { return new FloatKeyframe ( fraction , value ) ; } public static Keyframe ofFloat ( float fraction ) { return new FloatKeyframe ( fraction ) ; } public static Keyframe ofObject ( float fraction , Object value ) { return new ObjectKeyframe ( fraction , value ) ; } public static Keyframe ofObject ( float fraction ) { return new ObjectKeyframe ( fraction , null ) ; } public boolean hasValue ( ) { return mHasValue ; } public abstract Object getValue ( ) ; public abstract void setValue ( Object value ) ; public float getFraction ( ) { return mFraction ; } public void setFraction ( float fraction ) { mFraction = fraction ; } public Interpolator getInterpolator ( ) { return mInterpolator ; } public void setInterpolator ( Interpolator interpolator ) { mInterpolator = interpolator ; } public Class getType ( ) { return mValueType ; } @ Override public abstract Keyframe clone ( ) ; static class ObjectKeyframe extends Keyframe { Object mValue ; ObjectKeyframe ( float fraction , Object value ) { mFraction = fraction ; mValue = value ; mHasValue = ( value != null ) ; mValueType = mHasValue ? value . getClass ( ) : Object . class ; } public Object getValue ( ) { return mValue ; } public void setValue ( Object value ) { mValue = value ; mHasValue = ( value != null ) ; } @ Override public ObjectKeyframe clone ( ) { ObjectKeyframe kfClone = new ObjectKeyframe ( getFraction ( ) , mValue ) ; kfClone . setInterpolator ( getInterpolator ( ) ) ; return kfClone ; } } static class IntKeyframe extends Keyframe { int mValue ; IntKeyframe ( float fraction , int value ) { mFraction = fraction ; mValue = value ; mValueType = int . class ; mHasValue = true ; } IntKeyframe ( float fraction ) { mFraction = fraction ; mValueType = int . class ; } public int getIntValue ( ) { return mValue ; } public Object getValue ( ) { return mValue ; } public void setValue ( Object value ) { if ( value != null && value . getClass ( ) == Integer . class ) { mValue = ( ( Integer ) value ) . intValue ( ) ; mHasValue = true ; } } @ Override public IntKeyframe clone ( ) { IntKeyframe kfClone = new IntKeyframe ( getFraction ( ) , mValue ) ; kfClone . setInterpolator ( getInterpolator ( ) ) ; return kfClone ; } } static class FloatKeyframe extends Keyframe { float mValue ; FloatKeyframe ( float fraction , float value ) { mFraction = fraction ; mValue = value ; mValueType = float . class ; mHasValue = true ; } FloatKeyframe ( float fraction ) { mFraction = fraction ; mValueType = float . class ; } public float getFloatValue ( ) { return mValue ; } public Object getValue ( ) { return mValue ; } public void setValue ( Object value ) { if ( value != null && value . getClass ( ) == Float . class ) { mValue = ( ( Float ) value ) . floatValue ( ) ; mHasValue = true ; } } @ Override public FloatKeyframe clone ( ) { FloatKeyframe kfClone = new FloatKeyframe ( getFraction ( ) , mValue ) ; kfClone . setInterpolator ( getInterpolator ( ) ) ; return kfClone ; } } } </s>
|
<s> package com . actionbarsherlock . internal . nineoldandroids . animation ; import java . util . ArrayList ; import java . util . Collection ; import java . util . HashMap ; import java . util . List ; import android . view . animation . Interpolator ; @ SuppressWarnings ( "<STR_LIT:unchecked>" ) public final class AnimatorSet extends Animator { private ArrayList < Animator > mPlayingSet = new ArrayList < Animator > ( ) ; private HashMap < Animator , Node > mNodeMap = new HashMap < Animator , Node > ( ) ; private ArrayList < Node > mNodes = new ArrayList < Node > ( ) ; private ArrayList < Node > mSortedNodes = new ArrayList < Node > ( ) ; private boolean mNeedsSort = true ; private AnimatorSetListener mSetListener = null ; boolean mTerminated = false ; private boolean mStarted = false ; private long mStartDelay = <NUM_LIT:0> ; private ValueAnimator mDelayAnim = null ; private long mDuration = - <NUM_LIT:1> ; public void playTogether ( Animator ... items ) { if ( items != null ) { mNeedsSort = true ; Builder builder = play ( items [ <NUM_LIT:0> ] ) ; for ( int i = <NUM_LIT:1> ; i < items . length ; ++ i ) { builder . with ( items [ i ] ) ; } } } public void playTogether ( Collection < Animator > items ) { if ( items != null && items . size ( ) > <NUM_LIT:0> ) { mNeedsSort = true ; Builder builder = null ; for ( Animator anim : items ) { if ( builder == null ) { builder = play ( anim ) ; } else { builder . with ( anim ) ; } } } } public void playSequentially ( Animator ... items ) { if ( items != null ) { mNeedsSort = true ; if ( items . length == <NUM_LIT:1> ) { play ( items [ <NUM_LIT:0> ] ) ; } else { for ( int i = <NUM_LIT:0> ; i < items . length - <NUM_LIT:1> ; ++ i ) { play ( items [ i ] ) . before ( items [ i + <NUM_LIT:1> ] ) ; } } } } public void playSequentially ( List < Animator > items ) { if ( items != null && items . size ( ) > <NUM_LIT:0> ) { mNeedsSort = true ; if ( items . size ( ) == <NUM_LIT:1> ) { play ( items . get ( <NUM_LIT:0> ) ) ; } else { for ( int i = <NUM_LIT:0> ; i < items . size ( ) - <NUM_LIT:1> ; ++ i ) { play ( items . get ( i ) ) . before ( items . get ( i + <NUM_LIT:1> ) ) ; } } } } public ArrayList < Animator > getChildAnimations ( ) { ArrayList < Animator > childList = new ArrayList < Animator > ( ) ; for ( Node node : mNodes ) { childList . add ( node . animation ) ; } return childList ; } @ Override public void setTarget ( Object target ) { for ( Node node : mNodes ) { Animator animation = node . animation ; if ( animation instanceof AnimatorSet ) { ( ( AnimatorSet ) animation ) . setTarget ( target ) ; } else if ( animation instanceof ObjectAnimator ) { ( ( ObjectAnimator ) animation ) . setTarget ( target ) ; } } } @ Override public void setInterpolator ( Interpolator interpolator ) { for ( Node node : mNodes ) { node . animation . setInterpolator ( interpolator ) ; } } public Builder play ( Animator anim ) { if ( anim != null ) { mNeedsSort = true ; return new Builder ( anim ) ; } return null ; } @ Override public void cancel ( ) { mTerminated = true ; if ( isStarted ( ) ) { ArrayList < AnimatorListener > tmpListeners = null ; if ( mListeners != null ) { tmpListeners = ( ArrayList < AnimatorListener > ) mListeners . clone ( ) ; for ( AnimatorListener listener : tmpListeners ) { listener . onAnimationCancel ( this ) ; } } if ( mDelayAnim != null && mDelayAnim . isRunning ( ) ) { mDelayAnim . cancel ( ) ; } else if ( mSortedNodes . size ( ) > <NUM_LIT:0> ) { for ( Node node : mSortedNodes ) { node . animation . cancel ( ) ; } } if ( tmpListeners != null ) { for ( AnimatorListener listener : tmpListeners ) { listener . onAnimationEnd ( this ) ; } } mStarted = false ; } } @ Override public void end ( ) { mTerminated = true ; if ( isStarted ( ) ) { if ( mSortedNodes . size ( ) != mNodes . size ( ) ) { sortNodes ( ) ; for ( Node node : mSortedNodes ) { if ( mSetListener == null ) { mSetListener = new AnimatorSetListener ( this ) ; } node . animation . addListener ( mSetListener ) ; } } if ( mDelayAnim != null ) { mDelayAnim . cancel ( ) ; } if ( mSortedNodes . size ( ) > <NUM_LIT:0> ) { for ( Node node : mSortedNodes ) { node . animation . end ( ) ; } } if ( mListeners != null ) { ArrayList < AnimatorListener > tmpListeners = ( ArrayList < AnimatorListener > ) mListeners . clone ( ) ; for ( AnimatorListener listener : tmpListeners ) { listener . onAnimationEnd ( this ) ; } } mStarted = false ; } } @ Override public boolean isRunning ( ) { for ( Node node : mNodes ) { if ( node . animation . isRunning ( ) ) { return true ; } } return false ; } @ Override public boolean isStarted ( ) { return mStarted ; } @ Override public long getStartDelay ( ) { return mStartDelay ; } @ Override public void setStartDelay ( long startDelay ) { mStartDelay = startDelay ; } @ Override public long getDuration ( ) { return mDuration ; } @ Override public AnimatorSet setDuration ( long duration ) { if ( duration < <NUM_LIT:0> ) { throw new IllegalArgumentException ( "<STR_LIT>" ) ; } for ( Node node : mNodes ) { node . animation . setDuration ( duration ) ; } mDuration = duration ; return this ; } @ Override public void setupStartValues ( ) { for ( Node node : mNodes ) { node . animation . setupStartValues ( ) ; } } @ Override public void setupEndValues ( ) { for ( Node node : mNodes ) { node . animation . setupEndValues ( ) ; } } @ Override public void start ( ) { mTerminated = false ; mStarted = true ; sortNodes ( ) ; int numSortedNodes = mSortedNodes . size ( ) ; for ( int i = <NUM_LIT:0> ; i < numSortedNodes ; ++ i ) { Node node = mSortedNodes . get ( i ) ; ArrayList < AnimatorListener > oldListeners = node . animation . getListeners ( ) ; if ( oldListeners != null && oldListeners . size ( ) > <NUM_LIT:0> ) { final ArrayList < AnimatorListener > clonedListeners = new ArrayList < AnimatorListener > ( oldListeners ) ; for ( AnimatorListener listener : clonedListeners ) { if ( listener instanceof DependencyListener || listener instanceof AnimatorSetListener ) { node . animation . removeListener ( listener ) ; } } } } final ArrayList < Node > nodesToStart = new ArrayList < Node > ( ) ; for ( int i = <NUM_LIT:0> ; i < numSortedNodes ; ++ i ) { Node node = mSortedNodes . get ( i ) ; if ( mSetListener == null ) { mSetListener = new AnimatorSetListener ( this ) ; } if ( node . dependencies == null || node . dependencies . size ( ) == <NUM_LIT:0> ) { nodesToStart . add ( node ) ; } else { int numDependencies = node . dependencies . size ( ) ; for ( int j = <NUM_LIT:0> ; j < numDependencies ; ++ j ) { Dependency dependency = node . dependencies . get ( j ) ; dependency . node . animation . addListener ( new DependencyListener ( this , node , dependency . rule ) ) ; } node . tmpDependencies = ( ArrayList < Dependency > ) node . dependencies . clone ( ) ; } node . animation . addListener ( mSetListener ) ; } if ( mStartDelay <= <NUM_LIT:0> ) { for ( Node node : nodesToStart ) { node . animation . start ( ) ; mPlayingSet . add ( node . animation ) ; } } else { mDelayAnim = ValueAnimator . ofFloat ( <NUM_LIT> , <NUM_LIT> ) ; mDelayAnim . setDuration ( mStartDelay ) ; mDelayAnim . addListener ( new AnimatorListenerAdapter ( ) { boolean canceled = false ; public void onAnimationCancel ( Animator anim ) { canceled = true ; } public void onAnimationEnd ( Animator anim ) { if ( ! canceled ) { int numNodes = nodesToStart . size ( ) ; for ( int i = <NUM_LIT:0> ; i < numNodes ; ++ i ) { Node node = nodesToStart . get ( i ) ; node . animation . start ( ) ; mPlayingSet . add ( node . animation ) ; } } } } ) ; mDelayAnim . start ( ) ; } if ( mListeners != null ) { ArrayList < AnimatorListener > tmpListeners = ( ArrayList < AnimatorListener > ) mListeners . clone ( ) ; int numListeners = tmpListeners . size ( ) ; for ( int i = <NUM_LIT:0> ; i < numListeners ; ++ i ) { tmpListeners . get ( i ) . onAnimationStart ( this ) ; } } if ( mNodes . size ( ) == <NUM_LIT:0> && mStartDelay == <NUM_LIT:0> ) { mStarted = false ; if ( mListeners != null ) { ArrayList < AnimatorListener > tmpListeners = ( ArrayList < AnimatorListener > ) mListeners . clone ( ) ; int numListeners = tmpListeners . size ( ) ; for ( int i = <NUM_LIT:0> ; i < numListeners ; ++ i ) { tmpListeners . get ( i ) . onAnimationEnd ( this ) ; } } } } @ Override public AnimatorSet clone ( ) { final AnimatorSet anim = ( AnimatorSet ) super . clone ( ) ; anim . mNeedsSort = true ; anim . mTerminated = false ; anim . mStarted = false ; anim . mPlayingSet = new ArrayList < Animator > ( ) ; anim . mNodeMap = new HashMap < Animator , Node > ( ) ; anim . mNodes = new ArrayList < Node > ( ) ; anim . mSortedNodes = new ArrayList < Node > ( ) ; HashMap < Node , Node > nodeCloneMap = new HashMap < Node , Node > ( ) ; for ( Node node : mNodes ) { Node nodeClone = node . clone ( ) ; nodeCloneMap . put ( node , nodeClone ) ; anim . mNodes . add ( nodeClone ) ; anim . mNodeMap . put ( nodeClone . animation , nodeClone ) ; nodeClone . dependencies = null ; nodeClone . tmpDependencies = null ; nodeClone . nodeDependents = null ; nodeClone . nodeDependencies = null ; ArrayList < AnimatorListener > cloneListeners = nodeClone . animation . getListeners ( ) ; if ( cloneListeners != null ) { ArrayList < AnimatorListener > listenersToRemove = null ; for ( AnimatorListener listener : cloneListeners ) { if ( listener instanceof AnimatorSetListener ) { if ( listenersToRemove == null ) { listenersToRemove = new ArrayList < AnimatorListener > ( ) ; } listenersToRemove . add ( listener ) ; } } if ( listenersToRemove != null ) { for ( AnimatorListener listener : listenersToRemove ) { cloneListeners . remove ( listener ) ; } } } } for ( Node node : mNodes ) { Node nodeClone = nodeCloneMap . get ( node ) ; if ( node . dependencies != null ) { for ( Dependency dependency : node . dependencies ) { Node clonedDependencyNode = nodeCloneMap . get ( dependency . node ) ; Dependency cloneDependency = new Dependency ( clonedDependencyNode , dependency . rule ) ; nodeClone . addDependency ( cloneDependency ) ; } } } return anim ; } private static class DependencyListener implements AnimatorListener { private AnimatorSet mAnimatorSet ; private Node mNode ; private int mRule ; public DependencyListener ( AnimatorSet animatorSet , Node node , int rule ) { this . mAnimatorSet = animatorSet ; this . mNode = node ; this . mRule = rule ; } public void onAnimationCancel ( Animator animation ) { } public void onAnimationEnd ( Animator animation ) { if ( mRule == Dependency . AFTER ) { startIfReady ( animation ) ; } } public void onAnimationRepeat ( Animator animation ) { } public void onAnimationStart ( Animator animation ) { if ( mRule == Dependency . WITH ) { startIfReady ( animation ) ; } } private void startIfReady ( Animator dependencyAnimation ) { if ( mAnimatorSet . mTerminated ) { return ; } Dependency dependencyToRemove = null ; int numDependencies = mNode . tmpDependencies . size ( ) ; for ( int i = <NUM_LIT:0> ; i < numDependencies ; ++ i ) { Dependency dependency = mNode . tmpDependencies . get ( i ) ; if ( dependency . rule == mRule && dependency . node . animation == dependencyAnimation ) { dependencyToRemove = dependency ; dependencyAnimation . removeListener ( this ) ; break ; } } mNode . tmpDependencies . remove ( dependencyToRemove ) ; if ( mNode . tmpDependencies . size ( ) == <NUM_LIT:0> ) { mNode . animation . start ( ) ; mAnimatorSet . mPlayingSet . add ( mNode . animation ) ; } } } private class AnimatorSetListener implements AnimatorListener { private AnimatorSet mAnimatorSet ; AnimatorSetListener ( AnimatorSet animatorSet ) { mAnimatorSet = animatorSet ; } public void onAnimationCancel ( Animator animation ) { if ( ! mTerminated ) { if ( mPlayingSet . size ( ) == <NUM_LIT:0> ) { if ( mListeners != null ) { int numListeners = mListeners . size ( ) ; for ( int i = <NUM_LIT:0> ; i < numListeners ; ++ i ) { mListeners . get ( i ) . onAnimationCancel ( mAnimatorSet ) ; } } } } } public void onAnimationEnd ( Animator animation ) { animation . removeListener ( this ) ; mPlayingSet . remove ( animation ) ; Node animNode = mAnimatorSet . mNodeMap . get ( animation ) ; animNode . done = true ; if ( ! mTerminated ) { ArrayList < Node > sortedNodes = mAnimatorSet . mSortedNodes ; boolean allDone = true ; int numSortedNodes = sortedNodes . size ( ) ; for ( int i = <NUM_LIT:0> ; i < numSortedNodes ; ++ i ) { if ( ! sortedNodes . get ( i ) . done ) { allDone = false ; break ; } } if ( allDone ) { if ( mListeners != null ) { ArrayList < AnimatorListener > tmpListeners = ( ArrayList < AnimatorListener > ) mListeners . clone ( ) ; int numListeners = tmpListeners . size ( ) ; for ( int i = <NUM_LIT:0> ; i < numListeners ; ++ i ) { tmpListeners . get ( i ) . onAnimationEnd ( mAnimatorSet ) ; } } mAnimatorSet . mStarted = false ; } } } public void onAnimationRepeat ( Animator animation ) { } public void onAnimationStart ( Animator animation ) { } } private void sortNodes ( ) { if ( mNeedsSort ) { mSortedNodes . clear ( ) ; ArrayList < Node > roots = new ArrayList < Node > ( ) ; int numNodes = mNodes . size ( ) ; for ( int i = <NUM_LIT:0> ; i < numNodes ; ++ i ) { Node node = mNodes . get ( i ) ; if ( node . dependencies == null || node . dependencies . size ( ) == <NUM_LIT:0> ) { roots . add ( node ) ; } } ArrayList < Node > tmpRoots = new ArrayList < Node > ( ) ; while ( roots . size ( ) > <NUM_LIT:0> ) { int numRoots = roots . size ( ) ; for ( int i = <NUM_LIT:0> ; i < numRoots ; ++ i ) { Node root = roots . get ( i ) ; mSortedNodes . add ( root ) ; if ( root . nodeDependents != null ) { int numDependents = root . nodeDependents . size ( ) ; for ( int j = <NUM_LIT:0> ; j < numDependents ; ++ j ) { Node node = root . nodeDependents . get ( j ) ; node . nodeDependencies . remove ( root ) ; if ( node . nodeDependencies . size ( ) == <NUM_LIT:0> ) { tmpRoots . add ( node ) ; } } } } roots . clear ( ) ; roots . addAll ( tmpRoots ) ; tmpRoots . clear ( ) ; } mNeedsSort = false ; if ( mSortedNodes . size ( ) != mNodes . size ( ) ) { throw new IllegalStateException ( "<STR_LIT>" + "<STR_LIT>" ) ; } } else { int numNodes = mNodes . size ( ) ; for ( int i = <NUM_LIT:0> ; i < numNodes ; ++ i ) { Node node = mNodes . get ( i ) ; if ( node . dependencies != null && node . dependencies . size ( ) > <NUM_LIT:0> ) { int numDependencies = node . dependencies . size ( ) ; for ( int j = <NUM_LIT:0> ; j < numDependencies ; ++ j ) { Dependency dependency = node . dependencies . get ( j ) ; if ( node . nodeDependencies == null ) { node . nodeDependencies = new ArrayList < Node > ( ) ; } if ( ! node . nodeDependencies . contains ( dependency . node ) ) { node . nodeDependencies . add ( dependency . node ) ; } } } node . done = false ; } } } private static class Dependency { static final int WITH = <NUM_LIT:0> ; static final int AFTER = <NUM_LIT:1> ; public Node node ; public int rule ; public Dependency ( Node node , int rule ) { this . node = node ; this . rule = rule ; } } private static class Node implements Cloneable { public Animator animation ; public ArrayList < Dependency > dependencies = null ; public ArrayList < Dependency > tmpDependencies = null ; public ArrayList < Node > nodeDependencies = null ; public ArrayList < Node > nodeDependents = null ; public boolean done = false ; public Node ( Animator animation ) { this . animation = animation ; } public void addDependency ( Dependency dependency ) { if ( dependencies == null ) { dependencies = new ArrayList < Dependency > ( ) ; nodeDependencies = new ArrayList < Node > ( ) ; } dependencies . add ( dependency ) ; if ( ! nodeDependencies . contains ( dependency . node ) ) { nodeDependencies . add ( dependency . node ) ; } Node dependencyNode = dependency . node ; if ( dependencyNode . nodeDependents == null ) { dependencyNode . nodeDependents = new ArrayList < Node > ( ) ; } dependencyNode . nodeDependents . add ( this ) ; } @ Override public Node clone ( ) { try { Node node = ( Node ) super . clone ( ) ; node . animation = animation . clone ( ) ; return node ; } catch ( CloneNotSupportedException e ) { throw new AssertionError ( ) ; } } } public class Builder { private Node mCurrentNode ; Builder ( Animator anim ) { mCurrentNode = mNodeMap . get ( anim ) ; if ( mCurrentNode == null ) { mCurrentNode = new Node ( anim ) ; mNodeMap . put ( anim , mCurrentNode ) ; mNodes . add ( mCurrentNode ) ; } } public Builder with ( Animator anim ) { Node node = mNodeMap . get ( anim ) ; if ( node == null ) { node = new Node ( anim ) ; mNodeMap . put ( anim , node ) ; mNodes . add ( node ) ; } Dependency dependency = new Dependency ( mCurrentNode , Dependency . WITH ) ; node . addDependency ( dependency ) ; return this ; } public Builder before ( Animator anim ) { Node node = mNodeMap . get ( anim ) ; if ( node == null ) { node = new Node ( anim ) ; mNodeMap . put ( anim , node ) ; mNodes . add ( node ) ; } Dependency dependency = new Dependency ( mCurrentNode , Dependency . AFTER ) ; node . addDependency ( dependency ) ; return this ; } public Builder after ( Animator anim ) { Node node = mNodeMap . get ( anim ) ; if ( node == null ) { node = new Node ( anim ) ; mNodeMap . put ( anim , node ) ; mNodes . add ( node ) ; } Dependency dependency = new Dependency ( node , Dependency . AFTER ) ; mCurrentNode . addDependency ( dependency ) ; return this ; } public Builder after ( long delay ) { ValueAnimator anim = ValueAnimator . ofFloat ( <NUM_LIT> , <NUM_LIT> ) ; anim . setDuration ( delay ) ; after ( anim ) ; return this ; } } } </s>
|
<s> package com . actionbarsherlock . internal . nineoldandroids . animation ; public class FloatEvaluator implements TypeEvaluator < Number > { public Float evaluate ( float fraction , Number startValue , Number endValue ) { float startFloat = startValue . floatValue ( ) ; return startFloat + fraction * ( endValue . floatValue ( ) - startFloat ) ; } } </s>
|
<s> package com . actionbarsherlock . internal . nineoldandroids . view ; import android . content . Context ; import android . util . AttributeSet ; import android . view . ViewGroup ; import com . actionbarsherlock . internal . nineoldandroids . view . animation . AnimatorProxy ; public abstract class NineViewGroup extends ViewGroup { private final AnimatorProxy mProxy ; public NineViewGroup ( Context context ) { super ( context ) ; mProxy = AnimatorProxy . NEEDS_PROXY ? AnimatorProxy . wrap ( this ) : null ; } public NineViewGroup ( Context context , AttributeSet attrs ) { super ( context , attrs ) ; mProxy = AnimatorProxy . NEEDS_PROXY ? AnimatorProxy . wrap ( this ) : null ; } public NineViewGroup ( Context context , AttributeSet attrs , int defStyle ) { super ( context , attrs , defStyle ) ; mProxy = AnimatorProxy . NEEDS_PROXY ? AnimatorProxy . wrap ( this ) : null ; } @ Override public void setVisibility ( int visibility ) { if ( mProxy != null ) { if ( visibility == GONE ) { clearAnimation ( ) ; } else if ( visibility == VISIBLE ) { setAnimation ( mProxy ) ; } } super . setVisibility ( visibility ) ; } public float getAlpha ( ) { if ( AnimatorProxy . NEEDS_PROXY ) { return mProxy . getAlpha ( ) ; } else { return super . getAlpha ( ) ; } } public void setAlpha ( float alpha ) { if ( AnimatorProxy . NEEDS_PROXY ) { mProxy . setAlpha ( alpha ) ; } else { super . setAlpha ( alpha ) ; } } public float getTranslationX ( ) { if ( AnimatorProxy . NEEDS_PROXY ) { return mProxy . getTranslationX ( ) ; } else { return super . getTranslationX ( ) ; } } public void setTranslationX ( float translationX ) { if ( AnimatorProxy . NEEDS_PROXY ) { mProxy . setTranslationX ( translationX ) ; } else { super . setTranslationX ( translationX ) ; } } public float getTranslationY ( ) { if ( AnimatorProxy . NEEDS_PROXY ) { return mProxy . getTranslationY ( ) ; } else { return super . getTranslationY ( ) ; } } public void setTranslationY ( float translationY ) { if ( AnimatorProxy . NEEDS_PROXY ) { mProxy . setTranslationY ( translationY ) ; } else { super . setTranslationY ( translationY ) ; } } } </s>
|
<s> package com . actionbarsherlock . internal . nineoldandroids . view . animation ; import java . lang . ref . WeakReference ; import java . util . WeakHashMap ; import android . graphics . Matrix ; import android . graphics . RectF ; import android . os . Build ; import android . util . FloatMath ; import android . view . View ; import android . view . animation . Animation ; import android . view . animation . Transformation ; public final class AnimatorProxy extends Animation { public static final boolean NEEDS_PROXY = Build . VERSION . SDK_INT < Build . VERSION_CODES . HONEYCOMB ; private static final WeakHashMap < View , AnimatorProxy > PROXIES = new WeakHashMap < View , AnimatorProxy > ( ) ; public static AnimatorProxy wrap ( View view ) { AnimatorProxy proxy = PROXIES . get ( view ) ; if ( proxy == null ) { proxy = new AnimatorProxy ( view ) ; PROXIES . put ( view , proxy ) ; } return proxy ; } private final WeakReference < View > mView ; private float mAlpha = <NUM_LIT:1> ; private float mScaleX = <NUM_LIT:1> ; private float mScaleY = <NUM_LIT:1> ; private float mTranslationX ; private float mTranslationY ; private final RectF mBefore = new RectF ( ) ; private final RectF mAfter = new RectF ( ) ; private final Matrix mTempMatrix = new Matrix ( ) ; private AnimatorProxy ( View view ) { setDuration ( <NUM_LIT:0> ) ; setFillAfter ( true ) ; view . setAnimation ( this ) ; mView = new WeakReference < View > ( view ) ; } public float getAlpha ( ) { return mAlpha ; } public void setAlpha ( float alpha ) { if ( mAlpha != alpha ) { mAlpha = alpha ; View view = mView . get ( ) ; if ( view != null ) { view . invalidate ( ) ; } } } public float getScaleX ( ) { return mScaleX ; } public void setScaleX ( float scaleX ) { if ( mScaleX != scaleX ) { prepareForUpdate ( ) ; mScaleX = scaleX ; invalidateAfterUpdate ( ) ; } } public float getScaleY ( ) { return mScaleY ; } public void setScaleY ( float scaleY ) { if ( mScaleY != scaleY ) { prepareForUpdate ( ) ; mScaleY = scaleY ; invalidateAfterUpdate ( ) ; } } public int getScrollX ( ) { View view = mView . get ( ) ; if ( view == null ) { return <NUM_LIT:0> ; } return view . getScrollX ( ) ; } public void setScrollX ( int value ) { View view = mView . get ( ) ; if ( view != null ) { view . scrollTo ( value , view . getScrollY ( ) ) ; } } public int getScrollY ( ) { View view = mView . get ( ) ; if ( view == null ) { return <NUM_LIT:0> ; } return view . getScrollY ( ) ; } public void setScrollY ( int value ) { View view = mView . get ( ) ; if ( view != null ) { view . scrollTo ( view . getScrollY ( ) , value ) ; } } public float getTranslationX ( ) { return mTranslationX ; } public void setTranslationX ( float translationX ) { if ( mTranslationX != translationX ) { prepareForUpdate ( ) ; mTranslationX = translationX ; invalidateAfterUpdate ( ) ; } } public float getTranslationY ( ) { return mTranslationY ; } public void setTranslationY ( float translationY ) { if ( mTranslationY != translationY ) { prepareForUpdate ( ) ; mTranslationY = translationY ; invalidateAfterUpdate ( ) ; } } private void prepareForUpdate ( ) { View view = mView . get ( ) ; if ( view != null ) { computeRect ( mBefore , view ) ; } } private void invalidateAfterUpdate ( ) { View view = mView . get ( ) ; if ( view == null ) { return ; } View parent = ( View ) view . getParent ( ) ; if ( parent == null ) { return ; } view . setAnimation ( this ) ; final RectF after = mAfter ; computeRect ( after , view ) ; after . union ( mBefore ) ; parent . invalidate ( ( int ) FloatMath . floor ( after . left ) , ( int ) FloatMath . floor ( after . top ) , ( int ) FloatMath . ceil ( after . right ) , ( int ) FloatMath . ceil ( after . bottom ) ) ; } private void computeRect ( final RectF r , View view ) { final float w = view . getWidth ( ) ; final float h = view . getHeight ( ) ; r . set ( <NUM_LIT:0> , <NUM_LIT:0> , w , h ) ; final Matrix m = mTempMatrix ; m . reset ( ) ; transformMatrix ( m , view ) ; mTempMatrix . mapRect ( r ) ; r . offset ( view . getLeft ( ) , view . getTop ( ) ) ; if ( r . right < r . left ) { final float f = r . right ; r . right = r . left ; r . left = f ; } if ( r . bottom < r . top ) { final float f = r . top ; r . top = r . bottom ; r . bottom = f ; } } private void transformMatrix ( Matrix m , View view ) { final float w = view . getWidth ( ) ; final float h = view . getHeight ( ) ; final float sX = mScaleX ; final float sY = mScaleY ; if ( ( sX != <NUM_LIT:1.0f> ) || ( sY != <NUM_LIT:1.0f> ) ) { final float deltaSX = ( ( sX * w ) - w ) / <NUM_LIT> ; final float deltaSY = ( ( sY * h ) - h ) / <NUM_LIT> ; m . postScale ( sX , sY ) ; m . postTranslate ( - deltaSX , - deltaSY ) ; } m . postTranslate ( mTranslationX , mTranslationY ) ; } @ Override protected void applyTransformation ( float interpolatedTime , Transformation t ) { View view = mView . get ( ) ; if ( view != null ) { t . setAlpha ( mAlpha ) ; transformMatrix ( t . getMatrix ( ) , view ) ; } } @ Override public void reset ( ) { } } </s>
|
<s> 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 > ( <NUM_LIT: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 ) { 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 ) ; } } } </s>
|
<s> 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 ; public class ActionBarImpl extends ActionBar { private Context mContext ; private Context mThemedContext ; private Activity mActivity ; 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 = <NUM_LIT:0> ; private static final int CONTEXT_DISPLAY_SPLIT = <NUM_LIT:1> ; private static final int INVALID_POSITION = - <NUM_LIT: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 ( <NUM_LIT:0> ) ; mContainerView . setTranslationY ( <NUM_LIT: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 ) ; if ( ( features & ( <NUM_LIT:1> << Window . FEATURE_ACTION_BAR_OVERLAY ) ) == <NUM_LIT:0> ) { mContentView = ( NineFrameLayout ) decor . findViewById ( android . R . id . content ) ; } } public ActionBarImpl ( Dialog 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 ( ) + "<STR_LIT>" + "<STR_LIT>" ) ; } mActionView . setContextView ( mContextView ) ; mContextDisplayMode = mActionView . isSplitActionBar ( ) ? CONTEXT_DISPLAY_SPLIT : CONTEXT_DISPLAY_NORMAL ; setHomeButtonEnabled ( mContext . getApplicationInfo ( ) . targetSdkVersion < <NUM_LIT> ) ; 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 ) ) ; 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 ; 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 ; } } 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 = <NUM_LIT: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 : <NUM_LIT:0> , DISPLAY_USE_LOGO ) ; } @ Override public void setDisplayShowHomeEnabled ( boolean showHome ) { setDisplayOptions ( showHome ? DISPLAY_SHOW_HOME : <NUM_LIT:0> , DISPLAY_SHOW_HOME ) ; } @ Override public void setDisplayHomeAsUpEnabled ( boolean showHomeAsUp ) { setDisplayOptions ( showHomeAsUp ? DISPLAY_HOME_AS_UP : <NUM_LIT:0> , DISPLAY_HOME_AS_UP ) ; } @ Override public void setDisplayShowTitleEnabled ( boolean showTitle ) { setDisplayOptions ( showTitle ? DISPLAY_SHOW_TITLE : <NUM_LIT:0> , DISPLAY_SHOW_TITLE ) ; } @ Override public void setDisplayShowCustomEnabled ( boolean showCustom ) { setDisplayOptions ( showCustom ? DISPLAY_SHOW_CUSTOM : <NUM_LIT: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 ( "<STR_LIT>" ) ; } } 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 ) { 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 ( "<STR_LIT>" ) ; } tabi . setPosition ( position ) ; mTabs . add ( position , tabi ) ; final int count = mTabs . size ( ) ; for ( int i = position + <NUM_LIT: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 ) { return ; } int selectedTabPosition = mSelectedTab != null ? mSelectedTab . getPosition ( ) : mSavedTabPosition ; mTabScrollView . removeTabAt ( position ) ; TabImpl removedTab = mTabs . remove ( position ) ; if ( removedTab != null ) { removedTab . setPosition ( - <NUM_LIT: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 ( <NUM_LIT:0> , position - <NUM_LIT: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 ( <NUM_LIT:0> ) ; AnimatorSet anim = new AnimatorSet ( ) ; AnimatorSet . Builder b = anim . play ( ObjectAnimator . ofFloat ( mContainerView , "<STR_LIT>" , <NUM_LIT:1> ) ) ; if ( mContentView != null ) { b . with ( ObjectAnimator . ofFloat ( mContentView , "<STR_LIT>" , - mContainerView . getHeight ( ) , <NUM_LIT:0> ) ) ; mContainerView . setTranslationY ( - mContainerView . getHeight ( ) ) ; b . with ( ObjectAnimator . ofFloat ( mContainerView , "<STR_LIT>" , <NUM_LIT:0> ) ) ; } if ( mSplitView != null && mContextDisplayMode == CONTEXT_DISPLAY_SPLIT ) { mSplitView . setAlpha ( <NUM_LIT:0> ) ; mSplitView . setVisibility ( View . VISIBLE ) ; b . with ( ObjectAnimator . ofFloat ( mSplitView , "<STR_LIT>" , <NUM_LIT:1> ) ) ; } anim . addListener ( mShowListener ) ; mCurrentShowAnim = anim ; anim . start ( ) ; } else { mContainerView . setAlpha ( <NUM_LIT:1> ) ; mContainerView . setTranslationY ( <NUM_LIT:0> ) ; mShowListener . onAnimationEnd ( null ) ; } } @ Override public void hide ( ) { if ( mCurrentShowAnim != null ) { mCurrentShowAnim . end ( ) ; } if ( mContainerView . getVisibility ( ) == View . GONE ) { return ; } if ( mShowHideAnimationEnabled ) { mContainerView . setAlpha ( <NUM_LIT:1> ) ; mContainerView . setTransitioning ( true ) ; AnimatorSet anim = new AnimatorSet ( ) ; AnimatorSet . Builder b = anim . play ( ObjectAnimator . ofFloat ( mContainerView , "<STR_LIT>" , <NUM_LIT:0> ) ) ; if ( mContentView != null ) { b . with ( ObjectAnimator . ofFloat ( mContentView , "<STR_LIT>" , <NUM_LIT:0> , - mContainerView . getHeight ( ) ) ) ; b . with ( ObjectAnimator . ofFloat ( mContainerView , "<STR_LIT>" , - mContainerView . getHeight ( ) ) ) ; } if ( mSplitView != null && mSplitView . getVisibility ( ) == View . VISIBLE ) { mSplitView . setAlpha ( <NUM_LIT:1> ) ; b . with ( ObjectAnimator . ofFloat ( mSplitView , "<STR_LIT>" , <NUM_LIT: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 != <NUM_LIT:0> ) { mThemedContext = new ContextThemeWrapper ( mContext , targetThemeRes ) ; } else { mThemedContext = mContext ; } } return mThemedContext ; } 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 ) { return ; } if ( mWasHiddenBeforeMode ) { mDeferredDestroyActionMode = this ; mDeferredModeDestroyCallback = mCallback ; } else { mCallback . onDestroyActionMode ( this ) ; } mCallback = null ; animateToMode ( false ) ; 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 ( ) ; } } 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 = - <NUM_LIT: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 >= <NUM_LIT: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 >= <NUM_LIT: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 >= <NUM_LIT: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 >= <NUM_LIT: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 ( ) : - <NUM_LIT:1> ; case NAVIGATION_MODE_LIST : return mActionView . getDropdownSelectedPosition ( ) ; default : return - <NUM_LIT: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 ( ) : <NUM_LIT:0> ; default : return <NUM_LIT: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 ) ; } } </s>
|
<s> package com . actionbarsherlock . internal ; import com . actionbarsherlock . ActionBarSherlock ; import com . actionbarsherlock . app . ActionBar ; import com . actionbarsherlock . internal . app . ActionBarWrapper ; import com . actionbarsherlock . internal . view . menu . MenuWrapper ; import com . actionbarsherlock . view . ActionMode ; import com . actionbarsherlock . view . MenuInflater ; import android . app . Activity ; import android . content . Context ; import android . util . Log ; import android . util . TypedValue ; import android . view . ContextThemeWrapper ; import android . view . View ; import android . view . Window ; import android . view . ViewGroup . LayoutParams ; @ ActionBarSherlock . Implementation ( api = <NUM_LIT> ) public class ActionBarSherlockNative extends ActionBarSherlock { private ActionBarWrapper mActionBar ; private ActionModeWrapper mActionMode ; private MenuWrapper mMenu ; public ActionBarSherlockNative ( Activity activity , int flags ) { super ( activity , flags ) ; } @ Override public ActionBar getActionBar ( ) { if ( DEBUG ) Log . d ( TAG , "<STR_LIT>" ) ; initActionBar ( ) ; return mActionBar ; } private void initActionBar ( ) { if ( mActionBar != null || mActivity . getActionBar ( ) == null ) { return ; } mActionBar = new ActionBarWrapper ( mActivity ) ; } @ Override public void dispatchInvalidateOptionsMenu ( ) { if ( DEBUG ) Log . d ( TAG , "<STR_LIT>" ) ; mActivity . getWindow ( ) . invalidatePanelMenu ( Window . FEATURE_OPTIONS_PANEL ) ; } @ Override public boolean dispatchCreateOptionsMenu ( android . view . Menu menu ) { if ( DEBUG ) Log . d ( TAG , "<STR_LIT>" + menu ) ; if ( mMenu == null || menu != mMenu . unwrap ( ) ) { mMenu = new MenuWrapper ( menu ) ; } final boolean result = callbackCreateOptionsMenu ( mMenu ) ; if ( DEBUG ) Log . d ( TAG , "<STR_LIT>" + result ) ; return result ; } @ Override public boolean dispatchPrepareOptionsMenu ( android . view . Menu menu ) { if ( DEBUG ) Log . d ( TAG , "<STR_LIT>" + menu ) ; final boolean result = callbackPrepareOptionsMenu ( mMenu ) ; if ( DEBUG ) Log . d ( TAG , "<STR_LIT>" + result ) ; return result ; } @ Override public boolean dispatchOptionsItemSelected ( android . view . MenuItem item ) { if ( DEBUG ) Log . d ( TAG , "<STR_LIT>" + item . getTitleCondensed ( ) ) ; final boolean result = callbackOptionsItemSelected ( mMenu . findItem ( item ) ) ; if ( DEBUG ) Log . d ( TAG , "<STR_LIT>" + result ) ; return result ; } @ Override public boolean hasFeature ( int feature ) { if ( DEBUG ) Log . d ( TAG , "<STR_LIT>" + feature ) ; final boolean result = mActivity . getWindow ( ) . hasFeature ( feature ) ; if ( DEBUG ) Log . d ( TAG , "<STR_LIT>" + result ) ; return result ; } @ Override public boolean requestFeature ( int featureId ) { if ( DEBUG ) Log . d ( TAG , "<STR_LIT>" + featureId ) ; final boolean result = mActivity . getWindow ( ) . requestFeature ( featureId ) ; if ( DEBUG ) Log . d ( TAG , "<STR_LIT>" + result ) ; return result ; } @ Override public void setUiOptions ( int uiOptions ) { if ( DEBUG ) Log . d ( TAG , "<STR_LIT>" + uiOptions ) ; mActivity . getWindow ( ) . setUiOptions ( uiOptions ) ; } @ Override public void setUiOptions ( int uiOptions , int mask ) { if ( DEBUG ) Log . d ( TAG , "<STR_LIT>" + uiOptions + "<STR_LIT>" + mask ) ; mActivity . getWindow ( ) . setUiOptions ( uiOptions , mask ) ; } @ Override public void setContentView ( int layoutResId ) { if ( DEBUG ) Log . d ( TAG , "<STR_LIT>" + layoutResId ) ; mActivity . getWindow ( ) . setContentView ( layoutResId ) ; initActionBar ( ) ; } @ Override public void setContentView ( View view , LayoutParams params ) { if ( DEBUG ) Log . d ( TAG , "<STR_LIT>" + view + "<STR_LIT>" + params ) ; mActivity . getWindow ( ) . setContentView ( view , params ) ; initActionBar ( ) ; } @ Override public void addContentView ( View view , LayoutParams params ) { if ( DEBUG ) Log . d ( TAG , "<STR_LIT>" + view + "<STR_LIT>" + params ) ; mActivity . getWindow ( ) . addContentView ( view , params ) ; initActionBar ( ) ; } @ Override public void setTitle ( CharSequence title ) { if ( DEBUG ) Log . d ( TAG , "<STR_LIT>" + title ) ; mActivity . getWindow ( ) . setTitle ( title ) ; } @ Override public void setProgressBarVisibility ( boolean visible ) { if ( DEBUG ) Log . d ( TAG , "<STR_LIT>" + visible ) ; mActivity . setProgressBarVisibility ( visible ) ; } @ Override public void setProgressBarIndeterminateVisibility ( boolean visible ) { if ( DEBUG ) Log . d ( TAG , "<STR_LIT>" + visible ) ; mActivity . setProgressBarIndeterminateVisibility ( visible ) ; } @ Override public void setProgressBarIndeterminate ( boolean indeterminate ) { if ( DEBUG ) Log . d ( TAG , "<STR_LIT>" + indeterminate ) ; mActivity . setProgressBarIndeterminate ( indeterminate ) ; } @ Override public void setProgress ( int progress ) { if ( DEBUG ) Log . d ( TAG , "<STR_LIT>" + progress ) ; mActivity . setProgress ( progress ) ; } @ Override public void setSecondaryProgress ( int secondaryProgress ) { if ( DEBUG ) Log . d ( TAG , "<STR_LIT>" + secondaryProgress ) ; mActivity . setSecondaryProgress ( secondaryProgress ) ; } @ Override protected Context getThemedContext ( ) { Context context = mActivity ; TypedValue outValue = new TypedValue ( ) ; mActivity . getTheme ( ) . resolveAttribute ( android . R . attr . actionBarWidgetTheme , outValue , true ) ; if ( outValue . resourceId != <NUM_LIT:0> ) { context = new ContextThemeWrapper ( context , outValue . resourceId ) ; } return context ; } @ Override public ActionMode startActionMode ( com . actionbarsherlock . view . ActionMode . Callback callback ) { if ( DEBUG ) Log . d ( TAG , "<STR_LIT>" + callback ) ; if ( mActionMode != null ) { mActionMode . finish ( ) ; } ActionModeCallbackWrapper wrapped = null ; if ( callback != null ) { wrapped = new ActionModeCallbackWrapper ( callback ) ; } mActivity . startActionMode ( wrapped ) ; return mActionMode ; } private class ActionModeCallbackWrapper implements android . view . ActionMode . Callback { private final ActionMode . Callback mCallback ; public ActionModeCallbackWrapper ( ActionMode . Callback callback ) { mCallback = callback ; } @ Override public boolean onCreateActionMode ( android . view . ActionMode mode , android . view . Menu menu ) { mActionMode = new ActionModeWrapper ( mode ) ; return mCallback . onCreateActionMode ( mActionMode , mActionMode . getMenu ( ) ) ; } @ Override public boolean onPrepareActionMode ( android . view . ActionMode mode , android . view . Menu menu ) { return mCallback . onPrepareActionMode ( mActionMode , mActionMode . getMenu ( ) ) ; } @ Override public boolean onActionItemClicked ( android . view . ActionMode mode , android . view . MenuItem item ) { return mCallback . onActionItemClicked ( mActionMode , mActionMode . getMenu ( ) . findItem ( item ) ) ; } @ Override public void onDestroyActionMode ( android . view . ActionMode mode ) { mCallback . onDestroyActionMode ( mActionMode ) ; } } private class ActionModeWrapper extends ActionMode { private final android . view . ActionMode mActionMode ; private MenuWrapper mMenu = null ; ActionModeWrapper ( android . view . ActionMode actionMode ) { mActionMode = actionMode ; } @ Override public void setTitle ( CharSequence title ) { mActionMode . setTitle ( title ) ; } @ Override public void setTitle ( int resId ) { mActionMode . setTitle ( resId ) ; } @ Override public void setSubtitle ( CharSequence subtitle ) { mActionMode . setSubtitle ( subtitle ) ; } @ Override public void setSubtitle ( int resId ) { mActionMode . setSubtitle ( resId ) ; } @ Override public void setCustomView ( View view ) { mActionMode . setCustomView ( view ) ; } @ Override public void invalidate ( ) { mActionMode . invalidate ( ) ; } @ Override public void finish ( ) { mActionMode . finish ( ) ; } @ Override public MenuWrapper getMenu ( ) { if ( mMenu == null ) { mMenu = new MenuWrapper ( mActionMode . getMenu ( ) ) ; } return mMenu ; } @ Override public CharSequence getTitle ( ) { return mActionMode . getTitle ( ) ; } @ Override public CharSequence getSubtitle ( ) { return mActionMode . getSubtitle ( ) ; } @ Override public View getCustomView ( ) { return mActionMode . getCustomView ( ) ; } @ Override public MenuInflater getMenuInflater ( ) { return ActionBarSherlockNative . this . getMenuInflater ( ) ; } @ Override public void setTag ( Object tag ) { mActionMode . setTag ( tag ) ; } @ Override public Object getTag ( ) { return mActionMode . getTag ( ) ; } } } </s>
|
<s> package com . actionbarsherlock . internal ; import android . content . Context ; import android . os . Build ; import android . util . DisplayMetrics ; import com . actionbarsherlock . R ; public final class ResourcesCompat { private ResourcesCompat ( ) { } public static boolean getResources_getBoolean ( Context context , int id ) { if ( Build . VERSION . SDK_INT >= Build . VERSION_CODES . HONEYCOMB_MR2 ) { return context . getResources ( ) . getBoolean ( id ) ; } DisplayMetrics metrics = context . getResources ( ) . getDisplayMetrics ( ) ; float widthDp = metrics . widthPixels / metrics . density ; float heightDp = metrics . heightPixels / metrics . density ; float smallestWidthDp = ( widthDp < heightDp ) ? widthDp : heightDp ; if ( id == R . bool . abs__action_bar_embed_tabs ) { if ( widthDp >= <NUM_LIT> ) { return true ; } return false ; } if ( id == R . bool . abs__split_action_bar_is_narrow ) { if ( widthDp >= <NUM_LIT> ) { return false ; } return true ; } if ( id == R . bool . abs__action_bar_expanded_action_views_exclusive ) { if ( smallestWidthDp >= <NUM_LIT> ) { return false ; } return true ; } if ( id == R . bool . abs__config_allowActionMenuItemTextWithIcon ) { if ( widthDp >= <NUM_LIT> ) { return true ; } return false ; } throw new IllegalArgumentException ( "<STR_LIT>" + id ) ; } public static int getResources_getInteger ( Context context , int id ) { if ( Build . VERSION . SDK_INT >= Build . VERSION_CODES . HONEYCOMB_MR2 ) { return context . getResources ( ) . getInteger ( id ) ; } DisplayMetrics metrics = context . getResources ( ) . getDisplayMetrics ( ) ; float widthDp = metrics . widthPixels / metrics . density ; if ( id == R . integer . abs__max_action_buttons ) { if ( widthDp >= <NUM_LIT> ) { return <NUM_LIT:5> ; } if ( widthDp >= <NUM_LIT> ) { return <NUM_LIT:4> ; } if ( widthDp >= <NUM_LIT> ) { return <NUM_LIT:3> ; } return <NUM_LIT:2> ; } throw new IllegalArgumentException ( "<STR_LIT>" + id ) ; } } </s>
|
<s> 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 ; } 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 ) { } @ 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 ) ; } 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 ( ) ; } } @ 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 ; } @ 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 ) ; } 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 ) ; } } </s>
|
<s> 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 ; public abstract class ActionBar { public static final int NAVIGATION_MODE_STANDARD = android . app . ActionBar . NAVIGATION_MODE_STANDARD ; public static final int NAVIGATION_MODE_LIST = android . app . ActionBar . NAVIGATION_MODE_LIST ; public static final int NAVIGATION_MODE_TABS = android . app . ActionBar . NAVIGATION_MODE_TABS ; public static final int DISPLAY_USE_LOGO = android . app . ActionBar . DISPLAY_USE_LOGO ; public static final int DISPLAY_SHOW_HOME = android . app . ActionBar . DISPLAY_SHOW_HOME ; public static final int DISPLAY_HOME_AS_UP = android . app . ActionBar . DISPLAY_HOME_AS_UP ; public static final int DISPLAY_SHOW_TITLE = android . app . ActionBar . DISPLAY_SHOW_TITLE ; public static final int DISPLAY_SHOW_CUSTOM = android . app . ActionBar . DISPLAY_SHOW_CUSTOM ; public abstract void setCustomView ( View view ) ; public abstract void setCustomView ( View view , LayoutParams layoutParams ) ; public abstract void setCustomView ( int resId ) ; public abstract void setIcon ( int resId ) ; public abstract void setIcon ( Drawable icon ) ; public abstract void setLogo ( int resId ) ; public abstract void setLogo ( Drawable logo ) ; public abstract void setListNavigationCallbacks ( SpinnerAdapter adapter , OnNavigationListener callback ) ; public abstract void setSelectedNavigationItem ( int position ) ; public abstract int getSelectedNavigationIndex ( ) ; public abstract int getNavigationItemCount ( ) ; public abstract void setTitle ( CharSequence title ) ; public abstract void setTitle ( int resId ) ; public abstract void setSubtitle ( CharSequence subtitle ) ; public abstract void setSubtitle ( int resId ) ; public abstract void setDisplayOptions ( int options ) ; public abstract void setDisplayOptions ( int options , int mask ) ; public abstract void setDisplayUseLogoEnabled ( boolean useLogo ) ; public abstract void setDisplayShowHomeEnabled ( boolean showHome ) ; public abstract void setDisplayHomeAsUpEnabled ( boolean showHomeAsUp ) ; public abstract void setDisplayShowTitleEnabled ( boolean showTitle ) ; public abstract void setDisplayShowCustomEnabled ( boolean showCustom ) ; public abstract void setBackgroundDrawable ( Drawable d ) ; public void setStackedBackgroundDrawable ( Drawable d ) { } public void setSplitBackgroundDrawable ( Drawable d ) { } public abstract View getCustomView ( ) ; public abstract CharSequence getTitle ( ) ; public abstract CharSequence getSubtitle ( ) ; public abstract int getNavigationMode ( ) ; public abstract void setNavigationMode ( int mode ) ; public abstract int getDisplayOptions ( ) ; public abstract Tab newTab ( ) ; public abstract void addTab ( Tab tab ) ; public abstract void addTab ( Tab tab , boolean setSelected ) ; public abstract void addTab ( Tab tab , int position ) ; public abstract void addTab ( Tab tab , int position , boolean setSelected ) ; public abstract void removeTab ( Tab tab ) ; public abstract void removeTabAt ( int position ) ; public abstract void removeAllTabs ( ) ; public abstract void selectTab ( Tab tab ) ; public abstract Tab getSelectedTab ( ) ; public abstract Tab getTabAt ( int index ) ; public abstract int getTabCount ( ) ; public abstract int getHeight ( ) ; public abstract void show ( ) ; public abstract void hide ( ) ; public abstract boolean isShowing ( ) ; public abstract void addOnMenuVisibilityListener ( OnMenuVisibilityListener listener ) ; public abstract void removeOnMenuVisibilityListener ( OnMenuVisibilityListener listener ) ; public void setHomeButtonEnabled ( boolean enabled ) { } public Context getThemedContext ( ) { return null ; } public interface OnNavigationListener { public boolean onNavigationItemSelected ( int itemPosition , long itemId ) ; } public interface OnMenuVisibilityListener { public void onMenuVisibilityChanged ( boolean isVisible ) ; } public static abstract class Tab { public static final int INVALID_POSITION = - <NUM_LIT:1> ; public abstract int getPosition ( ) ; public abstract Drawable getIcon ( ) ; public abstract CharSequence getText ( ) ; public abstract Tab setIcon ( Drawable icon ) ; public abstract Tab setIcon ( int resId ) ; public abstract Tab setText ( CharSequence text ) ; public abstract Tab setText ( int resId ) ; public abstract Tab setCustomView ( View view ) ; public abstract Tab setCustomView ( int layoutResId ) ; public abstract View getCustomView ( ) ; public abstract Tab setTag ( Object obj ) ; public abstract Object getTag ( ) ; public abstract Tab setTabListener ( TabListener listener ) ; public abstract void select ( ) ; public abstract Tab setContentDescription ( int resId ) ; public abstract Tab setContentDescription ( CharSequence contentDesc ) ; public abstract CharSequence getContentDescription ( ) ; } public interface TabListener { public void onTabSelected ( Tab tab , FragmentTransaction ft ) ; public void onTabUnselected ( Tab tab , FragmentTransaction ft ) ; public void onTabReselected ( Tab tab , FragmentTransaction ft ) ; } public static class LayoutParams extends MarginLayoutParams { @ ViewDebug . ExportedProperty ( mapping = { @ ViewDebug . IntToString ( from = - <NUM_LIT:1> , to = "<STR_LIT>" ) , @ ViewDebug . IntToString ( from = Gravity . NO_GRAVITY , to = "<STR_LIT>" ) , @ ViewDebug . IntToString ( from = Gravity . TOP , to = "<STR_LIT>" ) , @ ViewDebug . IntToString ( from = Gravity . BOTTOM , to = "<STR_LIT>" ) , @ ViewDebug . IntToString ( from = Gravity . LEFT , to = "<STR_LIT>" ) , @ ViewDebug . IntToString ( from = Gravity . RIGHT , to = "<STR_LIT>" ) , @ ViewDebug . IntToString ( from = Gravity . CENTER_VERTICAL , to = "<STR_LIT>" ) , @ ViewDebug . IntToString ( from = Gravity . FILL_VERTICAL , to = "<STR_LIT>" ) , @ ViewDebug . IntToString ( from = Gravity . CENTER_HORIZONTAL , to = "<STR_LIT>" ) , @ ViewDebug . IntToString ( from = Gravity . FILL_HORIZONTAL , to = "<STR_LIT>" ) , @ ViewDebug . IntToString ( from = Gravity . CENTER , to = "<STR_LIT>" ) , @ ViewDebug . IntToString ( from = Gravity . FILL , to = "<STR_LIT>" ) } ) public int gravity = - <NUM_LIT: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 ) ; } } } </s>
|
<s> 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 ( ) + "<STR_LIT>" ) ; } 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 ) { } @ Override public final void onPrepareOptionsMenu ( android . view . Menu menu ) { onPrepareOptionsMenu ( new MenuWrapper ( menu ) ) ; } @ Override public void onPrepareOptionsMenu ( Menu menu ) { } @ Override public final boolean onOptionsItemSelected ( android . view . MenuItem item ) { return onOptionsItemSelected ( new MenuItemWrapper ( item ) ) ; } @ Override public boolean onOptionsItemSelected ( MenuItem item ) { return false ; } } </s>
|
<s> 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 ; } 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 ) { } @ 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 ) ; } 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 ( ) ; } } @ 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 ; } @ 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 ) ; } 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 ) ; } } </s>
|
<s> 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 ; public class SherlockFragmentActivity extends _ActionBarSherlockTrojanHorse implements OnActionModeStartedListener , OnActionModeFinishedListener { private static final boolean DEBUG = false ; private static final String TAG = "<STR_LIT>" ; 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 ; } 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 ) { } @ 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 ) ; } public MenuInflater getSupportMenuInflater ( ) { if ( DEBUG ) Log . d ( TAG , "<STR_LIT>" ) ; return getSherlock ( ) . getMenuInflater ( ) ; } public void invalidateOptionsMenu ( ) { if ( DEBUG ) Log . d ( TAG , "<STR_LIT>" ) ; getSherlock ( ) . dispatchInvalidateOptionsMenu ( ) ; } public void supportInvalidateOptionsMenu ( ) { if ( DEBUG ) Log . d ( TAG , "<STR_LIT>" ) ; invalidateOptionsMenu ( ) ; } @ Override public final boolean onCreatePanelMenu ( int featureId , android . view . Menu menu ) { if ( DEBUG ) Log . d ( TAG , "<STR_LIT>" + featureId + "<STR_LIT>" + menu ) ; if ( featureId == Window . FEATURE_OPTIONS_PANEL && ! mIgnoreNativeCreate ) { mIgnoreNativeCreate = true ; boolean result = getSherlock ( ) . dispatchCreateOptionsMenu ( menu ) ; mIgnoreNativeCreate = false ; if ( DEBUG ) Log . d ( TAG , "<STR_LIT>" + 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 , "<STR_LIT>" + featureId + "<STR_LIT>" + view + "<STR_LIT>" + menu ) ; if ( featureId == Window . FEATURE_OPTIONS_PANEL && ! mIgnoreNativePrepare ) { mIgnoreNativePrepare = true ; boolean result = getSherlock ( ) . dispatchPrepareOptionsMenu ( menu ) ; mIgnoreNativePrepare = false ; if ( DEBUG ) Log . d ( TAG , "<STR_LIT>" + 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 , "<STR_LIT>" + featureId + "<STR_LIT>" + item ) ; if ( featureId == Window . FEATURE_OPTIONS_PANEL && ! mIgnoreNativeSelected ) { mIgnoreNativeSelected = true ; boolean result = getSherlock ( ) . dispatchOptionsItemSelected ( item ) ; mIgnoreNativeSelected = false ; if ( DEBUG ) Log . d ( TAG , "<STR_LIT>" + 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 ( ) ; } } public boolean onCreateOptionsMenu ( Menu menu ) { return true ; } public boolean onPrepareOptionsMenu ( Menu menu ) { return true ; } public boolean onOptionsItemSelected ( MenuItem item ) { return false ; } @ 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 ) ; } 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 ) ; } } </s>
|
<s> 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 ( ) + "<STR_LIT>" ) ; } 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 ) { } @ Override public final void onPrepareOptionsMenu ( android . view . Menu menu ) { onPrepareOptionsMenu ( new MenuWrapper ( menu ) ) ; } @ Override public void onPrepareOptionsMenu ( Menu menu ) { } @ Override public final boolean onOptionsItemSelected ( android . view . MenuItem item ) { return onOptionsItemSelected ( new MenuItemWrapper ( item ) ) ; } @ Override public boolean onOptionsItemSelected ( MenuItem item ) { return false ; } } </s>
|
<s> 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 ; } 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 ) { } @ 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 ) ; } 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 ( ) ; } } @ 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 ; } @ 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 ) ; } 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 ) ; } } </s>
|
<s> 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 ; } 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 ) { } @ 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 ) ; } 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 ( ) ; } } @ 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 ; } @ 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 ) ; } 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 ) ; } } </s>
|
<s> 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 ( ) + "<STR_LIT>" ) ; } 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 ) { } @ Override public final void onPrepareOptionsMenu ( android . view . Menu menu ) { onPrepareOptionsMenu ( new MenuWrapper ( menu ) ) ; } @ Override public void onPrepareOptionsMenu ( Menu menu ) { } @ Override public final boolean onOptionsItemSelected ( android . view . MenuItem item ) { return onOptionsItemSelected ( new MenuItemWrapper ( item ) ) ; } @ Override public boolean onOptionsItemSelected ( MenuItem item ) { return false ; } } </s>
|
<s> package com . actionbarsherlock ; import static android . view . ViewGroup . LayoutParams . MATCH_PARENT ; import java . lang . annotation . ElementType ; import java . lang . annotation . Retention ; import java . lang . annotation . RetentionPolicy ; import java . lang . annotation . Target ; import java . lang . reflect . Constructor ; import java . lang . reflect . InvocationTargetException ; import java . util . HashMap ; import java . util . Iterator ; import android . app . Activity ; import android . content . Context ; import android . content . res . Configuration ; import android . os . Build ; import android . os . Bundle ; import android . util . DisplayMetrics ; import android . util . Log ; import android . view . KeyEvent ; import android . view . View ; import android . view . ViewGroup ; import android . view . Window ; import com . actionbarsherlock . app . ActionBar ; import com . actionbarsherlock . internal . ActionBarSherlockCompat ; import com . actionbarsherlock . internal . ActionBarSherlockNative ; import com . actionbarsherlock . view . ActionMode ; import com . actionbarsherlock . view . Menu ; import com . actionbarsherlock . view . MenuInflater ; import com . actionbarsherlock . view . MenuItem ; public abstract class ActionBarSherlock { protected static final String TAG = "<STR_LIT>" ; protected static final boolean DEBUG = false ; private static final Class < ? > [ ] CONSTRUCTOR_ARGS = new Class [ ] { Activity . class , int . class } ; private static final HashMap < Implementation , Class < ? extends ActionBarSherlock > > IMPLEMENTATIONS = new HashMap < Implementation , Class < ? extends ActionBarSherlock > > ( ) ; static { registerImplementation ( ActionBarSherlockCompat . class ) ; registerImplementation ( ActionBarSherlockNative . class ) ; } @ Target ( ElementType . TYPE ) @ Retention ( RetentionPolicy . RUNTIME ) public @ interface Implementation { static final int DEFAULT_API = - <NUM_LIT:1> ; static final int DEFAULT_DPI = - <NUM_LIT:1> ; int api ( ) default DEFAULT_API ; int dpi ( ) default DEFAULT_DPI ; } public interface OnCreatePanelMenuListener { public boolean onCreatePanelMenu ( int featureId , Menu menu ) ; } public interface OnCreateOptionsMenuListener { public boolean onCreateOptionsMenu ( Menu menu ) ; } public interface OnMenuItemSelectedListener { public boolean onMenuItemSelected ( int featureId , MenuItem item ) ; } public interface OnOptionsItemSelectedListener { public boolean onOptionsItemSelected ( MenuItem item ) ; } public interface OnPreparePanelListener { public boolean onPreparePanel ( int featureId , View view , Menu menu ) ; } public interface OnPrepareOptionsMenuListener { public boolean onPrepareOptionsMenu ( Menu menu ) ; } public interface OnActionModeFinishedListener { public void onActionModeFinished ( ActionMode mode ) ; } public interface OnActionModeStartedListener { public void onActionModeStarted ( ActionMode mode ) ; } public static final int FLAG_DELEGATE = <NUM_LIT:1> ; public static void registerImplementation ( Class < ? extends ActionBarSherlock > implementationClass ) { if ( ! implementationClass . isAnnotationPresent ( Implementation . class ) ) { throw new IllegalArgumentException ( "<STR_LIT>" + implementationClass . getSimpleName ( ) + "<STR_LIT>" ) ; } else if ( IMPLEMENTATIONS . containsValue ( implementationClass ) ) { if ( DEBUG ) Log . w ( TAG , "<STR_LIT>" + implementationClass . getSimpleName ( ) + "<STR_LIT>" ) ; return ; } Implementation impl = implementationClass . getAnnotation ( Implementation . class ) ; if ( DEBUG ) Log . i ( TAG , "<STR_LIT>" + implementationClass . getSimpleName ( ) + "<STR_LIT>" + impl ) ; IMPLEMENTATIONS . put ( impl , implementationClass ) ; } public static boolean unregisterImplementation ( Class < ? extends ActionBarSherlock > implementationClass ) { return IMPLEMENTATIONS . values ( ) . remove ( implementationClass ) ; } public static ActionBarSherlock wrap ( Activity activity ) { return wrap ( activity , <NUM_LIT:0> ) ; } public static ActionBarSherlock wrap ( Activity activity , int flags ) { HashMap < Implementation , Class < ? extends ActionBarSherlock > > impls = new HashMap < Implementation , Class < ? extends ActionBarSherlock > > ( IMPLEMENTATIONS ) ; boolean hasQualfier ; hasQualfier = false ; for ( Implementation key : impls . keySet ( ) ) { if ( key . dpi ( ) == DisplayMetrics . DENSITY_TV ) { hasQualfier = true ; break ; } } if ( hasQualfier ) { final boolean isTvDpi = activity . getResources ( ) . getDisplayMetrics ( ) . densityDpi == DisplayMetrics . DENSITY_TV ; for ( Iterator < Implementation > keys = impls . keySet ( ) . iterator ( ) ; keys . hasNext ( ) ; ) { int keyDpi = keys . next ( ) . dpi ( ) ; if ( ( isTvDpi && keyDpi != DisplayMetrics . DENSITY_TV ) || ( ! isTvDpi && keyDpi == DisplayMetrics . DENSITY_TV ) ) { keys . remove ( ) ; } } } hasQualfier = false ; for ( Implementation key : impls . keySet ( ) ) { if ( key . api ( ) != Implementation . DEFAULT_API ) { hasQualfier = true ; break ; } } if ( hasQualfier ) { final int runtimeApi = Build . VERSION . SDK_INT ; int bestApi = <NUM_LIT:0> ; for ( Iterator < Implementation > keys = impls . keySet ( ) . iterator ( ) ; keys . hasNext ( ) ; ) { int keyApi = keys . next ( ) . api ( ) ; if ( keyApi > runtimeApi ) { keys . remove ( ) ; } else if ( keyApi > bestApi ) { bestApi = keyApi ; } } for ( Iterator < Implementation > keys = impls . keySet ( ) . iterator ( ) ; keys . hasNext ( ) ; ) { if ( keys . next ( ) . api ( ) != bestApi ) { keys . remove ( ) ; } } } if ( impls . size ( ) > <NUM_LIT:1> ) { throw new IllegalStateException ( "<STR_LIT>" ) ; } if ( impls . isEmpty ( ) ) { throw new IllegalStateException ( "<STR_LIT>" ) ; } Class < ? extends ActionBarSherlock > impl = impls . values ( ) . iterator ( ) . next ( ) ; if ( DEBUG ) Log . i ( TAG , "<STR_LIT>" + impl . getSimpleName ( ) ) ; try { Constructor < ? extends ActionBarSherlock > ctor = impl . getConstructor ( CONSTRUCTOR_ARGS ) ; return ctor . newInstance ( activity , flags ) ; } catch ( NoSuchMethodException e ) { throw new RuntimeException ( e ) ; } catch ( IllegalArgumentException e ) { throw new RuntimeException ( e ) ; } catch ( InstantiationException e ) { throw new RuntimeException ( e ) ; } catch ( IllegalAccessException e ) { throw new RuntimeException ( e ) ; } catch ( InvocationTargetException e ) { throw new RuntimeException ( e ) ; } } protected final Activity mActivity ; protected final boolean mIsDelegate ; protected MenuInflater mMenuInflater ; protected ActionBarSherlock ( Activity activity , int flags ) { if ( DEBUG ) Log . d ( TAG , "<STR_LIT>" + activity + "<STR_LIT>" + flags ) ; mActivity = activity ; mIsDelegate = ( flags & FLAG_DELEGATE ) != <NUM_LIT:0> ; } public abstract ActionBar getActionBar ( ) ; public void dispatchConfigurationChanged ( Configuration newConfig ) { } public void dispatchPostResume ( ) { } public void dispatchPause ( ) { } public void dispatchStop ( ) { } public abstract void dispatchInvalidateOptionsMenu ( ) ; public boolean dispatchOpenOptionsMenu ( ) { return false ; } public boolean dispatchCloseOptionsMenu ( ) { return false ; } public void dispatchPostCreate ( Bundle savedInstanceState ) { } public void dispatchTitleChanged ( CharSequence title , int color ) { } public boolean dispatchKeyEvent ( KeyEvent event ) { return false ; } public abstract boolean dispatchCreateOptionsMenu ( android . view . Menu menu ) ; public abstract boolean dispatchPrepareOptionsMenu ( android . view . Menu menu ) ; public abstract boolean dispatchOptionsItemSelected ( android . view . MenuItem item ) ; public boolean dispatchMenuOpened ( int featureId , android . view . Menu menu ) { return false ; } public void dispatchPanelClosed ( int featureId , android . view . Menu menu ) { } public void dispatchDestroy ( ) { } protected final boolean callbackCreateOptionsMenu ( Menu menu ) { if ( DEBUG ) Log . d ( TAG , "<STR_LIT>" + menu ) ; boolean result = true ; if ( mActivity instanceof OnCreatePanelMenuListener ) { OnCreatePanelMenuListener listener = ( OnCreatePanelMenuListener ) mActivity ; result = listener . onCreatePanelMenu ( Window . FEATURE_OPTIONS_PANEL , menu ) ; } else if ( mActivity instanceof OnCreateOptionsMenuListener ) { OnCreateOptionsMenuListener listener = ( OnCreateOptionsMenuListener ) mActivity ; result = listener . onCreateOptionsMenu ( menu ) ; } if ( DEBUG ) Log . d ( TAG , "<STR_LIT>" + result ) ; return result ; } protected final boolean callbackPrepareOptionsMenu ( Menu menu ) { if ( DEBUG ) Log . d ( TAG , "<STR_LIT>" + menu ) ; boolean result = true ; if ( mActivity instanceof OnPreparePanelListener ) { OnPreparePanelListener listener = ( OnPreparePanelListener ) mActivity ; result = listener . onPreparePanel ( Window . FEATURE_OPTIONS_PANEL , null , menu ) ; } else if ( mActivity instanceof OnPrepareOptionsMenuListener ) { OnPrepareOptionsMenuListener listener = ( OnPrepareOptionsMenuListener ) mActivity ; result = listener . onPrepareOptionsMenu ( menu ) ; } if ( DEBUG ) Log . d ( TAG , "<STR_LIT>" + result ) ; return result ; } protected final boolean callbackOptionsItemSelected ( MenuItem item ) { if ( DEBUG ) Log . d ( TAG , "<STR_LIT>" + item . getTitleCondensed ( ) ) ; boolean result = false ; if ( mActivity instanceof OnMenuItemSelectedListener ) { OnMenuItemSelectedListener listener = ( OnMenuItemSelectedListener ) mActivity ; result = listener . onMenuItemSelected ( Window . FEATURE_OPTIONS_PANEL , item ) ; } else if ( mActivity instanceof OnOptionsItemSelectedListener ) { OnOptionsItemSelectedListener listener = ( OnOptionsItemSelectedListener ) mActivity ; result = listener . onOptionsItemSelected ( item ) ; } if ( DEBUG ) Log . d ( TAG , "<STR_LIT>" + result ) ; return result ; } public abstract boolean hasFeature ( int featureId ) ; public abstract boolean requestFeature ( int featureId ) ; public abstract void setUiOptions ( int uiOptions ) ; public abstract void setUiOptions ( int uiOptions , int mask ) ; public abstract void setContentView ( int layoutResId ) ; public void setContentView ( View view ) { if ( DEBUG ) Log . d ( TAG , "<STR_LIT>" + view ) ; setContentView ( view , new ViewGroup . LayoutParams ( MATCH_PARENT , MATCH_PARENT ) ) ; } public abstract void setContentView ( View view , ViewGroup . LayoutParams params ) ; public abstract void addContentView ( View view , ViewGroup . LayoutParams params ) ; public abstract void setTitle ( CharSequence title ) ; public void setTitle ( int resId ) { if ( DEBUG ) Log . d ( TAG , "<STR_LIT>" + resId ) ; setTitle ( mActivity . getString ( resId ) ) ; } public abstract void setProgressBarVisibility ( boolean visible ) ; public abstract void setProgressBarIndeterminateVisibility ( boolean visible ) ; public abstract void setProgressBarIndeterminate ( boolean indeterminate ) ; public abstract void setProgress ( int progress ) ; public abstract void setSecondaryProgress ( int secondaryProgress ) ; public MenuInflater getMenuInflater ( ) { if ( DEBUG ) Log . d ( TAG , "<STR_LIT>" ) ; if ( mMenuInflater == null ) { if ( getActionBar ( ) != null ) { mMenuInflater = new MenuInflater ( getThemedContext ( ) ) ; } else { mMenuInflater = new MenuInflater ( mActivity ) ; } } return mMenuInflater ; } protected abstract Context getThemedContext ( ) ; public abstract ActionMode startActionMode ( ActionMode . Callback callback ) ; } </s>
|
<s> 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 ; class ActivityChooserModel extends DataSetObservable { public interface ActivityChooserModelClient { public void setActivityChooserModel ( ActivityChooserModel dataModel ) ; } public interface ActivitySorter { public void sort ( Intent intent , List < ActivityResolveInfo > activities , List < HistoricalRecord > historicalRecords ) ; } public interface OnChooseActivityListener { public boolean onChooseActivity ( ActivityChooserModel host , Intent intent ) ; } private static final boolean DEBUG = false ; private static final String LOG_TAG = ActivityChooserModel . class . getSimpleName ( ) ; private static final String TAG_HISTORICAL_RECORDS = "<STR_LIT>" ; private static final String TAG_HISTORICAL_RECORD = "<STR_LIT>" ; private static final String ATTRIBUTE_ACTIVITY = "<STR_LIT>" ; private static final String ATTRIBUTE_TIME = "<STR_LIT>" ; private static final String ATTRIBUTE_WEIGHT = "<STR_LIT>" ; public static final String DEFAULT_HISTORY_FILE_NAME = "<STR_LIT>" ; public static final int DEFAULT_HISTORY_MAX_LENGTH = <NUM_LIT> ; private static final int DEFAULT_ACTIVITY_INFLATION = <NUM_LIT:5> ; private static final float DEFAULT_HISTORICAL_RECORD_WEIGHT = <NUM_LIT:1.0f> ; private static final String HISTORY_FILE_EXTENSION = "<STR_LIT>" ; private static final int INVALID_INDEX = - <NUM_LIT:1> ; private static final Object sRegistryLock = new Object ( ) ; private static final Map < String , ActivityChooserModel > sDataModelRegistry = new HashMap < String , ActivityChooserModel > ( ) ; private final Object mInstanceLock = new Object ( ) ; private final List < ActivityResolveInfo > mActivites = new ArrayList < ActivityResolveInfo > ( ) ; private final List < HistoricalRecord > mHistoricalRecords = new ArrayList < HistoricalRecord > ( ) ; private final Context mContext ; private final String mHistoryFileName ; private Intent mIntent ; private ActivitySorter mActivitySorter = new DefaultSorter ( ) ; private int mHistoryMaxSize = DEFAULT_HISTORY_MAX_LENGTH ; private boolean mCanReadHistoricalData = true ; private boolean mReadShareHistoryCalled = false ; private boolean mHistoricalRecordsChanged = true ; private final Handler mHandler = new Handler ( ) ; private OnChooseActivityListener mActivityChoserModelPolicy ; 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 ; } } 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 ; } } public void setIntent ( Intent intent ) { synchronized ( mInstanceLock ) { if ( mIntent == intent ) { return ; } mIntent = intent ; loadActivitiesLocked ( ) ; } } public Intent getIntent ( ) { synchronized ( mInstanceLock ) { return mIntent ; } } public int getActivityCount ( ) { synchronized ( mInstanceLock ) { return mActivites . size ( ) ; } } public ResolveInfo getActivity ( int index ) { synchronized ( mInstanceLock ) { return mActivites . get ( index ) . resolveInfo ; } } public int getActivityIndex ( ResolveInfo activity ) { List < ActivityResolveInfo > activities = mActivites ; final int activityCount = activities . size ( ) ; for ( int i = <NUM_LIT:0> ; i < activityCount ; i ++ ) { ActivityResolveInfo currentActivity = activities . get ( i ) ; if ( currentActivity . resolveInfo == activity ) { return i ; } } return INVALID_INDEX ; } 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 ) { 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 ; } public void setOnChooseActivityListener ( OnChooseActivityListener listener ) { mActivityChoserModelPolicy = listener ; } public ResolveInfo getDefaultActivity ( ) { synchronized ( mInstanceLock ) { if ( ! mActivites . isEmpty ( ) ) { return mActivites . get ( <NUM_LIT:0> ) . resolveInfo ; } } return null ; } public void setDefaultActivity ( int index ) { ActivityResolveInfo newDefaultActivity = mActivites . get ( index ) ; ActivityResolveInfo oldDefaultActivity = mActivites . get ( <NUM_LIT:0> ) ; final float weight ; if ( oldDefaultActivity != null ) { 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 ) ; } private void readHistoricalData ( ) { synchronized ( mInstanceLock ) { if ( ! mCanReadHistoricalData || ! mHistoricalRecordsChanged ) { return ; } mCanReadHistoricalData = false ; mReadShareHistoryCalled = true ; if ( ! TextUtils . isEmpty ( mHistoryFileName ) ) { 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 ( ) ; } } } private void persistHistoricalData ( ) { synchronized ( mInstanceLock ) { if ( ! mReadShareHistoryCalled ) { throw new IllegalStateException ( "<STR_LIT>" ) ; } if ( ! mHistoricalRecordsChanged ) { return ; } mHistoricalRecordsChanged = false ; mCanReadHistoricalData = true ; if ( ! TextUtils . isEmpty ( mHistoryFileName ) ) { SERIAL_EXECUTOR . execute ( new HistoryPersister ( ) ) ; } } } public void setActivitySorter ( ActivitySorter activitySorter ) { synchronized ( mInstanceLock ) { if ( mActivitySorter == activitySorter ) { return ; } mActivitySorter = activitySorter ; sortActivities ( ) ; } } private void sortActivities ( ) { synchronized ( mInstanceLock ) { if ( mActivitySorter != null && ! mActivites . isEmpty ( ) ) { mActivitySorter . sort ( mIntent , mActivites , Collections . unmodifiableList ( mHistoricalRecords ) ) ; notifyChanged ( ) ; } } } public void setHistoryMaxSize ( int historyMaxSize ) { synchronized ( mInstanceLock ) { if ( mHistoryMaxSize == historyMaxSize ) { return ; } mHistoryMaxSize = historyMaxSize ; pruneExcessiveHistoricalRecordsLocked ( ) ; sortActivities ( ) ; } } public int getHistoryMaxSize ( ) { synchronized ( mInstanceLock ) { return mHistoryMaxSize ; } } public int getHistorySize ( ) { synchronized ( mInstanceLock ) { return mHistoricalRecords . size ( ) ; } } private boolean addHisoricalRecord ( HistoricalRecord historicalRecord ) { synchronized ( mInstanceLock ) { final boolean added = mHistoricalRecords . add ( historicalRecord ) ; if ( added ) { mHistoricalRecordsChanged = true ; pruneExcessiveHistoricalRecordsLocked ( ) ; persistHistoricalData ( ) ; sortActivities ( ) ; } return added ; } } private void pruneExcessiveHistoricalRecordsLocked ( ) { List < HistoricalRecord > choiceRecords = mHistoricalRecords ; final int pruneCount = choiceRecords . size ( ) - mHistoryMaxSize ; if ( pruneCount <= <NUM_LIT:0> ) { return ; } mHistoricalRecordsChanged = true ; for ( int i = <NUM_LIT:0> ; i < pruneCount ; i ++ ) { HistoricalRecord prunedRecord = choiceRecords . remove ( <NUM_LIT:0> ) ; if ( DEBUG ) { Log . i ( LOG_TAG , "<STR_LIT>" + prunedRecord ) ; } } } private void loadActivitiesLocked ( ) { mActivites . clear ( ) ; if ( mIntent != null ) { List < ResolveInfo > resolveInfos = mContext . getPackageManager ( ) . queryIntentActivities ( mIntent , <NUM_LIT:0> ) ; final int resolveInfoCount = resolveInfos . size ( ) ; for ( int i = <NUM_LIT:0> ; i < resolveInfoCount ; i ++ ) { ResolveInfo resolveInfo = resolveInfos . get ( i ) ; mActivites . add ( new ActivityResolveInfo ( resolveInfo ) ) ; } sortActivities ( ) ; } else { notifyChanged ( ) ; } } public final static class HistoricalRecord { public final ComponentName activity ; public final long time ; public final float weight ; public HistoricalRecord ( String activityName , long time , float weight ) { this ( ComponentName . unflattenFromString ( activityName ) , time , weight ) ; } public HistoricalRecord ( ComponentName activityName , long time , float weight ) { this . activity = activityName ; this . time = time ; this . weight = weight ; } @ Override public int hashCode ( ) { final int prime = <NUM_LIT:31> ; int result = <NUM_LIT:1> ; result = prime * result + ( ( activity == null ) ? <NUM_LIT:0> : activity . hashCode ( ) ) ; result = prime * result + ( int ) ( time ^ ( time > > > <NUM_LIT: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 ( "<STR_LIT:[>" ) ; builder . append ( "<STR_LIT>" ) . append ( activity ) ; builder . append ( "<STR_LIT>" ) . append ( time ) ; builder . append ( "<STR_LIT>" ) . append ( new BigDecimal ( weight ) ) ; builder . append ( "<STR_LIT:]>" ) ; return builder . toString ( ) ; } } public final class ActivityResolveInfo implements Comparable < ActivityResolveInfo > { public final ResolveInfo resolveInfo ; public float weight ; public ActivityResolveInfo ( ResolveInfo resolveInfo ) { this . resolveInfo = resolveInfo ; } @ Override public int hashCode ( ) { return <NUM_LIT: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 ( "<STR_LIT:[>" ) ; builder . append ( "<STR_LIT>" ) . append ( resolveInfo . toString ( ) ) ; builder . append ( "<STR_LIT>" ) . append ( new BigDecimal ( weight ) ) ; builder . append ( "<STR_LIT:]>" ) ; return builder . toString ( ) ; } } private final class DefaultSorter implements ActivitySorter { private static final float WEIGHT_DECAY_COEFFICIENT = <NUM_LIT> ; 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 = <NUM_LIT:0> ; i < activityCount ; i ++ ) { ActivityResolveInfo activity = activities . get ( i ) ; activity . weight = <NUM_LIT:0.0f> ; String packageName = activity . resolveInfo . activityInfo . packageName ; packageNameToActivityMap . put ( packageName , activity ) ; } final int lastShareIndex = historicalRecords . size ( ) - <NUM_LIT:1> ; float nextRecordWeight = <NUM_LIT:1> ; for ( int i = lastShareIndex ; i >= <NUM_LIT: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 = <NUM_LIT:0> ; i < activityCount ; i ++ ) { Log . i ( LOG_TAG , "<STR_LIT>" + activities . get ( i ) ) ; } } } } 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 , "<STR_LIT>" + 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 ( "<STR_LIT>" + TAG_HISTORICAL_RECORDS + "<STR_LIT>" ) ; } 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 ( "<STR_LIT>" ) ; } 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 , "<STR_LIT>" + readRecord . toString ( ) ) ; } } if ( DEBUG ) { Log . i ( LOG_TAG , "<STR_LIT>" + readRecords . size ( ) + "<STR_LIT>" ) ; } synchronized ( mInstanceLock ) { Set < HistoricalRecord > uniqueShareRecords = new LinkedHashSet < HistoricalRecord > ( readRecords ) ; List < HistoricalRecord > historicalRecords = mHistoricalRecords ; final int historicalRecordsCount = historicalRecords . size ( ) ; for ( int i = historicalRecordsCount - <NUM_LIT:1> ; i >= <NUM_LIT:0> ; i -- ) { HistoricalRecord historicalRecord = historicalRecords . get ( i ) ; uniqueShareRecords . add ( historicalRecord ) ; } if ( historicalRecords . size ( ) == uniqueShareRecords . size ( ) ) { return ; } historicalRecords . clear ( ) ; historicalRecords . addAll ( uniqueShareRecords ) ; mHistoricalRecordsChanged = true ; mHandler . post ( new Runnable ( ) { public void run ( ) { pruneExcessiveHistoricalRecordsLocked ( ) ; sortActivities ( ) ; } } ) ; } } catch ( XmlPullParserException xppe ) { Log . e ( LOG_TAG , "<STR_LIT>" + mHistoryFileName , xppe ) ; } catch ( IOException ioe ) { Log . e ( LOG_TAG , "<STR_LIT>" + mHistoryFileName , ioe ) ; } finally { if ( fis != null ) { try { fis . close ( ) ; } catch ( IOException ioe ) { } } } } } 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 , "<STR_LIT>" + mHistoryFileName , fnfe ) ; return ; } XmlSerializer serializer = Xml . newSerializer ( ) ; try { serializer . setOutput ( fos , null ) ; serializer . startDocument ( "<STR_LIT:UTF-8>" , true ) ; serializer . startTag ( null , TAG_HISTORICAL_RECORDS ) ; final int recordCount = records . size ( ) ; for ( int i = <NUM_LIT:0> ; i < recordCount ; i ++ ) { HistoricalRecord record = records . remove ( <NUM_LIT: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 , "<STR_LIT>" + record . toString ( ) ) ; } } serializer . endTag ( null , TAG_HISTORICAL_RECORDS ) ; serializer . endDocument ( ) ; if ( DEBUG ) { Log . i ( LOG_TAG , "<STR_LIT>" + recordCount + "<STR_LIT>" ) ; } } catch ( IllegalArgumentException iae ) { Log . e ( LOG_TAG , "<STR_LIT>" + mHistoryFileName , iae ) ; } catch ( IllegalStateException ise ) { Log . e ( LOG_TAG , "<STR_LIT>" + mHistoryFileName , ise ) ; } catch ( IOException ioe ) { Log . e ( LOG_TAG , "<STR_LIT>" + mHistoryFileName , ioe ) ; } finally { if ( fos != null ) { try { fos . close ( ) ; } catch ( IOException e ) { } } } } } } </s>
|
<s> 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 ; class ActivityChooserView extends ViewGroup implements ActivityChooserModelClient { private final ActivityChooserViewAdapter mAdapter ; private final Callbacks mCallbacks ; private final IcsLinearLayout mActivityChooserContent ; private final Drawable mActivityChooserContentBackground ; private final FrameLayout mExpandActivityOverflowButton ; private final ImageView mExpandActivityOverflowButtonImage ; private final FrameLayout mDefaultActivityButton ; private final ImageView mDefaultActivityButtonImage ; private final int mListPopupMaxWidth ; ActionProvider mProvider ; 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 ) ; } } } } } ; private IcsListPopupWindow mListPopupWindow ; private PopupWindow . OnDismissListener mOnDismissListener ; private boolean mIsSelectingDefaultActivity ; private int mInitialActivityCount = ActivityChooserViewAdapter . MAX_ACTIVITY_COUNT_DEFAULT ; private boolean mIsAttachedToWindow ; private int mDefaultActionButtonContentDescription ; private final Context mContext ; public ActivityChooserView ( Context context ) { this ( context , null ) ; } public ActivityChooserView ( Context context , AttributeSet attrs ) { this ( context , attrs , <NUM_LIT:0> ) ; } public ActivityChooserView ( Context context , AttributeSet attrs , int defStyle ) { super ( context , attrs , defStyle ) ; mContext = context ; TypedArray attributesArray = context . obtainStyledAttributes ( attrs , R . styleable . SherlockActivityChooserView , defStyle , <NUM_LIT: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 / <NUM_LIT:2> , resources . getDimensionPixelSize ( R . dimen . abs__config_prefDialogWidth ) ) ; } public void setActivityChooserModel ( ActivityChooserModel dataModel ) { mAdapter . setDataModel ( dataModel ) ; if ( isShowingPopup ( ) ) { dismissPopup ( ) ; showPopup ( ) ; } } public void setExpandActivityOverflowButtonDrawable ( Drawable drawable ) { mExpandActivityOverflowButtonImage . setImageDrawable ( drawable ) ; } public void setExpandActivityOverflowButtonContentDescription ( int resourceId ) { CharSequence contentDescription = mContext . getString ( resourceId ) ; mExpandActivityOverflowButtonImage . setContentDescription ( contentDescription ) ; } public void setProvider ( ActionProvider provider ) { mProvider = provider ; } public boolean showPopup ( ) { if ( isShowingPopup ( ) || ! mIsAttachedToWindow ) { return false ; } mIsSelectingDefaultActivity = false ; showPopupUnchecked ( mInitialActivityCount ) ; return true ; } private void showPopupUnchecked ( int maxActivityCount ) { if ( mAdapter . getDataModel ( ) == null ) { throw new IllegalStateException ( "<STR_LIT>" ) ; } getViewTreeObserver ( ) . addOnGlobalLayoutListener ( mOnGlobalLayoutListener ) ; final boolean defaultActivityButtonShown = mDefaultActivityButton . getVisibility ( ) == VISIBLE ; final int activityCount = mAdapter . getActivityCount ( ) ; final int maxActivityCountOffset = defaultActivityButtonShown ? <NUM_LIT:1> : <NUM_LIT:0> ; if ( maxActivityCount != ActivityChooserViewAdapter . MAX_ACTIVITY_COUNT_UNLIMITED && activityCount > maxActivityCount + maxActivityCountOffset ) { mAdapter . setShowFooterView ( true ) ; mAdapter . setMaxActivityCount ( maxActivityCount - <NUM_LIT: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 ) ) ; } } public boolean dismissPopup ( ) { if ( isShowingPopup ( ) ) { getListPopupWindow ( ) . dismiss ( ) ; ViewTreeObserver viewTreeObserver = getViewTreeObserver ( ) ; if ( viewTreeObserver . isAlive ( ) ) { viewTreeObserver . removeGlobalOnLayoutListener ( mOnGlobalLayoutListener ) ; } } return true ; } 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 ( 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 ( <NUM_LIT:0> , <NUM_LIT:0> , right - left , bottom - top ) ; if ( getListPopupWindow ( ) . isShowing ( ) ) { showPopupUnchecked ( mAdapter . getMaxActivityCount ( ) ) ; } else { dismissPopup ( ) ; } } public ActivityChooserModel getDataModel ( ) { return mAdapter . getDataModel ( ) ; } public void setOnDismissListener ( PopupWindow . OnDismissListener listener ) { mOnDismissListener = listener ; } public void setInitialActivityCount ( int itemCount ) { mInitialActivityCount = itemCount ; } public void setDefaultActionButtonContentDescription ( int resourceId ) { mDefaultActionButtonContentDescription = resourceId ; } 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 ; } private void updateAppearance ( ) { if ( mAdapter . getCount ( ) > <NUM_LIT:0> ) { mExpandActivityOverflowButton . setEnabled ( true ) ; } else { mExpandActivityOverflowButton . setEnabled ( false ) ; } final int activityCount = mAdapter . getActivityCount ( ) ; final int historySize = mAdapter . getHistorySize ( ) ; if ( activityCount > <NUM_LIT:0> && historySize > <NUM_LIT:0> ) { mDefaultActivityButton . setVisibility ( VISIBLE ) ; ResolveInfo activity = mAdapter . getDefaultActivity ( ) ; PackageManager packageManager = mContext . getPackageManager ( ) ; mDefaultActivityButtonImage . setImageDrawable ( activity . loadIcon ( packageManager ) ) ; if ( mDefaultActionButtonContentDescription != <NUM_LIT:0> ) { CharSequence label = activity . loadLabel ( packageManager ) ; String contentDescription = mContext . getString ( mDefaultActionButtonContentDescription , label ) ; mDefaultActivityButton . setContentDescription ( contentDescription ) ; } } else { mDefaultActivityButton . setVisibility ( View . GONE ) ; } if ( mDefaultActivityButton . getVisibility ( ) == VISIBLE ) { mActivityChooserContent . setBackgroundDrawable ( mActivityChooserContentBackground ) ; } else { mActivityChooserContent . setBackgroundDrawable ( null ) ; } } private class Callbacks implements AdapterView . OnItemClickListener , View . OnClickListener , View . OnLongClickListener , PopupWindow . OnDismissListener { 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 ) { if ( position > <NUM_LIT:0> ) { mAdapter . getDataModel ( ) . setDefaultActivity ( position ) ; } } else { position = mAdapter . getShowDefaultActivity ( ) ? position : position + <NUM_LIT:1> ; Intent launchIntent = mAdapter . getDataModel ( ) . chooseActivity ( position ) ; if ( launchIntent != null ) { mContext . startActivity ( launchIntent ) ; } } } break ; default : throw new IllegalArgumentException ( ) ; } } 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 ( ) ; } } @ Override public boolean onLongClick ( View view ) { if ( view == mDefaultActivityButton ) { if ( mAdapter . getCount ( ) > <NUM_LIT:0> ) { mIsSelectingDefaultActivity = true ; showPopupUnchecked ( mInitialActivityCount ) ; } } else { throw new IllegalArgumentException ( ) ; } return true ; } 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 ; private class ActivityChooserViewAdapter extends BaseAdapter { public static final int MAX_ACTIVITY_COUNT_UNLIMITED = Integer . MAX_VALUE ; public static final int MAX_ACTIVITY_COUNT_DEFAULT = <NUM_LIT:4> ; private static final int ITEM_VIEW_TYPE_ACTIVITY = <NUM_LIT:0> ; private static final int ITEM_VIEW_TYPE_FOOTER = <NUM_LIT:1> ; private static final int ITEM_VIEW_TYPE_COUNT = <NUM_LIT: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 ( ) - <NUM_LIT: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 = <NUM_LIT: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 ( ) ; ImageView iconView = ( ImageView ) convertView . findViewById ( R . id . abs__icon ) ; ResolveInfo activity = ( ResolveInfo ) getItem ( position ) ; iconView . setImageDrawable ( activity . loadIcon ( packageManager ) ) ; TextView titleView = ( TextView ) convertView . findViewById ( R . id . abs__title ) ; titleView . setText ( activity . loadLabel ( packageManager ) ) ; if ( IS_HONEYCOMB ) { if ( mShowDefaultActivity && position == <NUM_LIT:0> && mHighlightDefaultActivity ) { SetActivated . invoke ( convertView , true ) ; } else { SetActivated . invoke ( convertView , false ) ; } } return convertView ; default : throw new IllegalArgumentException ( ) ; } } public int measureContentWidth ( ) { final int oldMaxActivityCount = mMaxActivityCount ; mMaxActivityCount = MAX_ACTIVITY_COUNT_UNLIMITED ; int contentWidth = <NUM_LIT:0> ; View itemView = null ; final int widthMeasureSpec = MeasureSpec . makeMeasureSpec ( <NUM_LIT:0> , MeasureSpec . UNSPECIFIED ) ; final int heightMeasureSpec = MeasureSpec . makeMeasureSpec ( <NUM_LIT:0> , MeasureSpec . UNSPECIFIED ) ; final int count = getCount ( ) ; for ( int i = <NUM_LIT: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 ; } } } </s>
|
<s> 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 ; public class ShareActionProvider extends ActionProvider { public interface OnShareTargetSelectedListener { public boolean onShareTargetSelected ( ShareActionProvider source , Intent intent ) ; } private static final int DEFAULT_INITIAL_ACTIVITY_COUNT = <NUM_LIT:4> ; private int mMaxShownActivityCount = DEFAULT_INITIAL_ACTIVITY_COUNT ; private final ShareMenuItemOnMenuItemClickListener mOnMenuItemClickListener = new ShareMenuItemOnMenuItemClickListener ( ) ; public static final String DEFAULT_SHARE_HISTORY_FILE_NAME = "<STR_LIT>" ; private final Context mContext ; private String mShareHistoryFileName = DEFAULT_SHARE_HISTORY_FILE_NAME ; private OnShareTargetSelectedListener mOnShareTargetSelectedListener ; private OnChooseActivityListener mOnChooseActivityListener ; public ShareActionProvider ( Context context ) { super ( context ) ; mContext = context ; } public void setOnShareTargetSelectedListener ( OnShareTargetSelectedListener listener ) { mOnShareTargetSelectedListener = listener ; setActivityChooserPolicyIfNeeded ( ) ; } @ Override public View onCreateActionView ( ) { ActivityChooserModel dataModel = ActivityChooserModel . get ( mContext , mShareHistoryFileName ) ; ActivityChooserView activityChooserView = new ActivityChooserView ( mContext ) ; activityChooserView . setActivityChooserModel ( dataModel ) ; 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 ) ; activityChooserView . setDefaultActionButtonContentDescription ( R . string . abs__shareactionprovider_share_with_application ) ; activityChooserView . setExpandActivityOverflowButtonContentDescription ( R . string . abs__shareactionprovider_share_with ) ; return activityChooserView ; } @ Override public boolean hasSubMenu ( ) { return true ; } @ Override public void onPrepareSubMenu ( SubMenu subMenu ) { subMenu . clear ( ) ; ActivityChooserModel dataModel = ActivityChooserModel . get ( mContext , mShareHistoryFileName ) ; PackageManager packageManager = mContext . getPackageManager ( ) ; final int expandedActivityCount = dataModel . getActivityCount ( ) ; final int collapsedActivityCount = Math . min ( expandedActivityCount , mMaxShownActivityCount ) ; for ( int i = <NUM_LIT:0> ; i < collapsedActivityCount ; i ++ ) { ResolveInfo activity = dataModel . getActivity ( i ) ; subMenu . add ( <NUM_LIT:0> , i , i , activity . loadLabel ( packageManager ) ) . setIcon ( activity . loadIcon ( packageManager ) ) . setOnMenuItemClickListener ( mOnMenuItemClickListener ) ; } if ( collapsedActivityCount < expandedActivityCount ) { SubMenu expandedSubMenu = subMenu . addSubMenu ( Menu . NONE , collapsedActivityCount , collapsedActivityCount , mContext . getString ( R . string . abs__activity_chooser_view_see_all ) ) ; for ( int i = <NUM_LIT:0> ; i < expandedActivityCount ; i ++ ) { ResolveInfo activity = dataModel . getActivity ( i ) ; expandedSubMenu . add ( <NUM_LIT:0> , i , i , activity . loadLabel ( packageManager ) ) . setIcon ( activity . loadIcon ( packageManager ) ) . setOnMenuItemClickListener ( mOnMenuItemClickListener ) ; } } } public void setShareHistoryFileName ( String shareHistoryFile ) { mShareHistoryFileName = shareHistoryFile ; setActivityChooserPolicyIfNeeded ( ) ; } public void setShareIntent ( Intent shareIntent ) { ActivityChooserModel dataModel = ActivityChooserModel . get ( mContext , mShareHistoryFileName ) ; dataModel . setIntent ( shareIntent ) ; } 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 ; } } private void setActivityChooserPolicyIfNeeded ( ) { if ( mOnShareTargetSelectedListener == null ) { return ; } if ( mOnChooseActivityListener == null ) { mOnChooseActivityListener = new ShareAcitivityChooserModelPolicy ( ) ; } ActivityChooserModel dataModel = ActivityChooserModel . get ( mContext , mShareHistoryFileName ) ; dataModel . setOnChooseActivityListener ( mOnChooseActivityListener ) ; } private class ShareAcitivityChooserModelPolicy implements OnChooseActivityListener { @ Override public boolean onChooseActivity ( ActivityChooserModel host , Intent intent ) { if ( mOnShareTargetSelectedListener != null ) { return mOnShareTargetSelectedListener . onShareTargetSelected ( ShareActionProvider . this , intent ) ; } return false ; } } } </s>
|
<s> package android . support . v4 . app ; import android . util . Log ; import android . view . View ; import android . view . Window ; import com . actionbarsherlock . ActionBarSherlock . OnCreatePanelMenuListener ; import com . actionbarsherlock . ActionBarSherlock . OnMenuItemSelectedListener ; import com . actionbarsherlock . ActionBarSherlock . OnPreparePanelListener ; import com . actionbarsherlock . view . Menu ; import com . actionbarsherlock . view . MenuInflater ; import com . actionbarsherlock . view . MenuItem ; import java . util . ArrayList ; public abstract class _ActionBarSherlockTrojanHorse extends FragmentActivity implements OnCreatePanelMenuListener , OnPreparePanelListener , OnMenuItemSelectedListener { private static final boolean DEBUG = false ; private static final String TAG = "<STR_LIT>" ; public interface OnCreateOptionsMenuListener { public void onCreateOptionsMenu ( Menu menu , MenuInflater inflater ) ; } public interface OnPrepareOptionsMenuListener { public void onPrepareOptionsMenu ( Menu menu ) ; } public interface OnOptionsItemSelectedListener { public boolean onOptionsItemSelected ( MenuItem item ) ; } private ArrayList < Fragment > mCreatedMenus ; @ Override public boolean onCreatePanelMenu ( int featureId , Menu menu ) { if ( DEBUG ) Log . d ( TAG , "<STR_LIT>" + featureId + "<STR_LIT>" + menu ) ; if ( featureId == Window . FEATURE_OPTIONS_PANEL ) { boolean result = onCreateOptionsMenu ( menu ) ; if ( DEBUG ) Log . d ( TAG , "<STR_LIT>" + result ) ; MenuInflater inflater = getSupportMenuInflater ( ) ; boolean show = false ; ArrayList < Fragment > newMenus = null ; if ( mFragments . mActive != null ) { for ( int i = <NUM_LIT:0> ; i < mFragments . mAdded . size ( ) ; i ++ ) { Fragment f = mFragments . mAdded . get ( i ) ; if ( f != null && ! f . mHidden && f . mHasMenu && f . mMenuVisible && f instanceof OnCreateOptionsMenuListener ) { show = true ; ( ( OnCreateOptionsMenuListener ) f ) . onCreateOptionsMenu ( menu , inflater ) ; if ( newMenus == null ) { newMenus = new ArrayList < Fragment > ( ) ; } newMenus . add ( f ) ; } } } if ( mCreatedMenus != null ) { for ( int i = <NUM_LIT:0> ; i < mCreatedMenus . size ( ) ; i ++ ) { Fragment f = mCreatedMenus . get ( i ) ; if ( newMenus == null || ! newMenus . contains ( f ) ) { f . onDestroyOptionsMenu ( ) ; } } } mCreatedMenus = newMenus ; if ( DEBUG ) Log . d ( TAG , "<STR_LIT>" + show ) ; result |= show ; if ( DEBUG ) Log . d ( TAG , "<STR_LIT>" + result ) ; return result ; } return false ; } @ Override public boolean onPreparePanel ( int featureId , View view , Menu menu ) { if ( DEBUG ) Log . d ( TAG , "<STR_LIT>" + featureId + "<STR_LIT>" + view + "<STR_LIT>" + menu ) ; if ( featureId == Window . FEATURE_OPTIONS_PANEL ) { boolean result = onPrepareOptionsMenu ( menu ) ; if ( DEBUG ) Log . d ( TAG , "<STR_LIT>" + result ) ; boolean show = false ; if ( mFragments . mActive != null ) { for ( int i = <NUM_LIT:0> ; i < mFragments . mAdded . size ( ) ; i ++ ) { Fragment f = mFragments . mAdded . get ( i ) ; if ( f != null && ! f . mHidden && f . mHasMenu && f . mMenuVisible && f instanceof OnPrepareOptionsMenuListener ) { show = true ; ( ( OnPrepareOptionsMenuListener ) f ) . onPrepareOptionsMenu ( menu ) ; } } } if ( DEBUG ) Log . d ( TAG , "<STR_LIT>" + show ) ; result |= show ; result &= menu . hasVisibleItems ( ) ; if ( DEBUG ) Log . d ( TAG , "<STR_LIT>" + result ) ; return result ; } return false ; } @ Override public boolean onMenuItemSelected ( int featureId , MenuItem item ) { if ( DEBUG ) Log . d ( TAG , "<STR_LIT>" + featureId + "<STR_LIT>" + item ) ; if ( featureId == Window . FEATURE_OPTIONS_PANEL ) { if ( onOptionsItemSelected ( item ) ) { return true ; } if ( mFragments . mActive != null ) { for ( int i = <NUM_LIT:0> ; i < mFragments . mAdded . size ( ) ; i ++ ) { Fragment f = mFragments . mAdded . get ( i ) ; if ( f != null && ! f . mHidden && f . mHasMenu && f . mMenuVisible && f instanceof OnOptionsItemSelectedListener ) { if ( ( ( OnOptionsItemSelectedListener ) f ) . onOptionsItemSelected ( item ) ) { return true ; } } } } } return false ; } public abstract boolean onCreateOptionsMenu ( Menu menu ) ; public abstract boolean onPrepareOptionsMenu ( Menu menu ) ; public abstract boolean onOptionsItemSelected ( MenuItem item ) ; public abstract MenuInflater getSupportMenuInflater ( ) ; } </s>
|
<s> package gov . in . bloomington . georeporter . adapters ; import gov . in . bloomington . georeporter . models . Open311 ; import android . content . Context ; import android . view . LayoutInflater ; import android . view . View ; import android . view . ViewGroup ; import android . widget . BaseAdapter ; import android . widget . TextView ; public class GroupsAdapter extends BaseAdapter { private static LayoutInflater mInflater ; public GroupsAdapter ( Context c ) { mInflater = LayoutInflater . from ( c ) ; } @ Override public int getCount ( ) { return ( Open311 . sGroups == null ) ? <NUM_LIT:0> : Open311 . sGroups . size ( ) ; } @ Override public String getItem ( int position ) { return Open311 . sGroups . get ( position ) ; } @ Override public long getItemId ( int position ) { return position ; } private static class ViewHolder { public TextView name ; } @ Override public View getView ( int position , View convertView , ViewGroup parent ) { ViewHolder holder ; if ( convertView == null ) { convertView = mInflater . inflate ( android . R . layout . simple_list_item_1 , null ) ; holder = new ViewHolder ( ) ; holder . name = ( TextView ) convertView . findViewById ( android . R . id . text1 ) ; convertView . setTag ( holder ) ; } else { holder = ( ViewHolder ) convertView . getTag ( ) ; } holder . name . setText ( getItem ( position ) ) ; return convertView ; } } </s>
|
<s> package gov . in . bloomington . georeporter . adapters ; import gov . in . bloomington . georeporter . R ; import gov . in . bloomington . georeporter . models . Open311 ; import gov . in . bloomington . georeporter . models . Preferences ; import org . json . JSONArray ; import org . json . JSONObject ; import android . content . Context ; import android . view . LayoutInflater ; import android . view . View ; import android . view . ViewGroup ; import android . widget . BaseAdapter ; import android . widget . RadioButton ; import android . widget . TextView ; public class ServersAdapter extends BaseAdapter { private JSONArray mServers ; private static LayoutInflater mInflater ; private String mCurrentServerName ; public ServersAdapter ( JSONArray d , Context c ) { mServers = d ; mInflater = LayoutInflater . from ( c ) ; JSONObject currentServer = Preferences . getCurrentServer ( c ) ; mCurrentServerName = currentServer == null ? "<STR_LIT>" : currentServer . optString ( "<STR_LIT:name>" ) ; } @ Override public int getCount ( ) { return ( mServers == null ) ? <NUM_LIT:0> : mServers . length ( ) ; } @ Override public JSONObject getItem ( int position ) { return mServers . optJSONObject ( position ) ; } @ Override public long getItemId ( int position ) { return position ; } private static class ViewHolder { public TextView name , url ; public RadioButton radio ; } @ Override public View getView ( int position , View convertView , ViewGroup parent ) { ViewHolder holder ; if ( convertView == null ) { convertView = mInflater . inflate ( R . layout . list_item_servers , null ) ; holder = new ViewHolder ( ) ; holder . name = ( TextView ) convertView . findViewById ( android . R . id . text1 ) ; holder . url = ( TextView ) convertView . findViewById ( android . R . id . text2 ) ; holder . radio = ( RadioButton ) convertView . findViewById ( R . id . radio ) ; convertView . setTag ( holder ) ; } else { holder = ( ViewHolder ) convertView . getTag ( ) ; } String name = mServers . optJSONObject ( position ) . optString ( Open311 . NAME ) ; String url = mServers . optJSONObject ( position ) . optString ( Open311 . URL ) ; if ( name . equals ( mCurrentServerName ) ) { holder . radio . setChecked ( true ) ; } else { holder . radio . setChecked ( false ) ; } holder . name . setText ( name ) ; holder . url . setText ( url ) ; return convertView ; } } </s>
|
<s> package gov . in . bloomington . georeporter . adapters ; import org . json . JSONObject ; import android . content . Context ; import android . content . res . Resources ; import android . view . View ; import android . view . ViewGroup ; import android . view . LayoutInflater ; import android . widget . BaseAdapter ; import android . widget . TextView ; public class PersonalInfoAdapter extends BaseAdapter { private Resources mResources ; private String mPackageName ; private JSONObject mPersonalInfo ; private LayoutInflater mInflater ; public static final String [ ] FIELDS = { "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT:email>" , "<STR_LIT>" } ; public PersonalInfoAdapter ( JSONObject d , Context c ) { mPersonalInfo = d ; mInflater = LayoutInflater . from ( c ) ; mResources = c . getResources ( ) ; mPackageName = c . getPackageName ( ) ; } @ Override public int getCount ( ) { return FIELDS . length ; } @ Override public Object getItem ( int position ) { return mPersonalInfo . opt ( FIELDS [ position ] ) ; } @ Override public long getItemId ( int position ) { return position ; } private static class ViewHolder { public TextView label ; public TextView input ; } @ Override public View getView ( int position , View convertView , ViewGroup parent ) { ViewHolder holder ; if ( convertView == null ) { convertView = mInflater . inflate ( android . R . layout . simple_list_item_2 , null ) ; holder = new ViewHolder ( ) ; holder . label = ( TextView ) convertView . findViewById ( android . R . id . text1 ) ; holder . input = ( TextView ) convertView . findViewById ( android . R . id . text2 ) ; convertView . setTag ( holder ) ; } else { holder = ( ViewHolder ) convertView . getTag ( ) ; } String fieldname = FIELDS [ position ] ; holder . label . setText ( mResources . getIdentifier ( fieldname , "<STR_LIT:string>" , mPackageName ) ) ; holder . input . setText ( mPersonalInfo . optString ( fieldname ) ) ; return convertView ; } } </s>
|
<s> package gov . in . bloomington . georeporter . adapters ; import gov . in . bloomington . georeporter . models . Open311 ; import org . json . JSONArray ; import org . json . JSONException ; import org . json . JSONObject ; import android . content . Context ; import android . view . LayoutInflater ; import android . view . View ; import android . view . ViewGroup ; import android . widget . BaseAdapter ; import android . widget . TextView ; public class SavedReportsAdapter extends BaseAdapter { private JSONArray mServiceRequests ; private static LayoutInflater mInflater ; public SavedReportsAdapter ( JSONArray serviceRequests , Context c ) { mServiceRequests = serviceRequests ; mInflater = LayoutInflater . from ( c ) ; } @ Override public int getCount ( ) { return ( mServiceRequests == null ) ? <NUM_LIT:0> : mServiceRequests . length ( ) ; } @ Override public JSONObject getItem ( int position ) { return mServiceRequests . optJSONObject ( position ) ; } @ Override public long getItemId ( int position ) { return position ; } private static class ViewHolder { TextView name , description ; } @ Override public View getView ( int position , View convertView , ViewGroup parent ) { ViewHolder holder ; JSONObject report = getItem ( position ) ; if ( convertView == null ) { convertView = mInflater . inflate ( android . R . layout . simple_list_item_2 , null ) ; holder = new ViewHolder ( ) ; holder . name = ( TextView ) convertView . findViewById ( android . R . id . text1 ) ; holder . description = ( TextView ) convertView . findViewById ( android . R . id . text2 ) ; convertView . setTag ( holder ) ; } else { holder = ( ViewHolder ) convertView . getTag ( ) ; } JSONObject server ; try { server = report . getJSONObject ( Open311 . SERVER ) ; holder . name . setText ( server . getString ( Open311 . NAME ) ) ; holder . description . setText ( server . getString ( Open311 . URL ) ) ; } catch ( JSONException e ) { e . printStackTrace ( ) ; } return convertView ; } } </s>
|
<s> package gov . in . bloomington . georeporter . adapters ; import gov . in . bloomington . georeporter . models . Open311 ; import java . util . ArrayList ; import org . json . JSONObject ; import android . content . Context ; import android . view . LayoutInflater ; import android . view . View ; import android . view . ViewGroup ; import android . widget . BaseAdapter ; import android . widget . TextView ; public class ServicesAdapter extends BaseAdapter { private static LayoutInflater mInflater ; private static ArrayList < JSONObject > mServices ; public ServicesAdapter ( ArrayList < JSONObject > services , Context c ) { mServices = services ; mInflater = LayoutInflater . from ( c ) ; } @ Override public int getCount ( ) { return mServices . size ( ) ; } @ Override public JSONObject getItem ( int position ) { return mServices . get ( position ) ; } @ Override public long getItemId ( int position ) { return position ; } private static class ViewHolder { TextView name , description ; } @ Override public View getView ( int position , View convertView , ViewGroup parent ) { ViewHolder holder ; JSONObject service = getItem ( position ) ; if ( convertView == null ) { convertView = mInflater . inflate ( android . R . layout . simple_list_item_2 , null ) ; holder = new ViewHolder ( ) ; holder . name = ( TextView ) convertView . findViewById ( android . R . id . text1 ) ; holder . description = ( TextView ) convertView . findViewById ( android . R . id . text2 ) ; convertView . setTag ( holder ) ; } else { holder = ( ViewHolder ) convertView . getTag ( ) ; } holder . name . setText ( service . optString ( Open311 . SERVICE_NAME ) ) ; holder . description . setText ( service . optString ( Open311 . DESCRIPTION ) ) ; return convertView ; } } </s>
|
<s> package gov . in . bloomington . georeporter . models ; import java . io . FileInputStream ; import java . io . FileNotFoundException ; import java . io . FileOutputStream ; import java . io . IOException ; import java . io . UnsupportedEncodingException ; import java . util . ArrayList ; import java . util . HashMap ; import java . util . List ; import java . util . Map ; import org . apache . http . HttpResponse ; import org . apache . http . HttpVersion ; import org . apache . http . NameValuePair ; import org . apache . http . ParseException ; import org . apache . http . client . ClientProtocolException ; import org . apache . http . client . entity . UrlEncodedFormEntity ; import org . apache . http . client . methods . HttpGet ; import org . apache . http . client . methods . HttpPost ; import org . apache . http . impl . client . DefaultHttpClient ; import org . apache . http . message . BasicNameValuePair ; import org . apache . http . params . CoreConnectionPNames ; import org . apache . http . params . CoreProtocolPNames ; import org . apache . http . util . EntityUtils ; import org . json . JSONArray ; import org . json . JSONException ; import org . json . JSONObject ; import android . content . Context ; public class Open311 { public static final String JURISDICTION = "<STR_LIT>" ; public static final String API_KEY = "<STR_LIT>" ; public static final String SERVICE_CODE = "<STR_LIT>" ; public static final String SERVICE_NAME = "<STR_LIT>" ; public static final String MEDIA = "<STR_LIT>" ; public static final String MEDIA_URL = "<STR_LIT>" ; public static final String LATITUDE = "<STR_LIT>" ; public static final String LONGITUDE = "<STR_LIT:long>" ; public static final String ADDRESS = "<STR_LIT>" ; public static final String DESCRIPTION = "<STR_LIT:description>" ; public static final String EMAIL = "<STR_LIT:email>" ; public static final String DEVICE_ID = "<STR_LIT>" ; public static final String FIRST_NAME = "<STR_LIT>" ; public static final String LAST_NAME = "<STR_LIT>" ; public static final String PHONE = "<STR_LIT>" ; public static final String METADATA = "<STR_LIT>" ; public static final String ATTRIBUTES = "<STR_LIT>" ; public static final String VARIABLE = "<STR_LIT>" ; public static final String CODE = "<STR_LIT:code>" ; public static final String ORDER = "<STR_LIT>" ; public static final String VALUES = "<STR_LIT>" ; public static final String KEY = "<STR_LIT:key>" ; public static final String NAME = "<STR_LIT:name>" ; public static final String REQUIRED = "<STR_LIT>" ; public static final String DATATYPE = "<STR_LIT>" ; public static final String STRING = "<STR_LIT:string>" ; public static final String NUMBER = "<STR_LIT:number>" ; public static final String DATETIME = "<STR_LIT>" ; public static final String TEXT = "<STR_LIT:text>" ; public static final String SINGLEVALUELIST = "<STR_LIT>" ; public static final String MULTIVALUELIST = "<STR_LIT>" ; public static final String URL = "<STR_LIT:url>" ; public static final String SUPPORTS_MEDIA = "<STR_LIT>" ; private static final String SAVED_REPORTS_FILE = "<STR_LIT>" ; public static final String SERVER = "<STR_LIT>" ; public static final String SERVICE_REQUEST = "<STR_LIT>" ; public static final String SERVICE_REQUEST_ID = "<STR_LIT>" ; public static final String TOKEN = "<STR_LIT>" ; public static Boolean sReady = false ; public static JSONArray sServiceList = null ; public static HashMap < String , JSONObject > sServiceDefinitions ; public static ArrayList < String > sGroups ; private static JSONObject mEndpoint ; private static String mBaseUrl ; private static String mJurisdiction ; private static String mApiKey ; private static DefaultHttpClient mClient = null ; private static final int TIMEOUT = <NUM_LIT> ; private static Open311 mInstance ; private Open311 ( ) { } public static synchronized Open311 getInstance ( ) { if ( mInstance == null ) { mInstance = new Open311 ( ) ; } return mInstance ; } private static DefaultHttpClient getClient ( ) { if ( mClient == null ) { mClient = new DefaultHttpClient ( ) ; mClient . getParams ( ) . setParameter ( CoreProtocolPNames . HTTP_CONTENT_CHARSET , "<STR_LIT:UTF-8>" ) ; mClient . getParams ( ) . setParameter ( CoreProtocolPNames . PROTOCOL_VERSION , HttpVersion . HTTP_1_1 ) ; mClient . getParams ( ) . setParameter ( CoreConnectionPNames . SO_TIMEOUT , TIMEOUT ) ; mClient . getParams ( ) . setParameter ( CoreConnectionPNames . CONNECTION_TIMEOUT , TIMEOUT ) ; } return mClient ; } public static Boolean setEndpoint ( JSONObject current_server ) { sReady = false ; mBaseUrl = null ; mJurisdiction = null ; mApiKey = null ; sGroups = new ArrayList < String > ( ) ; sServiceList = null ; sServiceDefinitions = new HashMap < String , JSONObject > ( ) ; try { mBaseUrl = current_server . getString ( URL ) ; mJurisdiction = current_server . optString ( JURISDICTION ) ; mApiKey = current_server . optString ( API_KEY ) ; } catch ( JSONException e ) { return false ; } try { sServiceList = new JSONArray ( loadStringFromUrl ( getServiceListUrl ( ) ) ) ; String group = "<STR_LIT>" ; int len = sServiceList . length ( ) ; for ( int i = <NUM_LIT:0> ; i < len ; i ++ ) { JSONObject s = sServiceList . getJSONObject ( i ) ; group = s . optString ( "<STR_LIT>" ) ; if ( group != "<STR_LIT>" && ! sGroups . contains ( group ) ) { sGroups . add ( group ) ; } if ( s . optString ( "<STR_LIT>" ) == "<STR_LIT:true>" ) { String code = s . optString ( SERVICE_CODE ) ; JSONObject definition = getServiceDefinition ( code ) ; if ( definition != null ) { sServiceDefinitions . put ( code , definition ) ; } } } } catch ( ClientProtocolException e ) { e . printStackTrace ( ) ; return false ; } catch ( IllegalStateException e ) { e . printStackTrace ( ) ; return false ; } catch ( JSONException e ) { e . printStackTrace ( ) ; return false ; } catch ( IOException e ) { e . printStackTrace ( ) ; return false ; } mEndpoint = current_server ; sReady = true ; return sReady ; } public static ArrayList < JSONObject > getServices ( String group ) { ArrayList < JSONObject > services = new ArrayList < JSONObject > ( ) ; int len = sServiceList . length ( ) ; for ( int i = <NUM_LIT:0> ; i < len ; i ++ ) { try { JSONObject s = sServiceList . getJSONObject ( i ) ; if ( s . optString ( "<STR_LIT>" ) . equals ( group ) ) { services . add ( s ) ; } } catch ( JSONException e ) { e . printStackTrace ( ) ; } } return services ; } public static JSONObject getServiceDefinition ( String service_code ) { try { return new JSONObject ( loadStringFromUrl ( getServiceDefinitionUrl ( service_code ) ) ) ; } catch ( ClientProtocolException e ) { e . printStackTrace ( ) ; } catch ( IllegalStateException e ) { e . printStackTrace ( ) ; } catch ( JSONException e ) { e . printStackTrace ( ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; } return null ; } public static JSONArray postServiceRequest ( HashMap < String , String > data ) { List < NameValuePair > pairs = new ArrayList < NameValuePair > ( ) ; for ( Map . Entry < String , String > entry : data . entrySet ( ) ) { pairs . add ( new BasicNameValuePair ( entry . getKey ( ) , entry . getValue ( ) ) ) ; } if ( mJurisdiction != null ) { pairs . add ( new BasicNameValuePair ( JURISDICTION , mJurisdiction ) ) ; } if ( mApiKey != null ) { pairs . add ( new BasicNameValuePair ( API_KEY , mApiKey ) ) ; } HttpPost request = new HttpPost ( mBaseUrl + "<STR_LIT>" ) ; JSONArray response = null ; try { request . setEntity ( new UrlEncodedFormEntity ( pairs ) ) ; HttpResponse r = mClient . execute ( request ) ; response = new JSONArray ( EntityUtils . toString ( r . getEntity ( ) ) ) ; } catch ( UnsupportedEncodingException e ) { e . printStackTrace ( ) ; } catch ( ClientProtocolException e ) { e . printStackTrace ( ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; } catch ( ParseException e ) { e . printStackTrace ( ) ; } catch ( JSONException e ) { e . printStackTrace ( ) ; } return response ; } public static JSONArray loadServiceRequests ( Context c ) { JSONArray service_requests = new JSONArray ( ) ; StringBuffer buffer = new StringBuffer ( "<STR_LIT>" ) ; byte [ ] bytes = new byte [ <NUM_LIT> ] ; int length ; try { FileInputStream in = c . openFileInput ( SAVED_REPORTS_FILE ) ; while ( ( length = in . read ( bytes ) ) != - <NUM_LIT:1> ) { buffer . append ( new String ( bytes ) ) ; } service_requests = new JSONArray ( new String ( buffer ) ) ; } catch ( FileNotFoundException e ) { e . printStackTrace ( ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; } catch ( JSONException e ) { e . printStackTrace ( ) ; } return service_requests ; } private static boolean saveServiceRequests ( Context c , JSONArray requests ) { String json = requests . toString ( ) ; FileOutputStream out ; try { out = c . openFileOutput ( SAVED_REPORTS_FILE , Context . MODE_PRIVATE ) ; out . write ( json . getBytes ( ) ) ; out . close ( ) ; return true ; } catch ( FileNotFoundException e ) { e . printStackTrace ( ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; } return false ; } public static boolean saveServiceRequest ( Context c , JSONArray request ) { JSONObject report = new JSONObject ( ) ; try { report . put ( SERVER , mEndpoint ) ; report . put ( SERVICE_REQUEST , request . getJSONObject ( <NUM_LIT:0> ) ) ; JSONArray saved_requests = loadServiceRequests ( c ) ; saved_requests . put ( report ) ; return saveServiceRequests ( c , saved_requests ) ; } catch ( JSONException e ) { e . printStackTrace ( ) ; } return false ; } private static String loadStringFromUrl ( String url ) throws ClientProtocolException , IOException , IllegalStateException { HttpResponse r = getClient ( ) . execute ( new HttpGet ( url ) ) ; String response = EntityUtils . toString ( r . getEntity ( ) ) ; return response ; } private static String getServiceListUrl ( ) { return mBaseUrl + "<STR_LIT>" + JURISDICTION + "<STR_LIT:=>" + mJurisdiction ; } private static String getServiceDefinitionUrl ( String service_code ) { return mBaseUrl + "<STR_LIT>" + service_code + "<STR_LIT>" + JURISDICTION + "<STR_LIT:=>" + mJurisdiction ; } } </s>
|
<s> package gov . in . bloomington . georeporter . models ; import org . json . JSONException ; import org . json . JSONObject ; import android . content . Context ; import android . content . SharedPreferences ; public class Preferences { private static final String SETTINGS = "<STR_LIT>" ; private static final String PERSONAL_INFO = "<STR_LIT>" ; private static final String APP_STATE = "<STR_LIT>" ; private static final String CURRENT_SERVER = "<STR_LIT>" ; private static SharedPreferences mSettings = null ; private static SharedPreferences mState = null ; private static void loadSettings ( Context c ) { if ( mSettings == null ) { mSettings = c . getSharedPreferences ( SETTINGS , Context . MODE_PRIVATE ) ; } } private static void loadState ( Context c ) { if ( mState == null ) { mState = c . getSharedPreferences ( APP_STATE , Context . MODE_PRIVATE ) ; } } public static JSONObject getPersonalInfo ( Context c ) { Preferences . loadSettings ( c ) ; try { return new JSONObject ( mSettings . getString ( PERSONAL_INFO , "<STR_LIT:{}>" ) ) ; } catch ( JSONException e ) { return null ; } } public static JSONObject getCurrentServer ( Context c ) { Preferences . loadState ( c ) ; try { return new JSONObject ( mState . getString ( CURRENT_SERVER , "<STR_LIT>" ) ) ; } catch ( JSONException e ) { return null ; } } public static void setPersonalInfo ( JSONObject personal_info , Context c ) { Preferences . loadSettings ( c ) ; SharedPreferences . Editor editor = mSettings . edit ( ) ; editor . putString ( PERSONAL_INFO , personal_info . toString ( ) ) ; editor . commit ( ) ; } public static void setCurrentServer ( JSONObject server , Context c ) { Preferences . loadState ( c ) ; SharedPreferences . Editor editor = mState . edit ( ) ; if ( server != null ) { editor . putString ( CURRENT_SERVER , server . toString ( ) ) ; } else { editor . remove ( CURRENT_SERVER ) ; } editor . commit ( ) ; } } </s>
|
<s> package gov . in . bloomington . georeporter . dialogs ; import java . util . Calendar ; import android . app . DatePickerDialog ; import android . app . Dialog ; import android . app . DatePickerDialog . OnDateSetListener ; import android . os . Bundle ; import android . text . format . DateFormat ; import android . view . View ; import android . widget . TextView ; import com . actionbarsherlock . app . SherlockDialogFragment ; public class DatePickerDialogFragment extends SherlockDialogFragment implements OnDateSetListener { private TextView mInput ; public DatePickerDialogFragment ( View v ) { mInput = ( TextView ) v ; } @ Override public Dialog onCreateDialog ( Bundle savedInstanceState ) { Calendar c = Calendar . getInstance ( ) ; return new DatePickerDialog ( getActivity ( ) , this , c . get ( Calendar . YEAR ) , c . get ( Calendar . MONTH ) , c . get ( Calendar . DAY_OF_MONTH ) ) ; } @ Override public void onDateSet ( android . widget . DatePicker view , int year , int monthOfYear , int dayOfMonth ) { Calendar c = Calendar . getInstance ( ) ; c . set ( year , monthOfYear , dayOfMonth ) ; mInput . setText ( DateFormat . getDateFormat ( getActivity ( ) ) . format ( c . getTime ( ) ) ) ; } } </s>
|
<s> package gov . in . bloomington . georeporter . tasks ; import java . io . IOException ; import java . util . List ; import java . util . Locale ; import com . google . android . maps . GeoPoint ; import android . content . Context ; import android . location . Address ; import android . location . Geocoder ; import android . os . AsyncTask ; import android . widget . EditText ; public class ReverseGeocodingTask extends AsyncTask < GeoPoint , Void , String > { Context mContext ; EditText mLocationDisplay ; public ReverseGeocodingTask ( Context context , EditText view ) { super ( ) ; mContext = context ; mLocationDisplay = view ; } @ Override protected String doInBackground ( GeoPoint ... params ) { Geocoder geocoder = new Geocoder ( mContext , Locale . getDefault ( ) ) ; GeoPoint point = params [ <NUM_LIT:0> ] ; double latitude = point . getLatitudeE6 ( ) / <NUM_LIT> ; double longitude = point . getLongitudeE6 ( ) / <NUM_LIT> ; List < Address > addresses = null ; try { addresses = geocoder . getFromLocation ( latitude , longitude , <NUM_LIT:1> ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; } if ( addresses != null && addresses . size ( ) > <NUM_LIT:0> ) { Address address = addresses . get ( <NUM_LIT:0> ) ; return String . format ( "<STR_LIT:%s>" , address . getMaxAddressLineIndex ( ) > <NUM_LIT:0> ? address . getAddressLine ( <NUM_LIT:0> ) : "<STR_LIT>" ) ; } return null ; } @ Override protected void onPostExecute ( String result ) { if ( result != null ) { mLocationDisplay . setText ( result ) ; } super . onPostExecute ( result ) ; } } </s>
|
<s> package gov . in . bloomington . georeporter . util ; import gov . in . bloomington . georeporter . R ; import java . io . BufferedReader ; import java . io . IOException ; import java . io . InputStream ; import java . io . InputStreamReader ; import android . app . AlertDialog ; import android . content . Context ; import android . content . DialogInterface ; public class Util { public static String file_get_contents ( Context c , int resource ) { InputStream in = c . getResources ( ) . openRawResource ( resource ) ; BufferedReader reader = new BufferedReader ( new InputStreamReader ( in ) ) ; StringBuilder s = new StringBuilder ( ) ; String l = null ; try { while ( ( l = reader . readLine ( ) ) != null ) { s . append ( l ) ; } in . close ( ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; } return s . toString ( ) ; } public static void displayCrashDialog ( Context c , String message ) { AlertDialog . Builder builder = new AlertDialog . Builder ( c ) ; builder . setTitle ( "<STR_LIT>" ) . setMessage ( message ) . setCancelable ( false ) . setNegativeButton ( R . string . button_accept_error , new DialogInterface . OnClickListener ( ) { @ Override public void onClick ( DialogInterface dialog , int which ) { dialog . cancel ( ) ; } } ) ; builder . create ( ) ; builder . show ( ) ; } } </s>
|
<s> package gov . in . bloomington . georeporter . fragments ; import java . text . DateFormat ; import java . text . ParseException ; import java . text . SimpleDateFormat ; import java . util . Date ; import java . util . HashMap ; import gov . in . bloomington . georeporter . R ; import gov . in . bloomington . georeporter . activities . ChooseLocationActivity ; import gov . in . bloomington . georeporter . activities . MainActivity ; import gov . in . bloomington . georeporter . dialogs . DatePickerDialogFragment ; import gov . in . bloomington . georeporter . models . Open311 ; import gov . in . bloomington . georeporter . tasks . ReverseGeocodingTask ; import gov . in . bloomington . georeporter . util . Util ; import org . json . JSONArray ; import org . json . JSONException ; import org . json . JSONObject ; import android . app . Activity ; import android . app . ProgressDialog ; import android . content . Intent ; import android . os . AsyncTask ; import android . os . Bundle ; import android . text . InputType ; import android . view . LayoutInflater ; import android . view . View ; import android . view . View . OnClickListener ; import android . view . ViewGroup ; import android . widget . CheckBox ; import android . widget . CompoundButton ; import android . widget . EditText ; import android . widget . LinearLayout ; import android . widget . RadioButton ; import android . widget . RadioGroup ; import android . widget . TextView ; import com . actionbarsherlock . app . SherlockDialogFragment ; import com . actionbarsherlock . app . SherlockFragment ; import com . google . android . maps . GeoPoint ; public class ReportFragment extends SherlockFragment { public static final int CHOOSE_LOCATION_REQUEST = <NUM_LIT:1> ; private JSONObject mService , mDefinition ; private JSONArray mAttributes ; private HashMap < String , View > mAttributeViews ; private EditText mLocationView , mDescription ; private Double mLatitude , mLongitude ; public void setService ( JSONObject service ) { mService = service ; if ( mService . optBoolean ( Open311 . METADATA ) ) { mDefinition = Open311 . sServiceDefinitions . get ( mService . opt ( Open311 . SERVICE_CODE ) ) ; mAttributes = mDefinition . optJSONArray ( Open311 . ATTRIBUTES ) ; mAttributeViews = new HashMap < String , View > ( mAttributes . length ( ) ) ; } } @ Override public void onSaveInstanceState ( Bundle outState ) { super . onSaveInstanceState ( outState ) ; outState . putString ( "<STR_LIT>" , mService . toString ( ) ) ; } @ Override public View onCreateView ( LayoutInflater inflater , ViewGroup container , Bundle savedInstanceState ) { if ( savedInstanceState != null ) { try { JSONObject s = new JSONObject ( savedInstanceState . getString ( "<STR_LIT>" ) ) ; setService ( s ) ; } catch ( JSONException e ) { e . printStackTrace ( ) ; } } View v = getLayoutInflater ( savedInstanceState ) . inflate ( R . layout . fragment_report , container , false ) ; mLocationView = ( EditText ) v . findViewById ( R . id . address_string ) ; mDescription = ( EditText ) v . findViewById ( R . id . description ) ; v . findViewById ( R . id . mapChooserButton ) . setOnClickListener ( new OnClickListener ( ) { @ Override public void onClick ( View v ) { Intent i = new Intent ( getActivity ( ) , ChooseLocationActivity . class ) ; startActivityForResult ( i , CHOOSE_LOCATION_REQUEST ) ; } } ) ; v . findViewById ( R . id . button_cancel ) . setOnClickListener ( new OnClickListener ( ) { @ Override public void onClick ( View v ) { Intent intent = new Intent ( getActivity ( ) , MainActivity . class ) ; intent . addFlags ( Intent . FLAG_ACTIVITY_CLEAR_TOP ) ; startActivity ( intent ) ; } } ) ; v . findViewById ( R . id . button_submit ) . setOnClickListener ( new OnClickListener ( ) { @ Override public void onClick ( View v ) { submit ( v ) ; } } ) ; return v ; } @ Override public void onActivityCreated ( Bundle savedInstanceState ) { super . onActivityCreated ( savedInstanceState ) ; TextView service_description = ( TextView ) getView ( ) . findViewById ( R . id . service_description ) ; service_description . setText ( mService . optString ( Open311 . DESCRIPTION ) ) ; if ( mService . optBoolean ( Open311 . METADATA ) ) { LinearLayout layout = ( LinearLayout ) getView ( ) . findViewById ( R . id . attributes ) ; int len = mAttributes . length ( ) ; for ( int i = <NUM_LIT:0> ; i < len ; i ++ ) { JSONObject a ; try { a = mAttributes . getJSONObject ( i ) ; View v = loadViewForAttribute ( a , savedInstanceState ) ; if ( v != null ) { String description = a . getString ( Open311 . DESCRIPTION ) ; TextView label = ( TextView ) v . findViewById ( R . id . label ) ; label . setText ( description ) ; mAttributeViews . put ( a . getString ( Open311 . CODE ) , v ) ; layout . addView ( v ) ; } } catch ( JSONException e ) { e . printStackTrace ( ) ; } } } } @ Override public void onActivityResult ( int requestCode , int resultCode , Intent data ) { super . onActivityResult ( requestCode , resultCode , data ) ; if ( requestCode == CHOOSE_LOCATION_REQUEST ) { if ( resultCode == Activity . RESULT_OK ) { int latitudeE6 = data . getIntExtra ( Open311 . LATITUDE , <NUM_LIT:0> ) ; int longitudeE6 = data . getIntExtra ( Open311 . LONGITUDE , <NUM_LIT:0> ) ; String latitude = Double . toString ( latitudeE6 / <NUM_LIT> ) ; String longitude = Double . toString ( longitudeE6 / <NUM_LIT> ) ; mLocationView . setText ( String . format ( "<STR_LIT>" , latitude , longitude ) ) ; new ReverseGeocodingTask ( getActivity ( ) , mLocationView ) . execute ( new GeoPoint ( latitudeE6 , longitudeE6 ) ) ; } } } private View loadViewForAttribute ( JSONObject attribute , Bundle savedInstanceState ) { LayoutInflater inflater = getLayoutInflater ( savedInstanceState ) ; String datatype = attribute . optString ( Open311 . DATATYPE , Open311 . STRING ) ; if ( datatype . equals ( Open311 . STRING ) || datatype . equals ( Open311 . NUMBER ) || datatype . equals ( Open311 . TEXT ) ) { View v = inflater . inflate ( R . layout . list_item_report_attributes_string , null ) ; EditText input = ( EditText ) v . findViewById ( R . id . input ) ; if ( datatype . equals ( Open311 . NUMBER ) ) { input . setInputType ( InputType . TYPE_CLASS_NUMBER ) ; } if ( datatype . equals ( Open311 . TEXT ) ) { input . setInputType ( InputType . TYPE_TEXT_FLAG_MULTI_LINE ) ; } return v ; } else if ( datatype . equals ( Open311 . DATETIME ) ) { View v = inflater . inflate ( R . layout . list_item_report_attributes_datetime , null ) ; TextView input = ( TextView ) v . findViewById ( R . id . input ) ; input . setOnClickListener ( new OnClickListener ( ) { @ Override public void onClick ( View v ) { SherlockDialogFragment picker = new DatePickerDialogFragment ( v ) ; picker . show ( getActivity ( ) . getSupportFragmentManager ( ) , "<STR_LIT>" ) ; } } ) ; return v ; } else if ( datatype . equals ( Open311 . SINGLEVALUELIST ) || datatype . equals ( Open311 . MULTIVALUELIST ) ) { JSONArray values = attribute . optJSONArray ( Open311 . VALUES ) ; int len = values . length ( ) ; if ( datatype . equals ( Open311 . SINGLEVALUELIST ) ) { View v = inflater . inflate ( R . layout . list_item_report_attributes_singlevaluelist , null ) ; RadioGroup input = ( RadioGroup ) v . findViewById ( R . id . input ) ; for ( int i = <NUM_LIT:0> ; i < len ; i ++ ) { JSONObject value = values . optJSONObject ( i ) ; RadioButton button = ( RadioButton ) inflater . inflate ( R . layout . radiobutton , null ) ; button . setText ( value . optString ( Open311 . KEY ) ) ; input . addView ( button ) ; } return v ; } else if ( datatype . equals ( Open311 . MULTIVALUELIST ) ) { View v = inflater . inflate ( R . layout . list_item_report_attributes_multivaluelist , null ) ; LinearLayout input = ( LinearLayout ) v . findViewById ( R . id . input ) ; for ( int i = <NUM_LIT:0> ; i < len ; i ++ ) { JSONObject value = values . optJSONObject ( i ) ; CheckBox checkbox = ( CheckBox ) inflater . inflate ( R . layout . checkbox , null ) ; checkbox . setText ( value . optString ( Open311 . KEY ) ) ; input . addView ( checkbox ) ; } return v ; } } return null ; } public void submit ( View v ) { HashMap < String , String > post ; try { post = generatePost ( v ) ; new ServiceRequestPost ( ) . execute ( post ) ; } catch ( JSONException e ) { e . printStackTrace ( ) ; } } private HashMap < String , String > generatePost ( View v ) throws JSONException { HashMap < String , String > post = new HashMap < String , String > ( ) ; post . put ( Open311 . SERVICE_CODE , mService . getString ( Open311 . SERVICE_CODE ) ) ; post . put ( Open311 . ADDRESS , mLocationView . getText ( ) . toString ( ) ) ; post . put ( Open311 . DESCRIPTION , mDescription . getText ( ) . toString ( ) ) ; if ( mLatitude != null && mLongitude != null ) { post . put ( Open311 . LATITUDE , mLatitude . toString ( ) ) ; post . put ( Open311 . LONGITUDE , mLongitude . toString ( ) ) ; } if ( mService . optBoolean ( Open311 . METADATA ) ) { int len = mAttributes . length ( ) ; for ( int i = <NUM_LIT:0> ; i < len ; i ++ ) { JSONObject attribute = mAttributes . getJSONObject ( i ) ; String code = attribute . getString ( Open311 . CODE ) ; String datatype = attribute . optString ( Open311 . DATATYPE , Open311 . STRING ) ; String key = String . format ( "<STR_LIT>" , code ) ; if ( datatype . equals ( Open311 . STRING ) || datatype . equals ( Open311 . NUMBER ) || datatype . equals ( Open311 . TEXT ) ) { EditText input = ( EditText ) mAttributeViews . get ( code ) ; post . put ( key , input . getText ( ) . toString ( ) ) ; } else if ( datatype . equals ( Open311 . DATETIME ) ) { TextView input = ( TextView ) mAttributeViews . get ( code ) ; DateFormat df = DateFormat . getInstance ( ) ; try { Date date = df . parse ( input . getText ( ) . toString ( ) ) ; SimpleDateFormat format = new SimpleDateFormat ( "<STR_LIT>" ) ; post . put ( key , format . format ( date ) ) ; } catch ( ParseException e ) { e . printStackTrace ( ) ; } } else if ( datatype . equals ( Open311 . SINGLEVALUELIST ) || datatype . equals ( Open311 . MULTIVALUELIST ) ) { ViewGroup input = ( ViewGroup ) mAttributeViews . get ( code ) ; JSONArray values = attribute . optJSONArray ( Open311 . VALUES ) ; int l = values . length ( ) ; for ( int j = <NUM_LIT:0> ; j < l ; j ++ ) { CompoundButton b = ( CompoundButton ) input . getChildAt ( j ) ; if ( b . isChecked ( ) ) { String value = values . getJSONObject ( j ) . getString ( Open311 . NAME ) ; if ( datatype . equals ( Open311 . SINGLEVALUELIST ) ) { post . put ( key , value ) ; break ; } else { post . put ( key + "<STR_LIT:[]>" , value ) ; } } } } } } return post ; } private class ServiceRequestPost extends AsyncTask < HashMap < String , String > , Void , Boolean > { ProgressDialog dialog ; @ Override protected void onPreExecute ( ) { super . onPreExecute ( ) ; dialog = ProgressDialog . show ( getActivity ( ) , getResources ( ) . getString ( R . string . dialog_loading_services ) , "<STR_LIT>" , true ) ; } @ Override protected Boolean doInBackground ( HashMap < String , String > ... params ) { Boolean result = false ; JSONArray response = Open311 . postServiceRequest ( params [ <NUM_LIT:0> ] ) ; if ( response != null && response . length ( ) > <NUM_LIT:0> ) { result = Open311 . saveServiceRequest ( getActivity ( ) , response ) ; } return result ; } @ Override protected void onPostExecute ( Boolean result ) { dialog . dismiss ( ) ; if ( ! result ) { Util . displayCrashDialog ( getActivity ( ) , "<STR_LIT>" ) ; } else { } super . onPostExecute ( result ) ; } } } </s>
|
<s> package gov . in . bloomington . georeporter . fragments ; import gov . in . bloomington . georeporter . adapters . GroupsAdapter ; import gov . in . bloomington . georeporter . models . Open311 ; import android . app . Activity ; import android . view . View ; import android . widget . ListView ; import com . actionbarsherlock . app . SherlockListFragment ; public class ChooseGroupFragment extends SherlockListFragment { OnGroupSelectedListener mListener ; public interface OnGroupSelectedListener { public void onGroupSelected ( String group ) ; } @ Override public void onAttach ( Activity activity ) { super . onAttach ( activity ) ; setListAdapter ( new GroupsAdapter ( getActivity ( ) ) ) ; mListener = ( OnGroupSelectedListener ) activity ; } @ Override public void onListItemClick ( ListView l , View v , int position , long id ) { super . onListItemClick ( l , v , position , id ) ; mListener . onGroupSelected ( Open311 . sGroups . get ( position ) ) ; } } </s>
|
<s> package gov . in . bloomington . georeporter . fragments ; import gov . in . bloomington . georeporter . adapters . ServicesAdapter ; import java . util . ArrayList ; import org . json . JSONObject ; import android . app . Activity ; import android . view . View ; import android . widget . ListView ; import com . actionbarsherlock . app . SherlockListFragment ; public class ChooseServiceFragment extends SherlockListFragment { private static OnServiceSelectedListener mListener ; private static ArrayList < JSONObject > mServices ; public interface OnServiceSelectedListener { public void onServiceSelected ( JSONObject service ) ; } public void setServices ( ArrayList < JSONObject > services ) { mServices = services ; } @ Override public void onAttach ( Activity activity ) { super . onAttach ( activity ) ; setListAdapter ( new ServicesAdapter ( mServices , activity ) ) ; mListener = ( OnServiceSelectedListener ) activity ; } @ Override public void onListItemClick ( ListView l , View v , int position , long id ) { super . onListItemClick ( l , v , position , id ) ; mListener . onServiceSelected ( mServices . get ( position ) ) ; } } </s>
|
<s> package gov . in . bloomington . georeporter . fragments ; import gov . in . bloomington . georeporter . R ; import gov . in . bloomington . georeporter . activities . MainActivity ; import gov . in . bloomington . georeporter . adapters . ServersAdapter ; import gov . in . bloomington . georeporter . models . Preferences ; import gov . in . bloomington . georeporter . util . Util ; import org . json . JSONArray ; import org . json . JSONException ; import org . json . JSONObject ; import com . actionbarsherlock . app . SherlockListFragment ; import android . content . Intent ; import android . os . Bundle ; import android . view . View ; import android . widget . ListView ; public class ServersFragment extends SherlockListFragment { JSONArray mServers = null ; @ Override public void onCreate ( Bundle savedInstanceState ) { super . onCreate ( savedInstanceState ) ; try { mServers = new JSONArray ( Util . file_get_contents ( getActivity ( ) , R . raw . available_servers ) ) ; } catch ( JSONException e ) { Util . displayCrashDialog ( getActivity ( ) , "<STR_LIT>" ) ; } setListAdapter ( new ServersAdapter ( mServers , getActivity ( ) ) ) ; } @ Override public void onListItemClick ( ListView l , View v , int position , long id ) { super . onListItemClick ( l , v , position , id ) ; JSONObject current_server = null ; try { current_server = mServers . getJSONObject ( position ) ; } catch ( JSONException e ) { } Preferences . setCurrentServer ( current_server , getActivity ( ) ) ; Intent i = new Intent ( getActivity ( ) , MainActivity . class ) ; i . addFlags ( Intent . FLAG_ACTIVITY_CLEAR_TOP ) ; startActivity ( i ) ; } } </s>
|
<s> package gov . in . bloomington . georeporter . fragments ; import gov . in . bloomington . georeporter . adapters . PersonalInfoAdapter ; import gov . in . bloomington . georeporter . models . Preferences ; import org . json . JSONException ; import org . json . JSONObject ; import android . app . AlertDialog ; import android . content . DialogInterface ; import android . content . SharedPreferences ; import android . os . Bundle ; import android . text . InputType ; import android . view . View ; import android . widget . EditText ; import android . widget . ListView ; import android . widget . TextView ; import com . actionbarsherlock . app . SherlockListFragment ; public class PersonalInfoFragment extends SherlockListFragment { JSONObject mPersonalInfo = null ; SharedPreferences mPreferences = null ; @ Override public void onCreate ( Bundle savedInstanceState ) { super . onCreate ( savedInstanceState ) ; mPersonalInfo = Preferences . getPersonalInfo ( getActivity ( ) ) ; setListAdapter ( new PersonalInfoAdapter ( mPersonalInfo , getActivity ( ) ) ) ; } @ Override public void onPause ( ) { Preferences . setPersonalInfo ( mPersonalInfo , getActivity ( ) ) ; super . onPause ( ) ; } @ Override public void onListItemClick ( ListView l , View v , int position , long id ) { super . onListItemClick ( l , v , position , id ) ; final String fieldname = PersonalInfoAdapter . FIELDS [ position ] ; final TextView label = ( TextView ) v . findViewById ( android . R . id . text1 ) ; final TextView input = ( TextView ) v . findViewById ( android . R . id . text2 ) ; final EditText newValue = new EditText ( getActivity ( ) ) ; newValue . setText ( input . getText ( ) ) ; int type = InputType . TYPE_TEXT_FLAG_CAP_WORDS ; if ( fieldname == "<STR_LIT:email>" ) { type = InputType . TYPE_TEXT_VARIATION_EMAIL_ADDRESS ; } if ( fieldname == "<STR_LIT>" ) { type = InputType . TYPE_CLASS_PHONE ; } newValue . setInputType ( type ) ; new AlertDialog . Builder ( getActivity ( ) ) . setTitle ( label . getText ( ) ) . setView ( newValue ) . setPositiveButton ( "<STR_LIT>" , new DialogInterface . OnClickListener ( ) { @ Override public void onClick ( DialogInterface dialog , int which ) { try { mPersonalInfo . put ( fieldname , newValue . getText ( ) ) ; } catch ( JSONException e ) { } } } ) . setNegativeButton ( "<STR_LIT>" , new DialogInterface . OnClickListener ( ) { @ Override public void onClick ( DialogInterface dialog , int which ) { } } ) . show ( ) ; } } </s>
|
<s> package gov . in . bloomington . georeporter . fragments ; import gov . in . bloomington . georeporter . adapters . SavedReportsAdapter ; import gov . in . bloomington . georeporter . models . Open311 ; import android . os . Bundle ; import com . actionbarsherlock . app . SherlockListFragment ; public class SavedReportsListFragment extends SherlockListFragment { @ Override public void onCreate ( Bundle savedInstanceState ) { super . onCreate ( savedInstanceState ) ; setListAdapter ( new SavedReportsAdapter ( Open311 . loadServiceRequests ( getActivity ( ) ) , getActivity ( ) ) ) ; } } </s>
|
<s> package gov . in . bloomington . georeporter . activities ; import gov . in . bloomington . georeporter . R ; import android . os . Bundle ; import android . support . v4 . app . FragmentTransaction ; import com . actionbarsherlock . app . ActionBar ; import com . actionbarsherlock . app . ActionBar . Tab ; import com . actionbarsherlock . app . SherlockListFragment ; import gov . in . bloomington . georeporter . fragments . PersonalInfoFragment ; import gov . in . bloomington . georeporter . fragments . ServersFragment ; public class SettingsActivity extends BaseFragmentActivity { @ Override protected void onCreate ( Bundle savedInstanceState ) { super . onCreate ( savedInstanceState ) ; ActionBar actionBar = getSupportActionBar ( ) ; actionBar . setNavigationMode ( ActionBar . NAVIGATION_MODE_TABS ) ; actionBar . setTitle ( R . string . menu_settings ) ; Tab tab ; tab = actionBar . newTab ( ) . setText ( R . string . tab_servers ) . setTabListener ( new TabListener < ServersFragment > ( this , "<STR_LIT>" , ServersFragment . class ) ) ; actionBar . addTab ( tab ) ; tab = actionBar . newTab ( ) . setText ( R . string . tab_personal_info ) . setTabListener ( new TabListener < PersonalInfoFragment > ( this , "<STR_LIT>" , PersonalInfoFragment . class ) ) ; actionBar . addTab ( tab ) ; } public static class TabListener < T extends SherlockListFragment > implements ActionBar . TabListener { private SherlockListFragment mFragment ; private final SettingsActivity mActivity ; private final String mTag ; private final Class < T > mClass ; public TabListener ( SettingsActivity settingsActivity , String tag , Class < T > clz ) { mActivity = settingsActivity ; mTag = tag ; mClass = clz ; } public void onTabSelected ( Tab tab , FragmentTransaction ft ) { if ( mFragment == null ) { mFragment = ( SherlockListFragment ) SherlockListFragment . instantiate ( mActivity , mClass . getName ( ) ) ; ft . add ( android . R . id . content , mFragment , mTag ) ; } else { ft . attach ( mFragment ) ; } } public void onTabUnselected ( Tab tab , FragmentTransaction ft ) { if ( mFragment != null ) { ft . detach ( mFragment ) ; } } public void onTabReselected ( Tab tab , FragmentTransaction ft ) { } } } </s>
|
<s> package gov . in . bloomington . georeporter . activities ; import org . json . JSONObject ; import android . app . ProgressDialog ; import android . content . Intent ; import android . os . AsyncTask ; import android . os . Bundle ; import gov . in . bloomington . georeporter . R ; import gov . in . bloomington . georeporter . models . Open311 ; import gov . in . bloomington . georeporter . models . Preferences ; import gov . in . bloomington . georeporter . util . Util ; public class MainActivity extends BaseActivity { @ Override protected void onCreate ( Bundle savedInstanceState ) { super . onCreate ( savedInstanceState ) ; setContentView ( R . layout . activity_main ) ; } @ Override protected void onResume ( ) { super . onResume ( ) ; JSONObject current_server = Preferences . getCurrentServer ( this ) ; if ( current_server == null ) { startActivity ( new Intent ( this , SettingsActivity . class ) ) ; } else { new EndpointLoader ( ) . execute ( current_server ) ; } } private class EndpointLoader extends AsyncTask < JSONObject , Void , Boolean > { ProgressDialog dialog ; @ Override protected void onPreExecute ( ) { super . onPreExecute ( ) ; dialog = ProgressDialog . show ( MainActivity . this , getResources ( ) . getString ( R . string . dialog_loading_services ) , "<STR_LIT>" , true ) ; } @ Override protected Boolean doInBackground ( JSONObject ... server ) { return Open311 . setEndpoint ( server [ <NUM_LIT:0> ] ) ; } @ Override protected void onPostExecute ( Boolean result ) { dialog . dismiss ( ) ; if ( ! result ) { Util . displayCrashDialog ( MainActivity . this , "<STR_LIT>" ) ; } super . onPostExecute ( result ) ; } } } </s>
|
<s> package gov . in . bloomington . georeporter . activities ; import gov . in . bloomington . georeporter . R ; import android . os . Bundle ; public class SavedReportsActivity extends BaseFragmentActivity { @ Override protected void onCreate ( Bundle savedInstanceState ) { super . onCreate ( savedInstanceState ) ; getSupportActionBar ( ) . setTitle ( R . string . menu_archive ) ; setContentView ( R . layout . activity_saved_reports ) ; } } </s>
|
<s> package gov . in . bloomington . georeporter . activities ; import gov . in . bloomington . georeporter . R ; import gov . in . bloomington . georeporter . models . Open311 ; import android . content . Intent ; import android . location . Criteria ; import android . location . Location ; import android . location . LocationListener ; import android . location . LocationManager ; import android . os . Bundle ; import android . view . View ; import com . google . android . maps . GeoPoint ; import com . google . android . maps . MapActivity ; import com . google . android . maps . MapView ; public class ChooseLocationActivity extends MapActivity { private MapView mMap ; private LocationManager mLocationManager ; public static final int DEFAULT_ZOOM = <NUM_LIT> ; @ Override protected void onCreate ( Bundle savedInstanceState ) { super . onCreate ( savedInstanceState ) ; setContentView ( R . layout . activity_map_chooser ) ; mMap = ( MapView ) findViewById ( R . id . mapview ) ; mMap . getController ( ) . setZoom ( DEFAULT_ZOOM ) ; } @ Override protected void onStart ( ) { super . onStart ( ) ; mLocationManager = ( LocationManager ) getSystemService ( LOCATION_SERVICE ) ; Criteria c = new Criteria ( ) ; c . setAccuracy ( Criteria . ACCURACY_COARSE ) ; String provider = mLocationManager . getBestProvider ( c , true ) ; mLocationManager . requestLocationUpdates ( provider , <NUM_LIT:0> , <NUM_LIT:0> , new MapListener ( ) ) ; } @ Override protected boolean isRouteDisplayed ( ) { return false ; } private class MapListener implements LocationListener { @ Override public void onLocationChanged ( Location location ) { mLocationManager . removeUpdates ( this ) ; GeoPoint p = new GeoPoint ( ( int ) ( location . getLatitude ( ) * <NUM_LIT> ) , ( int ) ( location . getLongitude ( ) * <NUM_LIT> ) ) ; mMap . getController ( ) . animateTo ( p ) ; } @ Override public void onProviderDisabled ( String provider ) { } @ Override public void onProviderEnabled ( String provider ) { } @ Override public void onStatusChanged ( String provider , int status , Bundle extras ) { } } public void submit ( View v ) { GeoPoint center = mMap . getMapCenter ( ) ; Intent result = new Intent ( ) ; result . putExtra ( Open311 . LATITUDE , center . getLatitudeE6 ( ) ) ; result . putExtra ( Open311 . LONGITUDE , center . getLongitudeE6 ( ) ) ; setResult ( RESULT_OK , result ) ; finish ( ) ; } public void cancel ( View v ) { setResult ( RESULT_CANCELED ) ; finish ( ) ; } } </s>
|
<s> package gov . in . bloomington . georeporter . activities ; import gov . in . bloomington . georeporter . R ; import android . content . Intent ; import android . os . Bundle ; import com . actionbarsherlock . app . SherlockFragmentActivity ; import com . actionbarsherlock . view . Menu ; import com . actionbarsherlock . view . MenuItem ; public abstract class BaseFragmentActivity extends SherlockFragmentActivity { @ Override protected void onCreate ( Bundle savedInstanceState ) { super . onCreate ( savedInstanceState ) ; getSupportActionBar ( ) . setDisplayHomeAsUpEnabled ( true ) ; } @ Override public boolean onCreateOptionsMenu ( Menu menu ) { getSupportMenuInflater ( ) . inflate ( R . menu . main , menu ) ; return true ; } @ Override public boolean onOptionsItemSelected ( MenuItem item ) { Intent intent ; switch ( item . getItemId ( ) ) { case android . R . id . home : intent = new Intent ( this , MainActivity . class ) ; intent . addFlags ( Intent . FLAG_ACTIVITY_CLEAR_TOP ) ; startActivity ( intent ) ; return true ; case R . id . menu_settings : intent = new Intent ( this , SettingsActivity . class ) ; startActivity ( intent ) ; return true ; case R . id . menu_report : intent = new Intent ( this , ReportActivity . class ) ; startActivity ( intent ) ; return true ; case R . id . menu_archive : intent = new Intent ( this , SavedReportsActivity . class ) ; startActivity ( intent ) ; return true ; default : return super . onOptionsItemSelected ( item ) ; } } } </s>
|
<s> package gov . in . bloomington . georeporter . activities ; import gov . in . bloomington . georeporter . R ; import android . content . Intent ; import android . os . Bundle ; import com . actionbarsherlock . app . SherlockActivity ; import com . actionbarsherlock . view . Menu ; import com . actionbarsherlock . view . MenuItem ; public abstract class BaseActivity extends SherlockActivity { @ Override protected void onCreate ( Bundle savedInstanceState ) { super . onCreate ( savedInstanceState ) ; getSupportActionBar ( ) . setDisplayHomeAsUpEnabled ( true ) ; } @ Override public boolean onCreateOptionsMenu ( Menu menu ) { getSupportMenuInflater ( ) . inflate ( R . menu . main , menu ) ; return true ; } @ Override public boolean onOptionsItemSelected ( MenuItem item ) { Intent intent ; switch ( item . getItemId ( ) ) { case android . R . id . home : intent = new Intent ( this , MainActivity . class ) ; intent . addFlags ( Intent . FLAG_ACTIVITY_CLEAR_TOP ) ; startActivity ( intent ) ; return true ; case R . id . menu_settings : intent = new Intent ( this , SettingsActivity . class ) ; startActivity ( intent ) ; return true ; case R . id . menu_report : intent = new Intent ( this , ReportActivity . class ) ; startActivity ( intent ) ; return true ; case R . id . menu_archive : intent = new Intent ( this , SavedReportsActivity . class ) ; startActivity ( intent ) ; return true ; default : return super . onOptionsItemSelected ( item ) ; } } } </s>
|
<s> package gov . in . bloomington . georeporter . activities ; import org . json . JSONObject ; import gov . in . bloomington . georeporter . R ; import gov . in . bloomington . georeporter . fragments . ChooseGroupFragment ; import gov . in . bloomington . georeporter . fragments . ChooseServiceFragment ; import gov . in . bloomington . georeporter . fragments . ReportFragment ; import gov . in . bloomington . georeporter . fragments . ChooseGroupFragment . OnGroupSelectedListener ; import gov . in . bloomington . georeporter . fragments . ChooseServiceFragment . OnServiceSelectedListener ; import gov . in . bloomington . georeporter . models . Open311 ; import android . os . Bundle ; import com . actionbarsherlock . app . ActionBar ; public class ReportActivity extends BaseFragmentActivity implements OnGroupSelectedListener , OnServiceSelectedListener { public static final int CHOOSE_LOCATION_REQUEST = <NUM_LIT:1> ; private ActionBar mActionBar ; private ReportFragment mReportFragment ; @ Override protected void onCreate ( Bundle savedInstanceState ) { super . onCreate ( savedInstanceState ) ; mActionBar = getSupportActionBar ( ) ; mActionBar . setTitle ( R . string . menu_report ) ; ChooseGroupFragment chooseGroup = new ChooseGroupFragment ( ) ; getSupportFragmentManager ( ) . beginTransaction ( ) . add ( android . R . id . content , chooseGroup ) . addToBackStack ( null ) . commit ( ) ; } @ Override public void onGroupSelected ( String group ) { ChooseServiceFragment chooseService = new ChooseServiceFragment ( ) ; chooseService . setServices ( Open311 . getServices ( group ) ) ; getSupportFragmentManager ( ) . beginTransaction ( ) . replace ( android . R . id . content , chooseService ) . addToBackStack ( null ) . commit ( ) ; } @ Override public void onServiceSelected ( JSONObject service ) { mActionBar . setTitle ( service . optString ( "<STR_LIT>" ) ) ; mReportFragment = new ReportFragment ( ) ; mReportFragment . setService ( service ) ; getSupportFragmentManager ( ) . beginTransaction ( ) . replace ( android . R . id . content , mReportFragment ) . addToBackStack ( null ) . commit ( ) ; } } </s>
|
<s> package org . jm . swagger ; import java . util . HashSet ; import java . util . List ; import java . util . Map ; import java . util . Map . Entry ; import java . util . Set ; import org . jm . spring . controller . EndpointDocumentationController ; import org . springframework . core . LocalVariableTableParameterNameDiscoverer ; import org . springframework . core . MethodParameter ; import org . springframework . core . annotation . AnnotationUtils ; import org . springframework . stereotype . Controller ; import org . springframework . web . bind . annotation . PathVariable ; import org . springframework . web . bind . annotation . RequestMapping ; import org . springframework . web . bind . annotation . RequestMethod ; import org . springframework . web . bind . annotation . RequestParam ; import org . springframework . web . method . HandlerMethod ; import org . springframework . web . servlet . mvc . method . RequestMappingInfo ; import org . springframework . web . servlet . mvc . method . annotation . RequestMappingHandlerMapping ; import com . google . common . base . Joiner ; import com . google . common . collect . Lists ; import com . wordnik . swagger . core . ApiParam ; import com . wordnik . swagger . core . Documentation ; import com . wordnik . swagger . core . DocumentationEndPoint ; import com . wordnik . swagger . core . DocumentationOperation ; import com . wordnik . swagger . core . DocumentationParameter ; public class SpringMVCAPIReader { private String apiVersion ; private String swaggerVersion ; private String basePath ; private String resourcePath ; @ SuppressWarnings ( { "<STR_LIT:rawtypes>" , "<STR_LIT:serial>" } ) private Set < Class > excludeControllers = new HashSet < Class > ( ) { { add ( EndpointDocumentationController . class ) ; } } ; public SpringMVCAPIReader ( String apiVersion , String swaggerVersion , String basePath , String resourcePath ) { this . apiVersion = apiVersion ; this . swaggerVersion = swaggerVersion ; this . basePath = basePath ; this . resourcePath = resourcePath ; } public Documentation createResources ( RequestMappingHandlerMapping mapping ) { Documentation documentation = new Documentation ( this . apiVersion , this . swaggerVersion , this . basePath , this . resourcePath ) ; Map < String , Object > beansWithAnnotation = mapping . getApplicationContext ( ) . getBeansWithAnnotation ( Controller . class ) ; for ( Entry < String , Object > entry : beansWithAnnotation . entrySet ( ) ) { if ( ! excludeControllers . contains ( entry . getValue ( ) . getClass ( ) ) ) { RequestMapping classRequestMapping = AnnotationUtils . findAnnotation ( entry . getValue ( ) . getClass ( ) , RequestMapping . class ) ; if ( classRequestMapping != null && classRequestMapping . value ( ) . length > <NUM_LIT:0> ) { String path = classRequestMapping . value ( ) [ <NUM_LIT:0> ] ; DocumentationEndPoint documentationEndPoint = new DocumentationEndPoint ( path , entry . getValue ( ) . getClass ( ) . getSimpleName ( ) ) ; documentation . addApi ( documentationEndPoint ) ; } } } return documentation ; } public Documentation processMethods ( RequestMappingHandlerMapping mapping , String classRequestMapping ) { Documentation documentation = new Documentation ( this . apiVersion , this . swaggerVersion , this . basePath , this . resourcePath ) ; for ( Entry < RequestMappingInfo , HandlerMethod > entry : mapping . getHandlerMethods ( ) . entrySet ( ) ) { RequestMappingInfo requestMappingInfo = entry . getKey ( ) ; HandlerMethod handlerMethod = entry . getValue ( ) ; RequestMapping requestMapping = handlerMethod . getBeanType ( ) . getAnnotation ( RequestMapping . class ) ; if ( requestMapping . value ( ) [ <NUM_LIT:0> ] . contains ( classRequestMapping ) ) { String path = null ; for ( String pt : requestMappingInfo . getPatternsCondition ( ) . getPatterns ( ) ) { path = pt ; } DocumentationEndPoint documentationEndPoint = new DocumentationEndPoint ( path + "<STR_LIT>" , "<STR_LIT:description>" ) ; DocumentationOperation documentationOperation = processRequestMapping ( requestMappingInfo , handlerMethod . getMethod ( ) . getName ( ) ) ; List < DocumentationParameter > documentationParamaters = convertHandlerMethod ( handlerMethod ) ; documentationOperation . setParameters ( documentationParamaters ) ; documentationEndPoint . addOperation ( documentationOperation ) ; documentation . addApi ( documentationEndPoint ) ; } } return documentation ; } private DocumentationOperation processRequestMapping ( RequestMappingInfo requestMappingInfo , String nickName ) { DocumentationOperation documentationOperation = new DocumentationOperation ( ) ; Set < RequestMethod > requestMethods = requestMappingInfo . getMethodsCondition ( ) . getMethods ( ) ; String value = Joiner . on ( "<STR_LIT:U+002C>" ) . join ( requestMethods ) ; documentationOperation . setHttpMethod ( value ) ; documentationOperation . setNickname ( nickName ) ; documentationOperation . setSummary ( "<STR_LIT>" ) ; return documentationOperation ; } private List < DocumentationParameter > convertHandlerMethod ( HandlerMethod handlerMethod ) { List < DocumentationParameter > documentationParameters = Lists . newArrayList ( ) ; MethodParameter [ ] methParameters = handlerMethod . getMethodParameters ( ) ; for ( MethodParameter methodParamater : methParameters ) { if ( methodParamater . hasParameterAnnotations ( ) ) { documentationParameters . add ( convertMethodParameter ( methodParamater ) ) ; } } return documentationParameters ; } private DocumentationParameter convertMethodParameter ( MethodParameter methodParamater ) { DocumentationParameter documentationParameter = new DocumentationParameter ( ) ; documentationParameter . setDataType ( methodParamater . getParameterType ( ) . getSimpleName ( ) ) ; methodParamater . initParameterNameDiscovery ( new LocalVariableTableParameterNameDiscoverer ( ) ) ; documentationParameter . setName ( methodParamater . getParameterName ( ) ) ; documentationParameter . setDescription ( "<STR_LIT:description>" ) ; documentationParameter . setNotes ( "<STR_LIT>" ) ; documentationParameter . setParamType ( "<STR_LIT:path>" ) ; documentationParameter . setDefaultValue ( "<STR_LIT>" ) ; documentationParameter . setAllowMultiple ( false ) ; PathVariable pathVariable = methodParamater . getParameterAnnotation ( PathVariable . class ) ; if ( pathVariable != null ) { documentationParameter . setRequired ( true ) ; } RequestParam requestParam = methodParamater . getParameterAnnotation ( RequestParam . class ) ; if ( requestParam != null ) { documentationParameter . setRequired ( requestParam . required ( ) ) ; documentationParameter . setDefaultValue ( requestParam . defaultValue ( ) ) ; } ApiParam apiParam = methodParamater . getParameterAnnotation ( ApiParam . class ) ; if ( apiParam != null ) { documentationParameter . setName ( apiParam . name ( ) ) ; documentationParameter . setDescription ( apiParam . value ( ) ) ; } return documentationParameter ; } @ SuppressWarnings ( "<STR_LIT:rawtypes>" ) public void setExcludeControllers ( Set < Class > excludeControllers ) { if ( this . excludeControllers != null ) { this . excludeControllers . addAll ( excludeControllers ) ; } } } </s>
|
<s> package org . jm . spring . controller ; import javax . servlet . http . HttpServletRequest ; import org . jm . swagger . SpringMVCAPIReader ; import org . springframework . beans . factory . annotation . Autowired ; import org . springframework . http . MediaType ; import org . springframework . stereotype . Controller ; import org . springframework . web . bind . annotation . PathVariable ; import org . springframework . web . bind . annotation . RequestMapping ; import org . springframework . web . bind . annotation . RequestMethod ; import org . springframework . web . bind . annotation . ResponseBody ; import org . springframework . web . servlet . mvc . method . annotation . RequestMappingHandlerMapping ; import org . springframework . web . util . UrlPathHelper ; import com . wordnik . swagger . core . Documentation ; @ Controller @ RequestMapping ( "<STR_LIT:/>" ) public class EndpointDocumentationController { private final RequestMappingHandlerMapping handlerMapping ; @ Autowired public EndpointDocumentationController ( RequestMappingHandlerMapping handlerMapping ) { this . handlerMapping = handlerMapping ; } private String getBasePath ( HttpServletRequest httpServletRequest ) { String scheme = httpServletRequest . getScheme ( ) ; String serverName = httpServletRequest . getServerName ( ) ; int serverPort = httpServletRequest . getServerPort ( ) ; StringBuffer basePath = new StringBuffer ( ) ; basePath . append ( scheme ) . append ( "<STR_LIT>" ) . append ( serverName ) ; if ( serverPort != <NUM_LIT> ) { basePath . append ( "<STR_LIT::>" ) . append ( serverPort ) ; } return basePath . toString ( ) ; } @ RequestMapping ( value = "<STR_LIT>" , method = RequestMethod . GET , produces = { MediaType . APPLICATION_JSON_VALUE } ) public @ ResponseBody Documentation showAvailableResources ( HttpServletRequest httpServletRequest ) throws Exception { UrlPathHelper urlPathHelper = new UrlPathHelper ( ) ; String basePath = getBasePath ( httpServletRequest ) ; SpringMVCAPIReader springMVCAPIReader = new SpringMVCAPIReader ( "<STR_LIT>" , "<STR_LIT>" , basePath , urlPathHelper . getContextPath ( httpServletRequest ) ) ; Documentation document = springMVCAPIReader . createResources ( handlerMapping ) ; return document ; } @ RequestMapping ( value = "<STR_LIT>" , method = RequestMethod . GET , produces = { MediaType . APPLICATION_JSON_VALUE } ) public @ ResponseBody Documentation showAvailableResource ( HttpServletRequest httpServletRequest , @ PathVariable String classRequestMapping ) throws ClassNotFoundException { Documentation document = null ; UrlPathHelper urlPathHelper = new UrlPathHelper ( ) ; String basePath = getBasePath ( httpServletRequest ) ; SpringMVCAPIReader springMVCAPIReader = new SpringMVCAPIReader ( "<STR_LIT>" , "<STR_LIT>" , basePath , urlPathHelper . getContextPath ( httpServletRequest ) ) ; document = springMVCAPIReader . processMethods ( handlerMapping , classRequestMapping ) ; return document ; } } </s>
|
<s> package org . jm . spring . controller . test ; import javax . servlet . http . HttpServletResponse ; import junit . framework . Assert ; import org . codehaus . jackson . map . ObjectMapper ; import org . jm . swagger . SpringMVCAPIReader ; import org . junit . Before ; import org . junit . Test ; import org . springframework . context . support . StaticApplicationContext ; import org . springframework . http . MediaType ; import org . springframework . stereotype . Controller ; import org . springframework . web . bind . annotation . PathVariable ; import org . springframework . web . bind . annotation . RequestMapping ; import org . springframework . web . bind . annotation . RequestMethod ; import org . springframework . web . bind . annotation . RequestParam ; import org . springframework . web . servlet . mvc . method . annotation . RequestMappingHandlerMapping ; import com . wordnik . swagger . core . Documentation ; public class SpringMVCAPIReaderTest { private RequestMappingHandlerMapping mapping ; private Handler handler ; private ObjectMapper mapper ; @ Before public void setUp ( ) throws Exception { mapper = new ObjectMapper ( ) ; handler = new Handler ( ) ; StaticApplicationContext context = new StaticApplicationContext ( ) ; context . registerSingleton ( "<STR_LIT>" , handler . getClass ( ) ) ; mapping = new RequestMappingHandlerMapping ( ) ; mapping . setApplicationContext ( context ) ; } @ Test public void test_get_all_resources ( ) { SpringMVCAPIReader mvcapiReader = new SpringMVCAPIReader ( "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" ) ; Documentation doc = mvcapiReader . createResources ( mapping ) ; Assert . assertNotNull ( doc ) ; } @ Test public void test_process_method ( ) { SpringMVCAPIReader mvcapiReader = new SpringMVCAPIReader ( "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" ) ; Documentation doc = mvcapiReader . processMethods ( mapping , Handler . class . toString ( ) ) ; Assert . assertNotNull ( doc ) ; } @ SuppressWarnings ( "<STR_LIT:unused>" ) @ Controller @ RequestMapping ( "<STR_LIT>" ) private static class Handler { @ RequestMapping ( value = { "<STR_LIT>" } , method = { RequestMethod . GET , RequestMethod . POST } , produces = { MediaType . APPLICATION_JSON_VALUE } , consumes = { MediaType . APPLICATION_JSON_VALUE } , headers = { } ) public void multipleValueWithMediaType ( HttpServletResponse response , @ PathVariable Integer param1 , @ PathVariable String param2 , @ RequestParam ( defaultValue = "<STR_LIT:none>" , required = true , value = "<STR_LIT>" ) String requestParam1 , @ RequestParam ( value = "<STR_LIT>" ) Integer requestParam2 ) { } } } </s>
|
<s> package com . smartgrid . messenger ; import java . util . Map ; public interface Messenger < T > { public Integer [ ] memberIds ( ) ; public < ResponseType , MessageType > ResponseType message ( Integer id , Message < MessageType > m ) ; public < ResponseType , MessageType > Map < Integer , ResponseType > messageMany ( Integer [ ] id , Message < MessageType > m ) ; } </s>
|
<s> package com . smartgrid . messenger ; import java . util . ArrayList ; import java . lang . Class ; import java . util . Iterator ; public final class Message < T > { private String methodName ; private T content ; private Class contentType ; public Message ( String m , T c ) { methodName = m ; content = c ; if ( c != null ) contentType = c . getClass ( ) ; else contentType = null ; } public String getMethodName ( ) { return methodName ; } public T getContent ( ) { return content ; } public Class getContentType ( ) { return contentType ; } } </s>
|
<s> package com . smartgrid . messenger ; import java . util . Map ; import java . util . HashMap ; import java . util . ArrayList ; import java . lang . reflect . InvocationTargetException ; import java . lang . reflect . Method ; import com . smartgrid . messenger . Message ; public final class MessengerBasic < T > implements Messenger < T > { private Map < Integer , T > members ; public MessengerBasic ( Map < Integer , T > members ) { this . members = members ; } public Integer [ ] memberIds ( ) { return members . keySet ( ) . < Integer > toArray ( new Integer [ <NUM_LIT:0> ] ) ; } public < ResponseType , MessageType > ResponseType message ( Integer id , Message < MessageType > m ) { T recepient = getMember ( id ) ; Method target = null ; try { if ( m . getContentType ( ) == null ) target = recepient . getClass ( ) . getMethod ( m . getMethodName ( ) ) ; else target = recepient . getClass ( ) . getMethod ( m . getMethodName ( ) , m . getContentType ( ) ) ; } catch ( SecurityException e ) { System . out . printf ( "<STR_LIT>" , m . getMethodName ( ) ) ; e . printStackTrace ( ) ; } catch ( NoSuchMethodException e ) { System . out . printf ( "<STR_LIT>" , m . getMethodName ( ) ) ; e . printStackTrace ( ) ; } ResponseType r = null ; try { if ( m . getContent ( ) == null ) r = ( ResponseType ) target . invoke ( recepient ) ; else r = ( ResponseType ) target . invoke ( recepient , m . getContent ( ) ) ; } catch ( IllegalArgumentException e ) { System . out . printf ( "<STR_LIT>" , m . getMethodName ( ) ) ; e . printStackTrace ( ) ; } catch ( IllegalAccessException e ) { System . out . printf ( "<STR_LIT>" , m . getMethodName ( ) ) ; e . printStackTrace ( ) ; } catch ( InvocationTargetException e ) { System . out . printf ( "<STR_LIT>" , m . getMethodName ( ) ) ; e . printStackTrace ( ) ; } return r ; } public < ResponseType , MessageType > Map < Integer , ResponseType > messageMany ( Integer [ ] recipients , Message < MessageType > m ) { Map < Integer , ResponseType > response = new HashMap < Integer , ResponseType > ( ) ; for ( Integer id : recipients ) { response . put ( id , this . < ResponseType , MessageType > message ( id , m ) ) ; } return response ; } private T getMember ( int id ) { return members . get ( id ) ; } } </s>
|
<s> package com . smartgrid . policies ; public interface Appliance { public Double getDemand ( ) ; public String getName ( ) ; public Integer getId ( ) ; } </s>
|
<s> package com . smartgrid . policies ; import java . util . ArrayList ; import java . util . Date ; import java . util . List ; import com . smartgrid . policies . Appliance ; import com . smartgrid . policies . GenericAppliance ; import com . smartgrid . app . CustomMessage ; public class CustomHouseholdPolicy implements HouseholdPolicy { private Double demand = <NUM_LIT:0.0> ; private Double previousElectricityPrice = <NUM_LIT:0.0> ; private Double electricityPrice = <NUM_LIT:0.0> ; private boolean priceChange = false ; private List < Appliance > appliances ; public CustomHouseholdPolicy ( ) { appliances = new ArrayList < Appliance > ( ) ; appliances . add ( new GenericAppliance ( <NUM_LIT:1> , <NUM_LIT> ) ) ; appliances . add ( new GenericAppliance ( <NUM_LIT:2> , <NUM_LIT> ) ) ; appliances . add ( new GenericAppliance ( <NUM_LIT:3> , <NUM_LIT> ) ) ; } public void tick ( Date date ) { demand = <NUM_LIT> ; if ( priceChange ) { priceChange = false ; if ( previousElectricityPrice > <NUM_LIT:0> ) { Double percentageChange = ( electricityPrice / previousElectricityPrice ) * <NUM_LIT:100> ; System . out . printf ( "<STR_LIT>" , percentageChange ) ; } } if ( date . getHours ( ) >= <NUM_LIT> && date . getHours ( ) <= <NUM_LIT> ) { demand = <NUM_LIT> ; } } public String getPolicyAuthor ( ) { return "<STR_LIT>" ; } public String getPolicyName ( ) { return "<STR_LIT>" ; } public Double getPolicyVersion ( ) { return <NUM_LIT:1.0> ; } public Double getElectricityDemand ( ) { return demand ; } public List < Appliance > getAppliances ( ) { return appliances ; } public Integer turnOffAppliance ( Appliance appliance ) { return <NUM_LIT:0> ; } public Integer notifyPrice ( Double newPrice ) { if ( newPrice != electricityPrice ) { previousElectricityPrice = electricityPrice ; electricityPrice = newPrice ; priceChange = true ; } return <NUM_LIT:0> ; } public CustomMessage handleMessage ( CustomMessage m ) throws Exception { throw new Exception ( "<STR_LIT>" + m . toString ( ) ) ; } } </s>
|
<s> package com . smartgrid . policies ; import java . util . Date ; import java . util . Map ; import com . smartgrid . app . Aggregator ; public class CustomAggregatorPolicy implements AggregatorPolicy { private final String PolicyName = "<STR_LIT>" ; private final Double PolicyVersion = <NUM_LIT:1.0> ; private final String PolicyAuthor = "<STR_LIT>" ; private Double supply ; private Double price ; public CustomAggregatorPolicy ( ) { supply = <NUM_LIT> ; price = <NUM_LIT> ; } public void tick ( Date date , Aggregator aggregator ) { Map < Integer , Double > demandMap = aggregator . getHouseholdDemandMap ( ) ; double totalDemand = <NUM_LIT:0> ; for ( Double e : demandMap . values ( ) ) totalDemand += e ; System . out . printf ( "<STR_LIT>" , PolicyName , aggregator . getElectricitySupply ( ) , totalDemand ) ; if ( totalDemand >= <NUM_LIT:1000> ) { aggregator . setElectricitySupply ( <NUM_LIT> ) ; aggregator . setElectricityPrice ( <NUM_LIT> ) ; } if ( totalDemand >= <NUM_LIT> ) { aggregator . setElectricitySupply ( <NUM_LIT> ) ; aggregator . setElectricityPrice ( <NUM_LIT> ) ; } if ( totalDemand >= <NUM_LIT> ) { aggregator . setElectricitySupply ( <NUM_LIT> ) ; aggregator . setElectricityPrice ( <NUM_LIT> ) ; } if ( totalDemand >= <NUM_LIT> ) { aggregator . setElectricitySupply ( <NUM_LIT> ) ; aggregator . setElectricityPrice ( <NUM_LIT> ) ; } if ( totalDemand >= <NUM_LIT> ) { aggregator . setElectricitySupply ( <NUM_LIT> ) ; aggregator . setElectricityPrice ( <NUM_LIT> ) ; } } public String getPolicyName ( ) { return PolicyName ; } public Double getPolicyVersion ( ) { return PolicyVersion ; } public String getPolicyAuthor ( ) { return PolicyAuthor ; } public Double getPrice ( ) { return price ; } public Double getSupply ( ) { return supply ; } } </s>
|
<s> package com . smartgrid . policies ; public class GenericAppliance implements Appliance { private Integer id ; private Double demand ; public GenericAppliance ( Integer id , Double demand ) { this . id = id ; this . demand = demand ; } public Double getDemand ( ) { return this . demand ; } public String getName ( ) { return "<STR_LIT>" ; } public Integer getId ( ) { return this . id ; } } </s>
|
<s> package com . smartgrid . policies ; import java . util . Date ; import java . util . List ; import com . smartgrid . policies . Appliance ; import com . smartgrid . app . CustomMessage ; public interface HouseholdPolicy { public void tick ( Date date ) ; public String getPolicyAuthor ( ) ; public String getPolicyName ( ) ; public Double getPolicyVersion ( ) ; public Double getElectricityDemand ( ) ; public List < Appliance > getAppliances ( ) ; public Integer turnOffAppliance ( Appliance appliance ) ; public Integer notifyPrice ( Double newPrice ) ; public CustomMessage handleMessage ( CustomMessage m ) throws Exception ; } </s>
|
<s> package com . smartgrid . policies ; import com . smartgrid . app . Aggregator ; import java . util . Date ; public interface AggregatorPolicy { public String getPolicyName ( ) ; public Double getPolicyVersion ( ) ; public String getPolicyAuthor ( ) ; public void tick ( Date date , Aggregator aggregator ) ; public Double getPrice ( ) ; public Double getSupply ( ) ; } </s>
|
<s> package com . smartgrid . app ; import com . smartgrid . app . Simulator ; import com . smartgrid . app . Logger ; import com . smartgrid . policies . AggregatorPolicy ; import com . smartgrid . policies . CustomAggregatorPolicy ; import com . smartgrid . policies . CustomHouseholdPolicy ; import com . smartgrid . policies . HouseholdPolicy ; import java . util . HashMap ; public class App { public static void main ( String [ ] args ) { Logger logger = new Logger ( "<STR_LIT:localhost>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" ) ; if ( ! logger . open ( ) ) { System . out . println ( "<STR_LIT>" ) ; return ; } else { System . out . println ( "<STR_LIT>" ) ; } HouseholdPolicy tmp = new CustomHouseholdPolicy ( ) ; logger . logHouseholdPolicy ( tmp . getPolicyAuthor ( ) , tmp . getPolicyName ( ) , tmp . getPolicyVersion ( ) ) ; Integer granularity = <NUM_LIT> * <NUM_LIT> ; Long iterations = <NUM_LIT> ; AggregatorPolicy aggregatorPolicy = new CustomAggregatorPolicy ( ) ; logger . logAggregatorPolicy ( aggregatorPolicy . getPolicyAuthor ( ) , aggregatorPolicy . getPolicyName ( ) , aggregatorPolicy . getPolicyVersion ( ) ) ; logger . logRun ( ) ; Integer population = <NUM_LIT> ; HashMap < Integer , Household > households = new HashMap < Integer , Household > ( ) ; for ( Integer i = <NUM_LIT:1> ; i <= population ; i ++ ) { HouseholdPolicy p = new CustomHouseholdPolicy ( ) ; logger . logRunHouseholdConnection ( i , p . getPolicyAuthor ( ) , p . getPolicyName ( ) , p . getPolicyVersion ( ) ) ; Household h = new Household ( i , p ) ; households . put ( i , h ) ; } Simulator simulator = new Simulator ( households , iterations , granularity , aggregatorPolicy , logger ) ; System . out . println ( "<STR_LIT>" ) ; simulator . run ( ) ; System . out . println ( "<STR_LIT>" ) ; logger . close ( ) ; } } </s>
|
<s> package com . smartgrid . app ; import com . smartgrid . messenger . Message ; import com . smartgrid . messenger . Messenger ; import com . smartgrid . messenger . MessengerBasic ; import com . smartgrid . policies . Appliance ; import com . smartgrid . app . Household ; import java . util . Date ; import java . util . HashMap ; import java . util . List ; import java . util . Map ; public class Aggregator { private Map < Integer , Double > householdDemandMap ; private Map < Integer , List < Appliance > > applianceMap ; private Logger logger ; private Double electricitySupply ; private Double electricityPrice ; private Integer [ ] allHouseholdIds ; private Messenger < Household > messenger ; Aggregator ( Messenger < Household > messenger , Logger logger ) { this . messenger = messenger ; allHouseholdIds = messenger . memberIds ( ) ; this . logger = logger ; } public Logger getLogger ( ) { return logger ; } public void setLogger ( Logger logger ) { this . logger = logger ; } public double getElectricitySupply ( ) { return electricitySupply ; } public void setElectricitySupply ( double electricitySupply ) { this . electricitySupply = electricitySupply ; } public Map < Integer , Double > getHouseholdDemandMap ( ) { return householdDemandMap ; } public Map < Integer , List < Appliance > > getHouseholdApplianceMap ( ) { return applianceMap ; } public void updateApplianceMap ( ) { Message < Void > m = new Message < Void > ( "<STR_LIT>" , null ) ; applianceMap = messenger . < List < Appliance > , Void > messageMany ( allHouseholdIds , m ) ; } public Double updateHouseholdDemands ( Date date ) { Message < Void > m = new Message < Void > ( "<STR_LIT>" , null ) ; householdDemandMap = messenger . < Double , Void > messageMany ( allHouseholdIds , m ) ; Double total = <NUM_LIT:0.0> ; for ( Integer i : allHouseholdIds ) { total += householdDemandMap . get ( i ) ; Integer appliances = applianceMap . get ( i ) . size ( ) ; logger . logHouseholdDemand ( i , date , householdDemandMap . get ( i ) , appliances ) ; } return total ; } public Integer turnOffAppliance ( Integer householdId , Appliance appliance ) { Message < Appliance > m = new Message < Appliance > ( "<STR_LIT>" , appliance ) ; return messenger . < Integer , Appliance > message ( householdId , m ) ; } public void setElectricityPrice ( double price ) { electricityPrice = price ; Message < Double > m = new Message < Double > ( "<STR_LIT>" , price ) ; messenger . < Integer , Double > messageMany ( allHouseholdIds , m ) ; } public Double getElectricityPrice ( ) { return electricityPrice ; } public List < Appliance > getAppliances ( Integer householdId ) { return applianceMap . get ( householdId ) ; } } </s>
|
<s> package com . smartgrid . app ; import java . util . HashMap ; import java . util . Date ; import com . smartgrid . app . Aggregator ; import com . smartgrid . messenger . Message ; import com . smartgrid . messenger . Messenger ; import com . smartgrid . messenger . MessengerBasic ; import com . smartgrid . policies . AggregatorPolicy ; import com . smartgrid . policies . HouseholdPolicy ; public class Simulator { private Long tick = <NUM_LIT> ; private Long iterations ; private Long startTime ; private Long currentTime ; private Messenger < Household > messenger ; private Integer granularity ; private AggregatorPolicy aggregatorPolicy ; private Aggregator aggregator ; private Logger logger ; public Simulator ( HashMap < Integer , Household > households , Long iterations , Integer granularity , AggregatorPolicy aggregatorPolicy , Logger logger ) { this . iterations = iterations ; this . granularity = granularity ; this . aggregatorPolicy = aggregatorPolicy ; messenger = new MessengerBasic < Household > ( households ) ; aggregator = new Aggregator ( messenger , logger ) ; aggregator . setElectricitySupply ( aggregatorPolicy . getSupply ( ) ) ; aggregator . setElectricityPrice ( aggregatorPolicy . getPrice ( ) ) ; this . logger = logger ; } private void tick ( Date date ) { messenger . < Void , Date > messageMany ( messenger . memberIds ( ) , new Message < Date > ( "<STR_LIT>" , date ) ) ; aggregator . updateApplianceMap ( ) ; Double overallDemand = aggregator . updateHouseholdDemands ( date ) ; logger . logAggregator ( date , aggregator . getElectricitySupply ( ) , overallDemand , aggregator . getElectricityPrice ( ) ) ; aggregatorPolicy . tick ( date , aggregator ) ; } public void run ( ) { currentTime = ( new Date ( ) ) . getTime ( ) ; while ( tick <= iterations ) { tick ++ ; currentTime += <NUM_LIT> * granularity ; tick ( new Date ( currentTime ) ) ; } } } </s>
|
<s> package com . smartgrid . app ; import com . smartgrid . policies . Appliance ; import com . smartgrid . policies . HouseholdPolicy ; import java . util . Date ; import java . util . List ; public class Household { private Integer householdId ; private HouseholdPolicy policy ; public Household ( Integer householdId , HouseholdPolicy policy ) { this . householdId = householdId ; this . policy = policy ; } private void logMessage ( String msg ) { System . out . printf ( "<STR_LIT>" , policy . getClass ( ) . toString ( ) , householdId , msg ) ; } public void tick ( Date date ) { logMessage ( "<STR_LIT>" ) ; policy . tick ( date ) ; } public Integer getHouseholdId ( ) { return householdId ; } public HouseholdPolicy getPolicy ( ) { return policy ; } public Double getElectricityDemand ( ) { Double demand = policy . getElectricityDemand ( ) ; logMessage ( String . format ( "<STR_LIT>" , demand ) ) ; return demand ; } public List < Appliance > getAppliances ( ) { return policy . getAppliances ( ) ; } public Integer turnOffAppliance ( Appliance appliance ) { logMessage ( "<STR_LIT>" ) ; return policy . turnOffAppliance ( appliance ) ; } public void notifyPrice ( Double newPrice ) { logMessage ( String . format ( "<STR_LIT>" , newPrice ) ) ; policy . notifyPrice ( newPrice ) ; } public CustomMessage handleMessage ( CustomMessage in ) throws Exception { return policy . handleMessage ( in ) ; } @ Override public String toString ( ) { return "<STR_LIT>" + householdId + "<STR_LIT>" + policy . getPolicyAuthor ( ) + "<STR_LIT:U+002CU+0020>" + policy . getPolicyVersion ( ) + "<STR_LIT:>>" ; } } </s>
|
<s> package com . smartgrid . app ; public abstract class CustomMessage { } </s>
|
<s> package com . smartgrid . app ; import java . sql . Connection ; import java . sql . DriverManager ; import java . sql . SQLException ; import java . sql . Statement ; import java . sql . Timestamp ; import java . util . Date ; public class Logger { private Connection con ; private String connectionURL ; private Statement stmt ; public Logger ( ) { con = null ; stmt = null ; connectionURL = "<STR_LIT>" + "<STR_LIT>" ; } public Logger ( String hostname , String database , String username , String password ) { con = null ; stmt = null ; this . connectionURL = "<STR_LIT>" + hostname + "<STR_LIT:/>" + database + "<STR_LIT:?>" + "<STR_LIT>" + username + "<STR_LIT>" + password ; } public boolean open ( ) { try { con = DriverManager . getConnection ( connectionURL ) ; } catch ( SQLException e ) { System . out . println ( "<STR_LIT>" + e . toString ( ) ) ; e . printStackTrace ( ) ; System . exit ( - <NUM_LIT:1> ) ; } try { stmt = con . createStatement ( ) ; } catch ( SQLException e ) { System . out . println ( "<STR_LIT>" + e . toString ( ) ) ; } catch ( Exception e ) { System . out . println ( "<STR_LIT>" + e . toString ( ) ) ; } createTables ( ) ; return true ; } public void close ( ) { try { con . close ( ) ; stmt . close ( ) ; } catch ( SQLException e ) { System . out . println ( "<STR_LIT>" + e . toString ( ) ) ; } } private void createTables ( ) { String query = new String ( ) ; query = "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" ; executeUpdate ( query ) ; query = "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" ; executeUpdate ( query ) ; query = "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" ; executeUpdate ( query ) ; query = "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" ; executeUpdate ( query ) ; query = "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" ; executeUpdate ( query ) ; query = "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" ; executeUpdate ( query ) ; } private boolean executeUpdate ( String query ) { try { stmt . executeUpdate ( query ) ; } catch ( SQLException e ) { System . out . println ( "<STR_LIT>" + e . toString ( ) ) ; e . printStackTrace ( ) ; System . exit ( - <NUM_LIT:1> ) ; } return true ; } public boolean logAggregatorPolicy ( String author , String name , double version ) { String query = new String ( ) ; query = "<STR_LIT>" + "<STR_LIT:'>" + author + "<STR_LIT>" + "<STR_LIT:'>" + name + "<STR_LIT>" + version + "<STR_LIT>" + "<STR_LIT>" + author + "<STR_LIT>" + name + "<STR_LIT>" + version + "<STR_LIT>" + "<STR_LIT:;>" ; if ( executeUpdate ( query ) ) { return true ; } else { return false ; } } public boolean logAggregator ( Date tick , double supply , double overallDemand , double price ) { Timestamp tstamp = new Timestamp ( tick . getTime ( ) ) ; String query = new String ( ) ; query = "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + tstamp . toString ( ) + "<STR_LIT>" + supply + "<STR_LIT:U+002C>" + overallDemand + "<STR_LIT:U+002C>" + price + "<STR_LIT>" ; if ( executeUpdate ( query ) ) { return true ; } else { return false ; } } public boolean logHouseholdPolicy ( String author , String name , double version ) { String query = new String ( ) ; query = "<STR_LIT>" + "<STR_LIT:'>" + author + "<STR_LIT>" + "<STR_LIT:'>" + name + "<STR_LIT>" + version + "<STR_LIT>" + "<STR_LIT>" + author + "<STR_LIT>" + name + "<STR_LIT>" + version + "<STR_LIT>" + "<STR_LIT:;>" ; if ( executeUpdate ( query ) ) { return true ; } else { return false ; } } public boolean logHouseholdDemand ( long householdID , Date tick , double demand , int appliancesOn ) { Timestamp tstamp = new Timestamp ( tick . getTime ( ) ) ; String query = new String ( ) ; query = "<STR_LIT>" + householdID + "<STR_LIT:U+002C>" + "<STR_LIT>" + "<STR_LIT>" + tstamp . toString ( ) + "<STR_LIT>" + demand + "<STR_LIT:U+002C>" + appliancesOn + "<STR_LIT>" ; if ( executeUpdate ( query ) ) { return true ; } else { return false ; } } public boolean logRun ( ) { String query = new String ( ) ; query = "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" ; if ( executeUpdate ( query ) ) { return true ; } else { return false ; } } public boolean logRunHouseholdConnection ( long household_id , String author , String name , double version ) { String query = new String ( ) ; query = "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT:U+002C>" + household_id + "<STR_LIT:U+002C>" + "<STR_LIT>" + "<STR_LIT>" + author + "<STR_LIT>" + name + "<STR_LIT>" + version + "<STR_LIT>" + "<STR_LIT>" ; if ( executeUpdate ( query ) ) { return true ; } else { return false ; } } } </s>
|
<s> package com . smartgrid . messenger ; import com . smartgrid . messenger . MessengerBasic ; import java . util . HashMap ; import java . util . Map ; import junit . framework . Test ; import junit . framework . TestCase ; import junit . framework . TestSuite ; class Person { private String name ; public Person ( String s ) { name = s ; } public Integer anounce ( String s ) { return <NUM_LIT:1> ; } public Integer whats_one_plus_one ( ) { return <NUM_LIT:2> ; } public boolean am_i_happy ( ) { return true ; } } public class MessengerBasicTest extends TestCase { private Map < Integer , Object > members ; Messenger < Person > messenger ; public MessengerBasicTest ( String testName ) { super ( testName ) ; } public static Test suite ( ) { return new TestSuite ( MessengerBasicTest . class ) ; } public void setUp ( ) { members = new HashMap < Integer , Object > ( ) ; members . put ( <NUM_LIT:1> , ( Object ) new Person ( "<STR_LIT>" ) ) ; messenger = new MessengerBasic ( members ) ; } public void testMessageOne ( ) { Integer i = messenger . < Integer , String > message ( <NUM_LIT:1> , new Message < String > ( "<STR_LIT>" , "<STR_LIT>" ) ) ; assertTrue ( i == <NUM_LIT:1> ) ; } public void testMessageNoParameters ( ) { Integer i = messenger . < Integer , Void > message ( <NUM_LIT:1> , new Message < Void > ( "<STR_LIT>" , null ) ) ; assertTrue ( i == <NUM_LIT:2> ) ; } public void testMessageBooleanReturnType ( ) { } public void testMapReturnType ( ) { } public void testMessageMany ( ) { Map < Integer , Person > many_members = new HashMap < Integer , Person > ( ) ; for ( Integer i = <NUM_LIT:0> ; i < <NUM_LIT> ; i ++ ) { many_members . put ( i , new Person ( i . toString ( ) ) ) ; } Messenger < Person > messenger_with_many = new MessengerBasic < Person > ( many_members ) ; Integer [ ] member_ids = many_members . keySet ( ) . < Integer > toArray ( new Integer [ <NUM_LIT:0> ] ) ; Map < Integer , Integer > response = messenger_with_many . < Integer , String > messageMany ( member_ids , new Message < String > ( "<STR_LIT>" , "<STR_LIT>" ) ) ; for ( Integer i = <NUM_LIT:0> ; i < <NUM_LIT> ; i ++ ) { assertTrue ( response . get ( i ) == <NUM_LIT:1> ) ; } } } </s>
|
<s> package com . smartgrid . app ; import junit . framework . Test ; import junit . framework . TestCase ; import junit . framework . TestSuite ; public class AppTest extends TestCase { public AppTest ( String testName ) { super ( testName ) ; } public static Test suite ( ) { return new TestSuite ( AppTest . class ) ; } public void testApp ( ) { assertTrue ( true ) ; } } </s>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.