Saj*_*sbi 5 java string android textview
我为波斯语字符串编写了一个自定义TextView,这个TextView应该将英文数字替换成波斯数字
public class PersianTextView extends TextView {
public PersianTextView(Context context) {
super(context);
}
public PersianTextView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public PersianTextView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
public void setText(CharSequence text, BufferType type) {
String t = text.toString();
t = t.replaceAll("0", "?");
t = t.replaceAll("1", "?");
t = t.replaceAll("2", "?");
t = t.replaceAll("3", "?");
t = t.replaceAll("4", "?");
t = t.replaceAll("5", "?");
t = t.replaceAll("6", "?");
t = t.replaceAll("7", "?");
t = t.replaceAll("8", "?");
t = t.replaceAll("9", "?");
super.setText((CharSequence)t, type);
}
}
Run Code Online (Sandbox Code Playgroud)
此View工作正常,但如果我从HTML设置文本,包含英文数字的链接将不会显示为链接!什么是解决问题最简单的方法?
某种形式需要在链接上进行模式匹配.
private static final Pattern DIGIT_OR_LINK_PATTERN =
Pattern.compile("(\\d|https?:[\\w_/+%?=&.]+)");
// Pattern: (dig|link )
private static final Map<String, String> PERSIAN_DIGITS = new HashMap<>();
static {
PERSIAN_DIGITS.put("0", "?");
PERSIAN_DIGITS.put("1", "?");
PERSIAN_DIGITS.put("2", "?");
PERSIAN_DIGITS.put("3", "?");
PERSIAN_DIGITS.put("4", "?");
PERSIAN_DIGITS.put("5", "?");
PERSIAN_DIGITS.put("6", "?");
PERSIAN_DIGITS.put("7", "?");
PERSIAN_DIGITS.put("8", "?");
PERSIAN_DIGITS.put("9", "?");
}
public static String persianDigits(String s) {
StringBuffer sb = new StringBuffer();
Matcher m = DIGIT_OR_LINK_PATTERN.matcher(s);
while (m.find()) {
String t = m.group(1);
if (t.length() == 1) {
// Digit.
t = PERSIAN_DIGITS.get(t);
}
m.appendReplacement(sb, t);
}
m.appendTail(sb);
return sb.toString();
}
Run Code Online (Sandbox Code Playgroud)
PS
根据文本的不同,最好只替换HTML标记之外的数字,即>
和之间的数字<
.
private static final Pattern DIGIT_OR_LINK_PATTERN =
Pattern.compile("(\\d|<[^>]*>)",
Pattern.DOTALL|Pattern.MULTILINE);
Run Code Online (Sandbox Code Playgroud)