/** * 将text中@某人、#某主题、https://网址的字体加亮,匹配的表情文字以表情显示 * @param text * @param context * @return * @author lvqiyong */ public static SpannableString formatContent(CharSequence text,Context context) { SpannableString spannableString = new SpannableString(text); /* * @[^\\s::]+[::\\s] 匹配@某人 \\[[^0-9]{1,4}\\] 匹配表情 * #([^\\#.]+)# 匹配#某主题 https://t\\.cn/\\w+ 匹配网址 */ Pattern pattern = Pattern.compile("@[^\\s::]+[::\\s]#([^\\#.]+)#https://t\\.cn/\\w+\\[[^0-9]{1,4}\\]"); Matcher matcher = pattern.matcher(spannableString); final Context mcontext = context; while (matcher.find()) { final String match=matcher.group(); if(match.startsWith("@")){ //@某人,加亮字体 spannableString.setSpan(new ClickableSpan() { // 在onClick方法中可以编写单击链接时要执行的动作 @Override public void onClick(View widget) { String username = match; username = username.replace("@", ""); username = username.replace(":", ""); username = username.trim(); Intent intent = new Intent(mcontext,UserInfoActivity.class); intent.putExtra("userid", username); mcontext.startActivity(intent);//跳转到用户信息界面 } }, matcher.start(), matcher.end(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); spannableString.setSpan(new ForegroundColorSpan(0xff0077ff), matcher.start(), matcher.end(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } else if(match.startsWith("#")){ //#某主题 spannableString.setSpan(new ClickableSpan() { // 在onClick方法中可以编写单击链接时要执行的动作 @Override public void onClick(View widget) { String theme = match; theme = theme.replace("#", ""); theme = theme.trim(); Intent intent = new Intent(mcontext,WeiboList.class); Bundle bundle=new Bundle(); bundle.putInt(WeiboList.WEIBO_CATE, WeiboList.CATE_THEME); bundle.putString(WeiboList.THEME, theme); intent.putExtras(bundle); mcontext.startActivity(intent);//跳转到话题信息界面 } }, matcher.start(), matcher.end(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); spannableString.setSpan(new ForegroundColorSpan(0xff0077ff), matcher.start(), matcher.end(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } else if(match.startsWith("https://")){ //匹配网址 spannableString.setSpan(new ClickableSpan() { // 在onClick方法中可以编写单击链接时要执行的动作 @Override public void onClick(View widget) { Uri uri = Uri.parse(match); Intent intent = new Intent(Intent.ACTION_VIEW, uri); mcontext.startActivity(intent); } }, matcher.start(), matcher.end(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); spannableString.setSpan(new ForegroundColorSpan(0xff0077ff), matcher.start(), matcher.end(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } else if(match.startsWith("[")){ //表情 } } return spannableString; }