Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  package com.actionbarsherlock;
  
  import static android.view.ViewGroup.LayoutParams.MATCH_PARENT;

Helper for implementing the action bar design pattern across all versions of Android.

This class will manage interaction with a custom action bar based on the Android 4.0 source code. The exposed API mirrors that of its native counterpart and you should refer to its documentation for instruction.

Author(s):
Jake Wharton <jakewharton@gmail.com>
 
 public abstract class ActionBarSherlock {
     protected static final String TAG = "ActionBarSherlock";
     protected static final boolean DEBUG = false;
 
     private static final Class<?>[] CONSTRUCTOR_ARGS = new Class[] { Activity.classint.class };
     private static final HashMap<ImplementationClass<? extends ActionBarSherlock>> IMPLEMENTATIONS =
             new HashMap<ImplementationClass<? extends ActionBarSherlock>>();
 
     static {
         //Register our two built-in implementations
     }


    

Denotes an implementation of ActionBarSherlock which provides an action bar-enhanced experience.

 
     public @interface Implementation {
         static final int DEFAULT_API = -1;
         static final int DEFAULT_DPI = -1;
 
         int api() default ;
         int dpi() default ;
     }


    
Activity interface for menu creation callback.
 
     public interface OnCreatePanelMenuListener {
         public boolean onCreatePanelMenu(int featureIdMenu menu);
     }
    
Activity interface for menu creation callback.
 
     public interface OnCreateOptionsMenuListener {
         public boolean onCreateOptionsMenu(Menu menu);
     }
    
Activity interface for menu item selection callback.
 
     public interface OnMenuItemSelectedListener {
         public boolean onMenuItemSelected(int featureIdMenuItem item);
     }
    
Activity interface for menu item selection callback.
 
     public interface OnOptionsItemSelectedListener {
         public boolean onOptionsItemSelected(MenuItem item);
     }
    
Activity interface for menu preparation callback.
 
     public interface OnPreparePanelListener {
         public boolean onPreparePanel(int featureIdView viewMenu menu);
     }
    
Activity interface for menu preparation callback.
 
     public interface OnPrepareOptionsMenuListener {
         public boolean onPrepareOptionsMenu(Menu menu);
     }
    
Activity interface for action mode finished callback.
 
     public interface OnActionModeFinishedListener {
         public void onActionModeFinished(ActionMode mode);
     }
    
Activity interface for action mode started callback.
 
    public interface OnActionModeStartedListener {
        public void onActionModeStarted(ActionMode mode);
    }


    
If set, the logic in these classes will assume that an android.app.Activity is dispatching all of the required events to the class. This flag should only be used internally or if you are creating your own base activity modeled after one of the included types (e.g., SherlockActivity).
    public static final int FLAG_DELEGATE = 1;


    
Register an ActionBarSherlock implementation.

Parameters:
implementationClass Target implementation class which extends ActionBarSherlock. This class must also be annotated with ActionBarSherlock.Implementation.
    public static void registerImplementation(Class<? extends ActionBarSherlockimplementationClass) {
        if (!implementationClass.isAnnotationPresent(Implementation.class)) {
            throw new IllegalArgumentException("Class " + implementationClass.getSimpleName() + " is not annotated with @Implementation");
        } else if (.containsValue(implementationClass)) {
            if () Log.w("Class " + implementationClass.getSimpleName() + " already registered");
            return;
        }
        Implementation impl = implementationClass.getAnnotation(Implementation.class);
        if () Log.i("Registering " + implementationClass.getSimpleName() + " with qualifier " + impl);
        .put(implimplementationClass);
    }

    
Unregister an ActionBarSherlock implementation. This should be considered very volatile and you should only use it if you know what you are doing. You have been warned.

Parameters:
implementationClass Target implementation class.
Returns:
Boolean indicating whether the class was removed.
    public static boolean unregisterImplementation(Class<? extends ActionBarSherlockimplementationClass) {
        return .values().remove(implementationClass);
    }

    
Wrap an activity with an action bar abstraction which will enable the use of a custom implementation on platforms where a native version does not exist.

Parameters:
activity Activity to wrap.
Returns:
Instance to interact with the action bar.
    public static ActionBarSherlock wrap(Activity activity) {
        return wrap(activity, 0);
    }

    
Wrap an activity with an action bar abstraction which will enable the use of a custom implementation on platforms where a native version does not exist.

Parameters:
activity Owning activity.
flags Option flags to control behavior.
Returns:
Instance to interact with the action bar.
    public static ActionBarSherlock wrap(Activity activityint flags) {
        //Create a local implementation map we can modify
        HashMap<ImplementationClass<? extends ActionBarSherlock>> impls =
                new HashMap<ImplementationClass<? extends ActionBarSherlock>>();
        boolean hasQualfier;
        /* DPI FILTERING */
        hasQualfier = false;
        for (Implementation key : impls.keySet()) {
            //Only honor TVDPI as a specific qualifier
            if (key.dpi() == .) {
                hasQualfier = true;
                break;
            }
        }
        if (hasQualfier) {
            final boolean isTvDpi = activity.getResources().getDisplayMetrics(). == .;
            for (Iterator<Implementationkeys = impls.keySet().iterator(); keys.hasNext(); ) {
                int keyDpi = keys.next().dpi();
                if ((isTvDpi && keyDpi != .)
                        || (!isTvDpi && keyDpi == .)) {
                    keys.remove();
                }
            }
        }
        /* API FILTERING */
        hasQualfier = false;
        for (Implementation key : impls.keySet()) {
            if (key.api() != .) {
                hasQualfier = true;
                break;
            }
        }
        if (hasQualfier) {
            final int runtimeApi = ..;
            int bestApi = 0;
            for (Iterator<Implementationkeys = impls.keySet().iterator(); keys.hasNext(); ) {
                int keyApi = keys.next().api();
                if (keyApi > runtimeApi) {
                    keys.remove();
                } else if (keyApi > bestApi) {
                    bestApi = keyApi;
                }
            }
            for (Iterator<Implementationkeys = impls.keySet().iterator(); keys.hasNext(); ) {
                if (keys.next().api() != bestApi) {
                    keys.remove();
                }
            }
        }
        if (impls.size() > 1) {
            throw new IllegalStateException("More than one implementation matches configuration.");
        }
        if (impls.isEmpty()) {
            throw new IllegalStateException("No implementations match configuration.");
        }
        Class<? extends ActionBarSherlockimpl = impls.values().iterator().next();
        if () Log.i("Using implementation: " + impl.getSimpleName());
        try {
            Constructor<? extends ActionBarSherlockctor = impl.getConstructor();
            return ctor.newInstance(activityflags);
        } catch (NoSuchMethodException e) {
            throw new RuntimeException(e);
        } catch (IllegalArgumentException e) {
            throw new RuntimeException(e);
        } catch (InstantiationException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        } catch (InvocationTargetException e) {
            throw new RuntimeException(e);
        }
    }


    
Activity which is displaying the action bar. Also used for context.
    protected final Activity mActivity;
    
Whether delegating actions for the activity or managing ourselves.
    protected final boolean mIsDelegate;

    
Reference to our custom menu inflater which supports action items.
    protected MenuInflater mMenuInflater;
    protected ActionBarSherlock(Activity activityint flags) {
        if () Log.d("[<ctor>] activity: " + activity + ", flags: " + flags);
         = activity;
         = (flags & ) != 0;
    }


    
Get the current action bar instance.

Returns:
Action bar instance.
    public abstract ActionBar getActionBar();
    ///////////////////////////////////////////////////////////////////////////
    // Lifecycle and interaction callbacks when delegating
    ///////////////////////////////////////////////////////////////////////////

    
Notify action bar of a configuration change event. Should be dispatched after the call to the superclass implementation.
 

Parameters:
newConfig The new device configuration.
Override:
public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); mSherlock.dispatchConfigurationChanged(newConfig); }
    public void dispatchConfigurationChanged(Configuration newConfig) {}

    
Notify the action bar that the activity has finished its resuming. This should be dispatched after the call to the superclass implementation.
 

Override:
protected void onPostResume() { super.onPostResume(); mSherlock.dispatchPostResume(); }
    public void dispatchPostResume() {}

    
Notify the action bar that the activity is pausing. This should be dispatched before the call to the superclass implementation.
 

Override:
protected void onPause() { mSherlock.dispatchPause(); super.onPause(); }
    public void dispatchPause() {}

    
Notify the action bar that the activity is stopping. This should be called before the superclass implementation.

Override:
protected void onStop() { mSherlock.dispatchStop(); super.onStop(); }
    public void dispatchStop() {}

    
    public abstract void dispatchInvalidateOptionsMenu();

    
Notify the action bar that it should display its overflow menu if it is appropriate for the device. The implementation should conditionally call the superclass method only if this method returns false.

Returns:
true if the opening of the menu was handled internally.
Override:
public void openOptionsMenu() { if (!mSherlock.dispatchOpenOptionsMenu()) { super.openOptionsMenu(); } }
    public boolean dispatchOpenOptionsMenu() {
        return false;
    }

    
Notify the action bar that it should close its overflow menu if it is appropriate for the device. This implementation should conditionally call the superclass method only if this method returns false.
 

Returns:
true if the closing of the menu was handled internally.
Override:
public void closeOptionsMenu() { if (!mSherlock.dispatchCloseOptionsMenu()) { super.closeOptionsMenu(); } }
    public boolean dispatchCloseOptionsMenu() {
        return false;
    }

    
Notify the class that the activity has finished its creation. This should be called after the superclass implementation.
 

Parameters:
savedInstanceState If the activity is being re-initialized after previously being shut down then this Bundle contains the data it most recently supplied in Activity.onSaveInstanceState(Bundle)}. Note: Otherwise it is null.
Override:
protected void onPostCreate(Bundle savedInstanceState) { mSherlock.dispatchPostCreate(savedInstanceState); super.onPostCreate(savedInstanceState); }
    public void dispatchPostCreate(Bundle savedInstanceState) {}

    
Notify the action bar that the title has changed and the action bar should be updated to reflect the change. This should be called before the superclass implementation.
  

Parameters:
title New activity title.
color New activity color.
Override:
protected void onTitleChanged(CharSequence title, int color) { mSherlock.dispatchTitleChanged(title, color); super.onTitleChanged(title, color); }
    public void dispatchTitleChanged(CharSequence titleint color) {}

    
Notify the action bar the user has created a key event. This is used to toggle the display of the overflow action item with the menu key and to close the action mode or expanded action item with the back key.
 

Parameters:
event Description of the key event.
Returns:
true if the event was handled.
Override:
public boolean dispatchKeyEvent(KeyEvent event) { if (mSherlock.dispatchKeyEvent(event)) { return true; } return super.dispatchKeyEvent(event); }
    public boolean dispatchKeyEvent(KeyEvent event) {
        return false;
    }

    
Notify the action bar that the Activity has triggered a menu creation which should happen on the conclusion of android.app.Activity.onCreate(android.os.Bundle). This will be used to gain a reference to the native menu for native and overflow binding as well as to indicate when compatibility create should occur for the first time.

Parameters:
menu Activity native menu.
Returns:
true since we always want to say that we have a native
    public abstract boolean dispatchCreateOptionsMenu(android.view.Menu menu);

    
Notify the action bar that the Activity has triggered a menu preparation which usually means that the user has requested the overflow menu via a hardware menu key. You should return the result of this method call and not call the superclass implementation.

Parameters:
menu Activity native menu.
Returns:
true if menu display should proceed.
Override:
public final boolean onPrepareOptionsMenu(android.view.Menu menu) { return mSherlock.dispatchPrepareOptionsMenu(menu); }
    public abstract boolean dispatchPrepareOptionsMenu(android.view.Menu menu);

    
Notify the action bar that a native options menu item has been selected. The implementation should return the result of this method call.

Parameters:
item Options menu item.
Returns:
@{code true} if the selection was handled.
Override:
public final boolean onOptionsItemSelected(android.view.MenuItem item) { return mSherlock.dispatchOptionsItemSelected(item); }
    public abstract boolean dispatchOptionsItemSelected(android.view.MenuItem item);

    
Notify the action bar that the overflow menu has been opened. The implementation should conditionally return true if this method returns true, otherwise return the result of the superclass method.

Parameters:
featureId Window feature which triggered the event.
menu Activity native menu.
Returns:
true if the event was handled by this method.
Override:
public final boolean onMenuOpened(int featureId, android.view.Menu menu) { if (mSherlock.dispatchMenuOpened(featureId, menu)) { return true; } return super.onMenuOpened(featureId, menu); }
    public boolean dispatchMenuOpened(int featureIdandroid.view.Menu menu) {
        return false;
    }

    
Notify the action bar that the overflow menu has been closed. This method should be called before the superclass implementation.

Parameters:
featureId
menu
Override:
public void onPanelClosed(int featureId, android.view.Menu menu) { mSherlock.dispatchPanelClosed(featureId, menu); super.onPanelClosed(featureId, menu); }
    public void dispatchPanelClosed(int featureIdandroid.view.Menu menu) {}

    
Notify the action bar that the activity has been destroyed. This method should be called before the superclass implementation.

Override:
public void onDestroy() { mSherlock.dispatchDestroy(); super.onDestroy(); }
    public void dispatchDestroy() {}
    ///////////////////////////////////////////////////////////////////////////
    ///////////////////////////////////////////////////////////////////////////


    
Internal method to trigger the menu creation process.

Returns:
true if menu creation should proceed.
    protected final boolean callbackCreateOptionsMenu(Menu menu) {
        if () Log.d("[callbackCreateOptionsMenu] menu: " + menu);
        boolean result = true;
        if ( instanceof OnCreatePanelMenuListener) {
            OnCreatePanelMenuListener listener = (OnCreatePanelMenuListener);
            result = listener.onCreatePanelMenu(.menu);
        } else if ( instanceof OnCreateOptionsMenuListener) {
            result = listener.onCreateOptionsMenu(menu);
        }
        if () Log.d("[callbackCreateOptionsMenu] returning " + result);
        return result;
    }

    
Internal method to trigger the menu preparation process.

Returns:
true if menu preparation should proceed.
    protected final boolean callbackPrepareOptionsMenu(Menu menu) {
        if () Log.d("[callbackPrepareOptionsMenu] menu: " + menu);
        boolean result = true;
        if ( instanceof OnPreparePanelListener) {
            OnPreparePanelListener listener = (OnPreparePanelListener);
            result = listener.onPreparePanel(.nullmenu);
        } else if ( instanceof OnPrepareOptionsMenuListener) {
            result = listener.onPrepareOptionsMenu(menu);
        }
        if () Log.d("[callbackPrepareOptionsMenu] returning " + result);
        return result;
    }

    
Internal method for dispatching options menu selection to the owning activity callback.

Parameters:
item Selected options menu item.
Returns:
true if the item selection was handled in the callback.
    protected final boolean callbackOptionsItemSelected(MenuItem item) {
        if () Log.d("[callbackOptionsItemSelected] item: " + item.getTitleCondensed());
        boolean result = false;
        if ( instanceof OnMenuItemSelectedListener) {
            result = listener.onMenuItemSelected(.item);
        } else if ( instanceof OnOptionsItemSelectedListener) {
            result = listener.onOptionsItemSelected(item);
        }
        if () Log.d("[callbackOptionsItemSelected] returning " + result);
        return result;
    }
    ///////////////////////////////////////////////////////////////////////////
    ///////////////////////////////////////////////////////////////////////////


    
Query for the availability of a certain feature.

Parameters:
featureId The feature ID to check.
Returns:
true if feature is enabled, false otherwise.
    public abstract boolean hasFeature(int featureId);

    
Enable extended screen features. This must be called before setContentView(). May be called as many times as desired as long as it is before setContentView(). If not called, no extended features will be available. You can not turn off a feature once it is requested.

Parameters:
featureId The desired features, defined as constants by Window.
Returns:
Returns true if the requested feature is supported and now enabled.
    public abstract boolean requestFeature(int featureId);

    
Set extra options that will influence the UI for this window.

Parameters:
uiOptions Flags specifying extra options for this window.
    public abstract void setUiOptions(int uiOptions);

    
Set extra options that will influence the UI for this window. Only the bits filtered by mask will be modified.

Parameters:
uiOptions Flags specifying extra options for this window.
mask Flags specifying which options should be modified. Others will remain unchanged.
    public abstract void setUiOptions(int uiOptionsint mask);

    
Set the content of the activity inside the action bar.

Parameters:
layoutResId Layout resource ID.
    public abstract void setContentView(int layoutResId);

    
Set the content of the activity inside the action bar.

Parameters:
view The desired content to display.
    public void setContentView(View view) {
        if () Log.d("[setContentView] view: " + view);
    }

    
Set the content of the activity inside the action bar.

Parameters:
view The desired content to display.
params Layout parameters to apply to the view.
    public abstract void setContentView(View viewViewGroup.LayoutParams params);

    
Variation on setContentView(android.view.View,android.view.ViewGroup.LayoutParams) to add an additional content view to the screen. Added after any existing ones on the screen -- existing views are NOT removed.

Parameters:
view The desired content to display.
params Layout parameters for the view.
    public abstract void addContentView(View viewViewGroup.LayoutParams params);

    
Change the title associated with this activity.
    public abstract void setTitle(CharSequence title);

    
Change the title associated with this activity.
    public void setTitle(int resId) {
        if () Log.d("[setTitle] resId: " + resId);
        setTitle(.getString(resId));
    }

    
Sets the visibility of the progress bar in the title.

In order for the progress bar to be shown, the feature must be requested via requestWindowFeature(int).

Parameters:
visible Whether to show the progress bars in the title.
    public abstract void setProgressBarVisibility(boolean visible);

    
Sets the visibility of the indeterminate progress bar in the title.

In order for the progress bar to be shown, the feature must be requested via requestWindowFeature(int).

Parameters:
visible Whether to show the progress bars in the title.
    public abstract void setProgressBarIndeterminateVisibility(boolean visible);

    
Sets whether the horizontal progress bar in the title should be indeterminate (the circular is always indeterminate).

In order for the progress bar to be shown, the feature must be requested via requestWindowFeature(int).

Parameters:
indeterminate Whether the horizontal progress bar should be indeterminate.
    public abstract void setProgressBarIndeterminate(boolean indeterminate);

    
Sets the progress for the progress bars in the title.

In order for the progress bar to be shown, the feature must be requested via requestWindowFeature(int).

Parameters:
progress The progress for the progress bar. Valid ranges are from 0 to 10000 (both inclusive). If 10000 is given, the progress bar will be completely filled and will fade out.
    public abstract void setProgress(int progress);

    
Sets the secondary progress for the progress bar in the title. This progress is drawn between the primary progress (set via setProgress(int) and the background. It can be ideal for media scenarios such as showing the buffering progress while the default progress shows the play progress.

In order for the progress bar to be shown, the feature must be requested via requestWindowFeature(int).

Parameters:
secondaryProgress The secondary progress for the progress bar. Valid ranges are from 0 to 10000 (both inclusive).
    public abstract void setSecondaryProgress(int secondaryProgress);

    
Get a menu inflater instance which supports the newer menu attributes.

Returns:
Menu inflater instance.
    public MenuInflater getMenuInflater() {
        if () Log.d("[getMenuInflater]");
        // Make sure that action views can get an appropriate theme.
        if ( == null) {
            if (getActionBar() != null) {
                 = new MenuInflater(getThemedContext());
            } else {
                 = new MenuInflater();
            }
        }
        return ;
    }
    protected abstract Context getThemedContext();

    
Start an action mode.

Parameters:
callback Callback that will manage lifecycle events for this context mode.
Returns:
The ContextMode that was started, or null if it was canceled.
See also:
com.actionbarsherlock.view.ActionMode
    public abstract ActionMode startActionMode(ActionMode.Callback callback);
New to GrepCode? Check out our FAQ X