操作栏背景未更改

时间:2013-08-14 05:29:19

标签: android android-actionbar

我尝试使用以下代码更改操作栏的背景。它适用于4.3但不低于4.3。使用以下代码,正在设置null背景即。旧的背景被删除但新的背景未被设置。 请帮帮我。

    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));

        }

    }
}

2 个答案:

答案 0 :(得分:21)

最后,我找到了解决方案。它是通过在设置背景后显示和隐藏动作栏的标题来实现的。

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

谢谢大家的关注。

答案 1 :(得分:2)

您唯一能做的就是在设置操作栏的背景后调用invalidateOptionsMenu ()

 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();
    }
相关问题