How to create a GalleryDialogPreference
The standard set of preferences does not provide a Gallery preference. This article describes how you can implement a Gallery preference. We do this by making use of a DialogPreference with a custom layout. The layout is done with xml and we also add some custom xml attributes for more control. A sample application is provided to show the working.
We start with creating a GalleryDialogPreference subclass. Extend it from DialogPreference. For our custom xml attributes we create the /res/values/attrs.xml file. The content looks like this:
|<?xml version="1.0" encoding="utf-8"?>
We have one custom attributes defined here:
- galleryItemBackground, the background appearance of the gallery items. This code is the same as the Hello Gallery tutorial from Android.
Within the /res/xml folder we create a settings.xml file where we define our settings. In this sample just our GalleryDialogPreference. See listing below.
The next step is to define the layout for the GalleryDialogPreference. The layout contains a ImageView for showing the current selected image and the Gallery. The layout file can be found within the /res/layout folder and the file is named: gallerydialogpreference_layout.xml.
We override the onCreateDialogView method to inflate the layout, retrieve the persistent value and initialize the widgets. We also apply an ImageAdapter to the gallery. See the Hello Gallery tutorial for more information.
Finally, we override the onClick method of the DialogPreference to persist our new gallery value. We only act on the positive button and if the value must be stored. And that's it. Have fun and don't forget to like, plus or retweet if you like this blog.
The GalleryDialogPreference is used within the following apps:
- Bubbles Live Wallpaper
- Hearts Live Wallpaper
- Lissajous Live Wallpaper
- PCB Live Wallpaper
- Rose Petals Live Wallpaper
- Spyro Live Wallpaper
- Star Trek Clock Widget
- Star Wars Clock Widget