2012-12-31 55 views
3

我需要將操作欄的背景更改爲自定義圖像,但每次嘗試使用此代碼時,它都不會改變任何事物。有沒有辦法在Android中通過圖像設置操作欄背景?

Bitmap b = BitmapFactory.decodeResource(getResources(), R.drawable.navbarbg); 
BitmapDrawable bd = new BitmapDrawable(getResources(), b); 
bar.setBackgroundDrawable(bd); 

此外,我試過這段代碼,但它沒有奏效。

Resources res = getResources(); 
xpp =res.getXml(R.drawable.actionbar_background); 
bitmapDrawable = (BitmapDrawable) BitmapDrawable.createFromXml (res, xpp); 

actionbar_background.xml的內容

<?xml version="1.0" encoding="utf-8"?> 
<bitmap xmlns:android="http://schemas.android.com/apk/res/android" 
android:src="@drawable/navbarbg" 
android:tileMode="repeat" /> 

編輯: 我用這個代碼工作得很好:

Bitmap bMap = BitmapFactory.decodeResource(res, R.drawable.action_bar_bg); 
BitmapDrawable actionBarBackground = new BitmapDrawable(res, bMap); 
ActionBar bar = getActionBar(); 
bar.setBackgroundDrawable(actionBarBackground); 

回答

10

我用這個代碼工作得很好:

Bitmap bMap = BitmapFactory.decodeResource(res, R.drawable.action_bar_bg); 
BitmapDrawable actionBarBackground = new BitmapDrawable(res, bMap); 
ActionBar bar = getActionBar(); 
bar.setBackgroundDrawable(actionBarBackground); 
6

你可以做到這一點通過styles.xml.玩弄這裏詳細的explanation。看看標記的答案。它被解釋爲actionbarsherlock。但方法是一樣的。如果你需要更多的細節。請參閱link,這也是由其他答覆者提供的。

<?xml version="1.0" encoding="utf-8"?> 
<resources> 
    <!-- the theme applied to the application or activity --> 
    <style name="MyTheme" parent="@android:style/Theme.Holo"> 
     <!-- Here you are including your actual custom theme in which your own things are defined --> 
     <item name="android:actionBarStyle">@style/MyActionBar</item> 
     <!-- other activity and action bar styles here --> 
    </style> 

    <!-- style for the action bar background which is named as "MyActionBar. The same name is being used in the above style." --> 
    <style name="MyActionBar" parent="@android:style/Widget.Holo.ActionBar"> 
     <item name="android:background">@drawable/actionbar_background</item> 
    </style> 
</resources> 

不要忘記將這個自定義主題包含在manifest文件中,就像下面這樣,以便在整個應用程序中生效。

<application android:theme="@style/MyTheme" /> 

如果您希望它僅用於特定活動,您甚至可以在活動方面包含此主題。希望這可以幫助。

+0

感謝要去檢查一下。 –

+0

整個應用程序和整個listView具有相同的背景,使得一切都看起來很糟糕,我試圖在操作欄上使用它,但沒有發生任何事情。也嘗試將風格添加到活動中,活動中的每件事物都具有無法工作的背景。 –

+0

你可能會錯在某個地方。因爲它的工作原理和我在我的項目中一樣。如果你還沒有得到它,用你的代碼編輯你的問題。 – Kanth

3
getActionBar().setBackgroundDrawable(
    getResources().getDrawable(R.drawable.navbarbg)); 
+0

現在已經棄用了 – moDev

相關問題