原地址:http://gundumw100.iteye.com/blog/904107
EditText通常用于显示文字,但有时候也需要在文字中夹杂一些图片,比如QQ中就可以使用表情图片,又比如需要的文字高亮显示等等,如何在android中也做到这样呢?
记得android中有个android.text包,这里提供了对文本的强大的处理功能。
添加图片主要用SpannableString和ImageSpan类:
- Drawable drawable = getResources().getDrawable(id);
- drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
-
- SpannableString spannable = new SpannableString(getText().toString()+"[smile]");
-
- ImageSpan span = new ImageSpan(drawable, ImageSpan.ALIGN_BASELINE);
-
-
- spannable.setSpan(span, getText().length(),getText().length()+"[smile]".length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
- setText(spannable);
Drawable drawable = getResources().getDrawable(id);
drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
//需要处理的文本,[smile]是需要被替代的文本
SpannableString spannable = new SpannableString(getText().toString()+"[smile]");
//要让图片替代指定的文字就要用ImageSpan
ImageSpan span = new ImageSpan(drawable, ImageSpan.ALIGN_BASELINE);
//开始替换,注意第2和第3个参数表示从哪里开始替换到哪里替换结束(start和end)
//最后一个参数类似数学中的集合,[5,12)表示从5到12,包括5但不包括12
spannable.setSpan(span, getText().length(),getText().length()+"[smile]".length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
setText(spannable);
将需要的文字高亮显示:
- public void highlight(int start,int end){
- SpannableStringBuilder spannable=new SpannableStringBuilder(getText().toString());
- ForegroundColorSpan span=new ForegroundColorSpan(Color.RED);
- spannable.setSpan(span, start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
- setText(spannable);
- }
public void highlight(int start,int end){
SpannableStringBuilder spannable=new SpannableStringBuilder(getText().toString());//用于可变字符串
ForegroundColorSpan span=new ForegroundColorSpan(Color.RED);
spannable.setSpan(span, start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
setText(spannable);
}
加下划线:
- public void underline(int start,int end){
- SpannableStringBuilder spannable=new SpannableStringBuilder(getText().toString());
- CharacterStyle span=new UnderlineSpan();
- spannable.setSpan(span, start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
- setText(spannable);
- }
public void underline(int start,int end){
SpannableStringBuilder spannable=new SpannableStringBuilder(getText().toString());
CharacterStyle span=new UnderlineSpan();
spannable.setSpan(span, start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
setText(spannable);
}
组合运用:
- SpannableStringBuilder spannable=new SpannableStringBuilder(getText().toString());
- CharacterStyle span_1=new StyleSpan(android.graphics.Typeface.ITALIC);
- CharacterStyle span_2=new ForegroundColorSpan(Color.RED);
- spannable.setSpan(span_1, start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
- spannable.setSpan(span_2, start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
- setText(spannable);
SpannableStringBuilder spannable=new SpannableStringBuilder(getText().toString());
CharacterStyle span_1=new StyleSpan(android.graphics.Typeface.ITALIC);
CharacterStyle span_2=new ForegroundColorSpan(Color.RED);
spannable.setSpan(span_1, start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
spannable.setSpan(span_2, start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
setText(spannable);
-
-
-
-
-
-
-
- public SpannableStringBuilder highlight(String text,int color1,int color2,int fontSize){
- SpannableStringBuilder spannable=new SpannableStringBuilder(text);
- CharacterStyle span_0=null,span_1=null,span_2;
- int end=text.indexOf("\n");
- if(end==-1){
- span_0=new ForegroundColorSpan(color1);
- spannable.setSpan(span_0, 0, text.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
- }else{
- span_0=new ForegroundColorSpan(color1);
- span_1=new ForegroundColorSpan(color2);
- spannable.setSpan(span_0, 0, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
- spannable.setSpan(span_1, end+1, text.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
-
- span_2=new AbsoluteSizeSpan(fontSize);
- spannable.setSpan(span_2, end+1, text.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
- }
- return spannable;
- }
/**
* 带有\n换行符的字符串都可以用此方法显示2种颜色
* @param text
* @param color1
* @param color2
* @return
*/
public SpannableStringBuilder highlight(String text,int color1,int color2,int fontSize){
SpannableStringBuilder spannable=new SpannableStringBuilder(text);//用于可变字符串
CharacterStyle span_0=null,span_1=null,span_2;
int end=text.indexOf("\n");
if(end==-1){//如果没有换行符就使用第一种颜色显示
span_0=new ForegroundColorSpan(color1);
spannable.setSpan(span_0, 0, text.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
}else{
span_0=new ForegroundColorSpan(color1);
span_1=new ForegroundColorSpan(color2);
spannable.setSpan(span_0, 0, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
spannable.setSpan(span_1, end+1, text.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
span_2=new AbsoluteSizeSpan(fontSize);//字体大小
spannable.setSpan(span_2, end+1, text.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
}
return spannable;
}
以上实际都是Html.fromHtml(html)的代码实现形式。
另外有个问题:如何让一个TextView中的关键字高亮显示?
http://www.eoeandroid.com/forum.php?mod=viewthread&tid=57880&page=1&extra=#pid558440
解决如下:
-
-
-
-
- public void highlight(String target){
- String temp=getText().toString();
- SpannableStringBuilder spannable = new SpannableStringBuilder(temp);
- CharacterStyle span=null;
-
- Pattern p = Pattern.compile(target);
- Matcher m = p.matcher(temp);
- while (m.find()) {
- span = new ForegroundColorSpan(Color.RED);
- spannable.setSpan(span, m.start(), m.end(),Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
- }
- setText(spannable);
- }
/**
* 关键字高亮显示
* @param target 需要高亮的关键字
*/
public void highlight(String target){
String temp=getText().toString();
SpannableStringBuilder spannable = new SpannableStringBuilder(temp);
CharacterStyle span=null;
Pattern p = Pattern.compile(target);
Matcher m = p.matcher(temp);
while (m.find()) {
span = new ForegroundColorSpan(Color.RED);//需要重复!
spannable.setSpan(span, m.start(), m.end(),Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
}
setText(spannable);
}
循环太慢,不知道有没有简单高效的方法?
下面给出一个类,专门用于将指定的文字转换成表情显示,当然使用前表情图片需要先导入drawable,另外表情图片的数量需要和数组定义的长度一致!否则抛参数异常。
- import android.content.Context;
- import android.text.Spannable;
- import android.text.SpannableStringBuilder;
- import android.text.style.ImageSpan;
- import android.util.Log;
- import java.util.HashMap;
- import java.util.regex.Matcher;
- import java.util.regex.Pattern;
-
- public class SmileyParser {
- private Context mContext;
- private String[] mSmileyTexts;
- private Pattern mPattern;
- private HashMap<String, Integer> mSmileyToRes;
- public static final int[] DEFAULT_SMILEY_RES_IDS = {
- R.drawable.aini,
- R.drawable.aoteman,
- R.drawable.baibai,
- R.drawable.baobao,
- R.drawable.beiju,
- R.drawable.beishang,
- R.drawable.bianbian,
- R.drawable.bishi,
- R.drawable.bizui,
- R.drawable.buyao,
- R.drawable.chanzui,
- };
-
- public SmileyParser(Context context) {
- mContext = context;
- mSmileyTexts = mContext.getResources().getStringArray(DEFAULT_SMILEY_TEXTS);
- mSmileyToRes = buildSmileyToRes();
- mPattern = buildPattern();
- }
-
- public static final int DEFAULT_SMILEY_TEXTS = R.array.default_smiley_texts;
-
- private HashMap<String, Integer> buildSmileyToRes() {
- if (DEFAULT_SMILEY_RES_IDS.length != mSmileyTexts.length) {
-
-
- throw new IllegalStateException("Smiley resource ID/text mismatch");
- }
-
- HashMap<String, Integer> smileyToRes = new HashMap<String, Integer>(mSmileyTexts.length);
- for (int i = 0; i < mSmileyTexts.length; i++) {
- smileyToRes.put(mSmileyTexts[i], DEFAULT_SMILEY_RES_IDS[i]);
- }
-
- return smileyToRes;
- }
-
-
- private Pattern buildPattern() {
- StringBuilder patternString = new StringBuilder(mSmileyTexts.length * 3);
- patternString.append('(');
- for (String s : mSmileyTexts) {
- patternString.append(Pattern.quote(s));
- patternString.append('|');
- }
- patternString.replace(patternString.length() - 1, patternString.length(), ")");
-
- return Pattern.compile(patternString.toString());
- }
-
-
- public CharSequence replace(CharSequence text) {
- SpannableStringBuilder builder = new SpannableStringBuilder(text);
- Matcher matcher = mPattern.matcher(text);
- while (matcher.find()) {
- int resId = mSmileyToRes.get(matcher.group());
- builder.setSpan(new ImageSpan(mContext, resId),matcher.start(), matcher.end(),Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
- }
- return builder;
- }
- }
import android.content.Context;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.style.ImageSpan;
import android.util.Log;
import java.util.HashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class SmileyParser {
private Context mContext;
private String[] mSmileyTexts;
private Pattern mPattern;
private HashMap<String, Integer> mSmileyToRes;
public static final int[] DEFAULT_SMILEY_RES_IDS = {
R.drawable.aini,
R.drawable.aoteman,
R.drawable.baibai,
R.drawable.baobao,
R.drawable.beiju,
R.drawable.beishang,
R.drawable.bianbian,
R.drawable.bishi,
R.drawable.bizui,
R.drawable.buyao,
R.drawable.chanzui,
};
public SmileyParser(Context context) {
mContext = context;
mSmileyTexts = mContext.getResources().getStringArray(DEFAULT_SMILEY_TEXTS);
mSmileyToRes = buildSmileyToRes();
mPattern = buildPattern();
}
public static final int DEFAULT_SMILEY_TEXTS = R.array.default_smiley_texts;
private HashMap<String, Integer> buildSmileyToRes() {
if (DEFAULT_SMILEY_RES_IDS.length != mSmileyTexts.length) {
// Log.w("SmileyParser", "Smiley resource ID/text mismatch");
//表情的数量需要和数组定义的长度一致!
throw new IllegalStateException("Smiley resource ID/text mismatch");
}
HashMap<String, Integer> smileyToRes = new HashMap<String, Integer>(mSmileyTexts.length);
for (int i = 0; i < mSmileyTexts.length; i++) {
smileyToRes.put(mSmileyTexts[i], DEFAULT_SMILEY_RES_IDS[i]);
}
return smileyToRes;
}
//构建正则表达式
private Pattern buildPattern() {
StringBuilder patternString = new StringBuilder(mSmileyTexts.length * 3);
patternString.append('(');
for (String s : mSmileyTexts) {
patternString.append(Pattern.quote(s));
patternString.append('|');
}
patternString.replace(patternString.length() - 1, patternString.length(), ")");
return Pattern.compile(patternString.toString());
}
//根据文本替换成图片
public CharSequence replace(CharSequence text) {
SpannableStringBuilder builder = new SpannableStringBuilder(text);
Matcher matcher = mPattern.matcher(text);
while (matcher.find()) {
int resId = mSmileyToRes.get(matcher.group());
builder.setSpan(new ImageSpan(mContext, resId),matcher.start(), matcher.end(),Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
}
return builder;
}
}
在res/arrays.xml中添加数组:
- <?xml version="1.0" encoding="UTF-8"?>
- <resources xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
- <string-array name="default_smiley_texts">
- <item >[爱你]</item>
- <item >[机器人]</item>
- <item >[拜拜]</item>
- <item >[抱抱]</item>
- <item >[悲剧]</item>
- <item >[悲伤]</item>
- <item >[便便]</item>
- <item >[鄙视]</item>
- <item >[闭嘴]</item>
- <item >[不要]</item>
- <item >[馋嘴]</item>
- </string-array>
- </resources>
<?xml version="1.0" encoding="UTF-8"?>
<resources xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
<string-array name="default_smiley_texts">
<item >[爱你]</item>
<item >[机器人]</item>
<item >[拜拜]</item>
<item >[抱抱]</item>
<item >[悲剧]</item>
<item >[悲伤]</item>
<item >[便便]</item>
<item >[鄙视]</item>
<item >[闭嘴]</item>
<item >[不要]</item>
<item >[馋嘴]</item>
</string-array>
</resources>
使用:
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
-
- TextView tvShow = (TextView) findViewById(R.id.tvShow);
- TextView tvSource = (TextView) findViewById(R.id.tvSource);
-
- SmileyParser parser = new SmileyParser(this);
- String text = "[鄙视][爱你][便便][馋嘴][机器人]";
- tvSource.setText("原文:"+text);
- tvShow.setText(parser.replace("SmileyParser类处理后:"+text));
- }
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TextView tvShow = (TextView) findViewById(R.id.tvShow);
TextView tvSource = (TextView) findViewById(R.id.tvSource);
SmileyParser parser = new SmileyParser(this);
String text = "[鄙视][爱你][便便][馋嘴][机器人]";
tvSource.setText("原文:"+text);
tvShow.setText(parser.replace("SmileyParser类处理后:"+text));
}
效果:
付继承关系:
扩展学习:
android开发:TextView中显示HTML和图片
最近有人咨询我如何在TextView中显示<img src=""/> html标签内的图片,大家都知道,在TextView中显示HTML内容的方法如下所示:
- TextView description=(TextView)findViewById(R.id.description);
- description.setText(Html.fromHtml(htmlStr));
TextView description=(TextView)findViewById(R.id.description);
description.setText(Html.fromHtml(htmlStr));
如果HTML中有图片的话,显示出来的图片会被一个小框取代,那么怎么样才能看到图片呢?查看了一下API,android.text.Html还还有另一个方法:Html.fromHtml(String source,ImageGetter imageGetter,TagHandler tagHandler),这个方法使用如下所示:
-
- ImageGetter imgGetter = new Html.ImageGetter() {
- public Drawable getDrawable(String source) {
- Drawable drawable = null;
- Log.d("Image Path", source);
- URL url;
- try {
- url = new URL(source);
- drawable = Drawable.createFromStream(url.openStream(), "");
- } catch (Exception e) {
- return null;
- }
- drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
- return drawable;
- }
- };
- .........
- TextView description=(TextView)findViewById(R.id.description);
- description.setText(Html.fromHtml(htmlStr,imgGetter,null));
//<img src='http://XXX.png' />的情况
ImageGetter imgGetter = new Html.ImageGetter() {
public Drawable getDrawable(String source) {
Drawable drawable = null;
Log.d("Image Path", source);
URL url;
try {
url = new URL(source);
drawable = Drawable.createFromStream(url.openStream(), "");
} catch (Exception e) {
return null;
}
drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
return drawable;
}
};
.........
TextView description=(TextView)findViewById(R.id.description);
description.setText(Html.fromHtml(htmlStr,imgGetter,null));
如果图片在该工程的res/drawable下,那么可以使用下面这种:
-
- ImageGetter imgGetter = new Html.ImageGetter() {
- @Override
- public Drawable getDrawable(String source) {
- int id = Integer.parseInt(source);
- Drawable drawable = getResources().getDrawable(id);
-
-
-
- drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
- return drawable;
- }
- };
//<img src='" + R.drawable.icon + "' />的情况
ImageGetter imgGetter = new Html.ImageGetter() {
@Override
public Drawable getDrawable(String source) {
int id = Integer.parseInt(source);
Drawable drawable = getResources().getDrawable(id);
//int height = fontH;
//int width = (int) ((float) drawable.getIntrinsicWidth() / (float) drawable.getIntrinsicHeight()) * fontH;
//drawable.setBounds(0, 0, width, height);
drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
return drawable;
}
};
怎么样?很简单,第二个参数TagHandler是干什么的呢?从名称我们就知道是处理HTML中的标签的,比如说遇到某个标签就把它替换为….之类的操作都可以通过TagHandler来处理,呵呵,我可没试过哦,瞎猜的,程序员一定要发挥充分的想像力,自己去试一下吧!
最后我要说的是,如果你的图片是从网络上获取的,那么你一定不要用这种方法显示一张图片,因为这是最垃圾的办法,你的程序会经常被卡死。
那么有没有更好的方法呢?也许不是最好,但我建议您可以使用WebView来显示HTML内容。