在android中我们有时候需要对一些标示性的文字进行高亮【用不同的颜色显示】,例如微博中的@**等等。。。这些特效是通过SpannableString这个类来实现的
思路是将要显示的string进行一次封装str = "#jone# 我的小小测试关于微博中的高亮呵呵呵#jone# 大家都来看看啊@王璇 http://www.jone.cn";spannableString = new SpannableString(str);,然后通过设置SpannableString的setSpan来设置不同的显示效果直接上代码:
package com.example.actiser;
import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import android.os.Bundle; import android.os.Handler; import android.app.Activity; import android.content.Intent; import android.graphics.Color; import android.graphics.drawable.Drawable; import android.text.Spannable; import android.text.SpannableString; import android.text.style.ForegroundColorSpan; import android.text.style.ImageSpan; import android.view.Menu; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; public class MainActivity extends Activity { public TextView txt; final String START = "start"; final String END = "end"; String str =""; final String TOPIC = "#.+?#"; final String NAMEH = "@([\u4e00-\u9fa5A-Za-z0-9_]*)"; final String URLH = "http://.*"; SpannableString spannableString; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); txt = (TextView) findViewById(R.id.tv); str = "#jone# 我的小小测试关于微博中的高亮呵呵呵#jone# 大家都来看看啊@王璇 http://www.jone.cn"; spannableString = new SpannableString(str); heightLight(TOPIC,Color.BLUE); heightLight(NAMEH,Color.RED); heightLight(URLH,Color.GREEN); txt.setText(spannableString); } private void heightLight(String pattern,int color){ ArrayList<Map<String,String>> lists = getStartAndEnd(Pattern.compile(pattern)); for(Map<String,String> str:lists){ ForegroundColorSpan span = new ForegroundColorSpan(color); spannableString.setSpan(span,Integer.parseInt(str.get(START)), Integer.parseInt(str.get(END)), Spannable.SPAN_EXCLUSIVE_INCLUSIVE); } } private ArrayList<Map<String,String>> getStartAndEnd(Pattern pattern){ ArrayList<Map<String,String>> lists = new ArrayList<Map<String,String>>(0); Matcher matcher = pattern.matcher(str); while(matcher.find()){ Map<String,String> map = new HashMap<String, String>(0); map.put(START, matcher.start()+""); map.put(END, matcher.end()+""); lists.add(map); } return lists; } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } }这里是原工程
下一篇接受如何通过代码展示不同的表情图像