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

Kha*_*jar 3 android background bitmap bitmapfactory android-actionbar

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

Bitmap b =  BitmapFactory.decodeResource(getResources(), R.drawable.navbarbg);
BitmapDrawable bd = new BitmapDrawable(getResources(), b);
bar.setBackgroundDrawable(bd);
Run Code Online (Sandbox Code Playgroud)

我也尝试了这段代码,但它没有用.

Resources res = getResources();
xpp =res.getXml(R.drawable.actionbar_background);
bitmapDrawable = (BitmapDrawable) BitmapDrawable.createFromXml (res, xpp);
Run Code Online (Sandbox Code Playgroud)

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" />
Run Code Online (Sandbox Code Playgroud)

编辑:我用这个代码工作正常:

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

Kha*_*jar 10

我用这个代码工作得很好:

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


Kan*_*nth 6

你可以通过玩这个来做到styles.xml.这里是一个详细的解释.看看标记的答案.它针对actionbarsherlock进行了解释.但方法是一样的.如果您需要更多细节.请参阅此链接,该链接也由其他回答者提供.

<?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> 
Run Code Online (Sandbox Code Playgroud)

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

<application android:theme="@style/MyTheme" />
Run Code Online (Sandbox Code Playgroud)

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