2014-09-27 61 views
4

我在一個片段中,當用戶單擊某個按鈕時,我想更改操作欄顏色並查看背景顏色。我目前在下面的代碼會導致無論用戶選擇什麼顏色,操作欄都會變灰。更改AppCompat Action Bar的背景顏色

private void changeColor(int colorId) { 
    ActionBar actionBar = ((ActionBarActivity)getActivity()).getSupportActionBar(); 
    actionBar.setBackgroundDrawable(new ColorDrawable(colorId)); 
    this.getView().setBackgroundColor(getResources().getColor(colorId)); 
} 

我有我的styles.xml中的主題是藍色的操作欄不知道是否有任何效果。如果您有任何建議,請告訴我。

感謝, 彌敦道

解決方案: 後來換:

actionBar.setBackgroundDrawable(new ColorDrawable(colorId)); 

要:

actionBar.setBackgroundDrawable(new ColorDrawable(getResources().getColor(colorId))); 
+0

IM如果從styles.xml刪除您的藍色呢? – joao2fast4u 2014-09-27 02:33:03

+1

同樣的問題,我也注意到,當我嘗試在列表視圖行上設置線性佈局的背景顏色時,我得到相同的灰色。 holder.titleLayout.setBackgroundColor(item.getColorCode()); – Nath5 2014-09-27 02:37:47

+0

@ Nath5,不要回答評論中的問題。 – Confuse 2014-09-27 04:29:53

回答

8

如果我正確理解你的問題,你想在改變顏色的基礎用戶干預,試試這個。使用這一個片段

public void setActionBarColor(int parsedColor){ 
    ActionBar mActionBar = getSupportActionBar(); 
    mActionBar.setBackgroundDrawable(new ColorDrawable(parsedColor)); 
    mActionBar.setDisplayShowTitleEnabled(false); 
    mActionBar.setDisplayShowTitleEnabled(true); 
} 

// check if instance of activity is MyActivity just an example 
MyActivity mA = ((MyActivity)getActivity()); 
mA.setActionBarColor(Color.parseColor("#FFA2C13E")); 

希望它能幫助:)

PS:使用ActionBarActivity