Skip to content

Instantly share code, notes, and snippets.

@bsara
Last active May 25, 2020 18:31
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bsara/b73fca6be70764c08f0c to your computer and use it in GitHub Desktop.
Save bsara/b73fca6be70764c08f0c to your computer and use it in GitHub Desktop.
Android Preference for Selecting a Time Zone
/*
The MIT License (MIT)
Copyright (c) 2014 Brandon Dale Sara
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
import java.util.Calendar;
import java.util.TimeZone;
import android.content.Context;
import android.content.res.TypedArray;
import android.preference.ListPreference;
import android.util.AttributeSet;
import org.apache.commons.lang3.StringUtils;
public class TimeZonePreference extends ListPreference {
//region Constructors
public TimeZonePreference(Context context) {
super(context);
this.init();
}
public TimeZonePreference(Context context, AttributeSet attrs) {
super(context, attrs);
this.init();
}
private void init() {
this.setEntries(TimeZone.getAvailableIDs());
this.setEntryValues(this.getEntries());
}
// endregion
@Override
protected Object onGetDefaultValue(TypedArray a, int index) {
return StringUtils.defaultIfBlank(a.getString(index), Calendar.getInstance().getTimeZone().getID());
}
@Override
public CharSequence getSummary() {
return StringUtils.defaultIfBlank(this.getValue(), "None");
}
}
@bsara
Copy link
Author

bsara commented Sep 17, 2014

For this class to work as is, you'll need to add a reference in your project to Apache Commons Lang >= 3.3.2.

If you don't want to add that reference, you can replace lines 44 and 50 with the same logic that [StringUtils.defaultIfBlank](http://commons.apache.org/proper/commons-lang/javadocs/api-release/org/apache/commons/lang3/StringUtils.html#defaultIfBlank%28T, T%29) provides.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment