1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87
|
public static SpannableString getWeiBoText(Context context, String text) { Resources res = context.getResources(); Pattern AT_PATTERN = Pattern.compile("@[\\u4e00-\\u9fa5\\w\\-]+"); Pattern TAG_PATTERN = Pattern.compile("#([^\\#|.]+)#"); Pattern Url_PATTERN = Pattern.compile("((http|https|ftp|ftps):\\/\\/)?([a-zA-Z0-9-]+\\.){1,5}(com|cn|net|org|hk|tw)((\\/(\\w|-)+(\\.([a-zA-Z]+))?)+)?(\\/)?(\\??([\\.%:a-zA-Z0-9_-]+=[#\\.%:a-zA-Z0-9_-]+(&)?)+)?"); Pattern EMOJI_PATTER = Pattern.compile("\\[([\u4e00-\u9fa5\\w])+\\]");
SpannableString spannable = new SpannableString(text);
Matcher tag = TAG_PATTERN.matcher(spannable); while (tag.find()) { String tagNameMatch = tag.group(); int start = tag.start(); spannable.setSpan(new MyTagSpan(context, tagNameMatch), start, start + tagNameMatch.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE); }
Matcher at = AT_PATTERN.matcher(spannable); while (at.find()) { String atUserName = at.group(); int start = at.start(); spannable.setSpan(new MyAtSpan(context, atUserName), start, start + atUserName.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE); }
Matcher url = Url_PATTERN.matcher(spannable); while (url.find()) { String urlString = url.group(); int start = url.start(); spannable.setSpan(new MyURLSpan(context, urlString), start, start + urlString.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE); }
Matcher emoji = EMOJI_PATTER.matcher(spannable); while (emoji.find()) { String key = emoji.group(); int start = emoji.start(); Integer imgRes = Emotion.getImgByName(key); System.out.println("@@@"+imgRes); if (imgRes != null) { BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeResource(res, imgRes, options);
int scale = (int) (options.outWidth / 32); options.inJustDecodeBounds = false; options.inSampleSize = scale; Bitmap bitmap = BitmapFactory.decodeResource(res, imgRes, options);
ImageSpan span = new ImageSpan(context, bitmap); spannable.setSpan(span, start, start + key.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); } }
return spannable; }
private static class MyURLSpan extends ClickableSpan { private String mUrl; private Context context;
MyURLSpan(Context ctx, String url) { context = ctx; mUrl = url; }
@Override public void updateDrawState(TextPaint ds) { ds.setColor(Color.parseColor("#f44336")); }
@Override public void onClick(View widget) { Intent intent = UrlActivity.newIntent(context, mUrl); context.startActivity(intent);
} }
|