Skip to content

Instantly share code, notes, and snippets.

@justjanne justjanne/
Last active Jan 26, 2016

What would you like to do?
public abstract class Settings {
@Preference(key="pref_theme_id") String themeId;
@Preference boolean fullHostmask;
int textSize;
public final class WrappedSettings {
public final BooleanPreference fullHostmask;
public final IntPreference textSize;
public final StringPreference themeId;
public WrappedSettings(SharedPreferences pref) {
this.fullHostmask = new BooleanPreference(pref, "pref_full_hostmask", null);
this.textSize = new IntPreference(pref, "pref_text_size", null);
this.themeId = new StringPreference(pref, "pref_theme_id", null);
pref.registerOnSharedPreferenceChangeListener(new SharedPreferences.OnSharedPreferenceChangeListener() {
public void onSharedPreferenceChanged(SharedPreferences preferences, String key) {
if (key == "pref_full_hostmask") fullHostmask.change();
if (key == "pref_text_size") textSize.change();
if (key == "pref_theme_id") themeId.change();
public WrappedSettings(Context ctx) {
this(ctx.getSharedPreferences("de.kuschku.testapp", 0));
public class StringPreference extends AbstractPreferenceElement<String> {
public StringPreference(SharedPreferences pref, String key, String init) {
super(pref, key, init);
protected void put(String value) {
edit.putString(key, value);
public String get() {
return pref.getString(key, defValue);
public abstract class AbstractPreferenceElement<T> implements PreferenceElement<T>, OnChangeListener<T> {
private final Set<OnChangeListener<T>> listeners = new HashSet<>();
protected SharedPreferences pref;
protected SharedPreferences.Editor edit;
protected String key;
protected T defValue;
public AbstractPreferenceElement(SharedPreferences pref, String key, T defValue) {
this.pref = pref;
this.key = key;
this.defValue = defValue;
public void change() {
public void change(T value) {
for (OnChangeListener<T> listener : listeners)
public void addChangeListener(OnChangeListener<T> listener) {
public void removeChangeListener(OnChangeListener<T> listener) {
protected abstract void put(T value);
public void batch(SharedPreferences.Editor edit) {
if (this.edit != null) this.edit.commit();
this.edit = edit;
public void set(T value) {
edit = pref.edit();
public interface PreferenceElement<T> {
void addChangeListener(OnChangeListener<T> listener);
void removeChangeListener(OnChangeListener<T> listener);
T get();
void set(T value);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.