Created
August 30, 2017 07:53
-
-
Save hector6872/f214f0391f20610f502c085c54b3079f to your computer and use it in GitHub Desktop.
StringSpan - String.format that works with Android Spannables
This file contains hidden or 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
// based on: https://github.com/george-steel/android-utils/blob/master/src/org/oshkimaadziig/george/androidutils/SpanFormatter.java | |
public class StringSpan { | |
private static final Pattern PATTERN = Pattern.compile("%([^a-zA-z%]*)([[a-zA-Z%]&&[^tT]]|[tT][a-zA-Z])"); | |
private StringSpan() { | |
} | |
public static CharSequence format(@NonNull CharSequence format, Object... args) { | |
return format(Locale.getDefault(), format, args); | |
} | |
@SuppressWarnings("ConstantConditions") | |
public static CharSequence format(@NonNull Locale locale, @NonNull CharSequence format, Object... args) { | |
if (locale == null || format == null) { | |
return format; | |
} | |
SpannableStringBuilder result = new SpannableStringBuilder(format); | |
int startPosition = 0; | |
int argPosition = -1; | |
while (startPosition < result.length()) { | |
Matcher matcher = PATTERN.matcher(result); | |
if (!matcher.find(startPosition)) { | |
break; | |
} | |
startPosition = matcher.start(); | |
int endPosition = matcher.end(); | |
String modifier = matcher.group(1); | |
String type = matcher.group(2); | |
argPosition++; | |
CharSequence charSequence; | |
if (type.equals("%")) { | |
charSequence = "%"; | |
} else if (type.equals("n")) { | |
charSequence = "\n"; | |
} else { | |
Object arg = args[argPosition]; | |
charSequence = arg instanceof Spanned && type.equals("s") ? (Spanned) arg : String.format(locale, "%" + modifier + type, arg); | |
} | |
result.replace(startPosition, endPosition, charSequence); | |
startPosition += charSequence.length(); | |
} | |
return result; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment