Actionbar background is not being changed

2019-01-20 01:43发布

问题:

I have tried with the following code to change the background of the actionbar. It works with 4.3 but not below 4.3. With the following code, null background is being set ie. old background is removed but new background is not being set. Please help me.

    public class TestActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.testing);
    }

    /**
     * Callback when button is clicked to change background
     * @param v
     */
    public void onStartClicked(View v) {
        int Min = 0;
        int Max = 2;

        //Random number generator between 0 and 2 inclusive
        int pos = Min + (int) (Math.random() * ((Max - Min) + 1));

        if (pos == 0) {
            getActionBar().setBackgroundDrawable(
                    getResources().getDrawable(R.drawable.header));
        } else if (pos == 1) {
            getActionBar().setBackgroundDrawable(
                    getResources().getDrawable(R.drawable.inbox_header));

        } else if (pos == 2) {
            getActionBar().setBackgroundDrawable(
                    getResources().getDrawable(R.drawable.outbox_header));

        }

    }
}

回答1:

Finally,I found the solution. It was acheived by showing and hiding the title of action bar after setting background.

getActionBar().setBackgroundDrawable(ContextCompat.getDrawable(this,R.drawable.inbox_header)); 
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setDisplayShowTitleEnabled(false);

Thank you all for your concern.



回答2:

The only think that you can do is to call invalidateOptionsMenu () after setting background for actionbar..

 public void onStartClicked(View v) {
        int Min = 0;
        int Max = 2;

        //Random number generator between 0 and 2 inclusive
        int pos = Min + (int) (Math.random() * ((Max - Min) + 1));

        if (pos == 0) {
            getActionBar().setBackgroundDrawable(
                    getResources().getDrawable(R.drawable.header));
        } else if (pos == 1) {
            getActionBar().setBackgroundDrawable(
                    getResources().getDrawable(R.drawable.inbox_header));

        } else if (pos == 2) {
            getActionBar().setBackgroundDrawable(
                    getResources().getDrawable(R.drawable.outbox_header));

        }
       invalidateOptionsMenu();
    }