Last active
August 29, 2015 14:02
-
-
Save NikolaDespotoski/7827caf6df2931b66ac0 to your computer and use it in GitHub Desktop.
textView.setAllCaps() backward compatibility below ICS
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class AllCapsMethodTransformationCompat implements TransformationMethod { | |
private static AllCapsMethodTransformationCompat sInstance; | |
private static AllCapsMethodTransformationCompat sKeepOriginalInstance; | |
private boolean mAllCaps = false; | |
private String mOriginalString; | |
public AllCapsMethodTransformationCompat(String string) { | |
mOriginalString = string; | |
} | |
public AllCapsMethodTransformationCompat() { | |
mAllCaps = true; | |
} | |
public static AllCapsMethodTransformationCompat getInstance(){ | |
if(sInstance == null){ | |
sInstance = new AllCapsMethodTransformationCompat(); | |
} | |
return sInstance; | |
} | |
private static TransformationMethod getInstance(String string) { | |
if(sKeepOriginalInstance == null){ | |
sKeepOriginalInstance = new AllCapsMethodTransformationCompat(string); | |
} | |
return sInstance; | |
} | |
@Override | |
public CharSequence getTransformation(CharSequence source, View view) { | |
return !TextUtils.isEmpty(source) && mAllCaps | |
? | |
source.toString().toUpperCase(view.getContext().getResources().getConfiguration().locale) | |
: keepOriginal()? mOriginalString : | |
source; | |
} | |
private boolean keepOriginal() { | |
return !TextUtils.isEmpty(mOriginalString) && !mAllCaps; | |
} | |
@Override | |
public void onFocusChanged(View view, CharSequence sourceText, | |
boolean focused, int direction, Rect previouslyFocusedRect) { | |
// TODO Auto-generated method stub | |
} | |
public static void setAllCaps(TextView textView, boolean allCaps) { | |
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH){ | |
textView.setAllCaps(allCaps); | |
}else{ | |
textView.setTransformationMethod(allCaps ? getInstance() : null); | |
} | |
} | |
//---Usage | |
public static void setAllCaps(TextView textView, int stringResId, boolean allCaps) { | |
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH){ | |
textView.setAllCaps(allCaps); | |
}else{ | |
textView.setTransformationMethod(allCaps ? getInstance() : getInstance(textView.getContext().getString(stringResId))); | |
} | |
} | |
public static void setAllCaps(TextView textView, String string, boolean allCaps) { | |
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH){ | |
textView.setAllCaps(allCaps); | |
}else{ | |
textView.setTransformationMethod(allCaps ? getInstance() : getInstance(string)); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment