Search code examples
androidandroid-actionbarandroid-holo-everywhere

How can I use getSupportActionBar() is to make changes from another class


UPDATE: Edited with working code!

I have a class (ColorChanger) where I'm trying to change the color of the actionbars from other activities, except getSupportActionBar() is undefined from my ColorChanger class. How can I do this properly?

Working code from ColorChanger:

public void changeColor(int newColor, Context context, Activity activity) {

    this.mActivity = activity;
    Drawable colorDrawable = new ColorDrawable(newColor);
    Drawable bottomDrawable = context.getResources().getDrawable(
            R.drawable.actionbar_bottom);
    LayerDrawable ld = new LayerDrawable(new Drawable[] { colorDrawable,
            bottomDrawable });

    if (oldBackground == null) {

        this.mActivity.getSupportActionBar().setBackgroundDrawable(ld);

    } else {

        TransitionDrawable td = new TransitionDrawable(new Drawable[] {
                oldBackground, ld });

        this.mActivity.getSupportActionBar().setBackgroundDrawable(td);

        td.startTransition(200);

    }

    oldBackground = ld;

    this.mActivity.getSupportActionBar().setDisplayShowTitleEnabled(false);
    this.mActivity.getSupportActionBar().setDisplayShowTitleEnabled(true);

    currentColor = newColor;

}

If you need more code, just ask.


Solution

  • getSupportActionBar() is a method from the SherlockActivity class, as you can see here

    If your class is not extending SherlockActivity, you can't use that method.

    To use it you have two options:

    1.You can create your ColorChange class as a private class inside a class that extends SherlockActivity.

    2.Pass a reference of the SherlockActivity to your ColorChange class, in the constructor for example:

    public ColorChange(SherlockActivity cActivity){
    
    this.callingActivity = cActivity;
    
    }
    

    And then from your method:

    this.callingActivity.getSupportActionBar()
    

    Hope that helps!