Setting a background image on a PreferenceActivity

How to set background image on a PreferenceActivity on Android

Screen shot of a PreferenceActivity using a background image in AndroidAfter implementing a PreferenceActivity the other day in an Android app, I realized that a lot of people have problems setting a background image on a PreferenceActivity.

The best way to do it is by defining a Theme with a background image, then setting that Theme for your PreferenceActivity in the Android manifest file.

Define the theme containing the background image

Add a theme in your “styles.xml” file, setting the background image using the windowBackground property. For an example, se below xml snippet.

In my theme I had to inherit the predefined Theme.Light because I have a very bright background. Using the standard Theme would render the fonts in a white color, making them unreadable on the background image being used. (See the image to the right for a screenshot)

<style name="PreferencesTheme" parent="android:Theme.Light">
       <item name="android:windowBackground">@drawable/background_image</item>
</style>

Using a background color instead of a picture

If you prefer to just use a background color instead of an image you can do that as well. Just replace the windowBackground property and use the background property, then set that to a color value (using hardcoded color values like I did in this example is not recommended).

<style name="PreferencesTheme" parent="android:Theme.Light">
       <item name="android:background">#FFEAEAEA</item>
</style>

Connect your Theme to your PreferenceActivity

To set the Theme on your PreferenceActivity you do it by declaring it in the app manifest file.
For an example, se the xml snippet below taken from the “myAppManifest.xml” file.

<activity android:label="@string/app_label"
            android:name=".client.PreferencesActivity"
            android:theme="@style/PreferencesTheme">
      <intent-filter>
      </intent-filter>
</activity>

As you can see I just set the android:theme to the Theme i previously defined in my styles.xml file to get the PreferenceActivity to show the selected background image.

Happy hacking!

 


Check out some other Android articles here

PopupWindow on Android

How to enable Eclipse to phone APK deployment

AlertDialog on Android

Related posts: