Skip to content

Instantly share code, notes, and snippets.

@JGeraldoLima
Last active March 20, 2018 16:13
Show Gist options
  • Save JGeraldoLima/fc6c8f36a6a113ba9afc6e1b05de01c2 to your computer and use it in GitHub Desktop.
Save JGeraldoLima/fc6c8f36a6a113ba9afc6e1b05de01c2 to your computer and use it in GitHub Desktop.
Android TimeZone preference using 100% native resources, with no need to read timezones from external files. Automatically sorted and translated.
package <your_package>;
import android.content.Context;
import android.util.AttributeSet;
/* You can use default ListPreference if you prefer.
Got this lib from <link>https://github.com/afollestad/material-dialogs</link>
*/
import com.afollestad.materialdialogs.prefs.MaterialListPreference;
import java.util.HashMap;
import java.util.Map;
import java.util.TimeZone;
import java.util.TreeMap;
public class TimeZonePreference extends MaterialListPreference {
public TimeZonePreference(Context context) {
super(context);
this.init();
}
public TimeZonePreference(Context context, AttributeSet attrs) {
super(context, attrs);
this.init();
}
private void init() {
String[] timezones = TimeZone.getAvailableIDs();
Map<String, String> unsortedTimezonesMap = new HashMap<>();
for (String timezoneId : timezones) {
String timezoneName = TimeZone.getTimeZone(timezoneId).getDisplayName();
if (timezoneId.trim().length() > 0 && unsortedTimezonesMap.get(timezoneName) == null) {
unsortedTimezonesMap.put(timezoneId, timezoneName);
}
}
Map<String, String> sortedTimezonesMap = new TreeMap<>(unsortedTimezonesMap);
String[] countriesCodesArray = new String[unsortedTimezonesMap.size()];
String[] countriesNamesArray = new String[unsortedTimezonesMap.size()];
this.setEntryValues(sortedTimezonesMap.values().toArray(countriesCodesArray));
this.setEntries(sortedTimezonesMap.keySet().toArray(countriesNamesArray));
}
}
/* To use on your pref.xml */
/***************************************************
<<your_package>.TimeZonePreference
android:defaultValue=""
android:key="user_timezone"
android:negativeButtonText="@null"
android:positiveButtonText="@null"
android:summary=""
android:title="@string/pref_timezone"/>
/**************************************************/
/* Here's an util method to get a TimeZone name to set on your PreferencesFragment */
/****************************************
private String getTimeZoneNameByCode() {
String currentPreferenceValue = userSharedPreferences.getString(Constants.PREFS_USER_TIMEZONE, Constants
.EMPTY);
String timeZoneCode = currentPreferenceValue.equals(Constants.EMPTY) ? TimeZone.getDefault().getID() :
currentPreferenceValue;
TimeZone tz = TimeZone.getTimeZone(timeZoneCode);
return tz.getDisplayName();
}
****************************************/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment