有没有办法在android中设置动作栏背景图像?

时间:2012-12-31 16:52:46

标签: android background bitmap android-actionbar bitmapfactory

我需要将操作栏的背景更改为自定义图像,但每次我尝试使用此代码时都不会更改。

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

3 个答案:

答案 0 :(得分:10)

我使用的代码运行良好:

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

答案 1 :(得分: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> 

不要忘记将此自定义主题包含在清单文件中,如下所示,以便在整个应用程序中生效。

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

如果您希望仅在特定活动中使用此主题,您甚至可以在活动中包含此主题。希望这会有所帮助。

答案 2 :(得分:3)

getActionBar().setBackgroundDrawable(
    getResources().getDrawable(R.drawable.navbarbg));
相关问题