使用TextView显式富文本
String html = " I love Android. ";html += " I love Android. ";html += "
I love Android.";html += " 我的网站 "; //将带预定义标签的字符串转换成CharSequence对象CharSequence charSequence = Html.fromHtml(html);textView1.setText(charSequence);//下边的语句必须调用,否则不能打开浏览器textView1.setMovementMethod(LinkMovementMethod.getInstance()); String text = "hellp.com\n";textView2.setText(text);textView2.setMovementMethod(LinkMovementMethod.getInstance());
2.TextView显示图文
String html = "图像1图像2
"; //name参数表示表示res/drawable中的图像文件名(不含扩展名)public int getResourceId(String name){ try{ Field field = R.drawable.class.getField(name); return Integer.parseInt(field.get(null).toString()); }catch(Exception e){ } return 0;} //使用Html.fromHtml方法转换包含Html标签的文本CharSequence charSequence = Html.fromHtml(html,new ImageGetter(){ @override public Drawable getDrawable(String sourse){ Drawable drawable = getResources.getDrawable(getResourceId(sourse)); drawable.setBounds(0,0,drawable.getIntrinsicWidth(),drawable.getIntrinsicHeight()); return drawable; }},null);textView.setText(charSequence);textView.setMovementMethod(LinkMovementMethod.getInstance());
3.单击链接弹出Activity
String text1 = "显示activity1";//将文本转换成SpannableString对象SpannableString spannableString1 = new SpannableString(text1);spannableString1.setSpan(new ClickableSpan(){ @override public void onClick(View widget){ Intent intent = new Intent(this,Activity1.class); startActivity(intent); }},0,text1.length(),Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);textView1.setMovementMethod(LinkMovementMethod.getInstance());
4.为指定文本添加背景
String text = " <没有背景> <黄色背景> ";//将字符串转成SpannableStringSpannableString spannableString = new SpannableString(text);//确定要设置的子字符串的位置int start=6;int stop = 12;//创建BackgroundColorSpan对象BackgroundColorSpan backgroundColorSpan = new BackgroundColorSpan(Color.YELLOW);//使用setSpan方法将指定子字符串转换成BackgroundColorSpan对象spannableString.setSpan(backgroundColorSpan,start,stop,Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);textView.setText(spannableString); 黄色背景> 没有背景>
--自定义ColorSpan,同时设置文字颜色和背景色
public class ColorSpan extends CharacterStyle{ private int mTextColor; private int mBackgroundColor; public ColorSpan(int textColor,int backgroundColor){ mTextColor = textColor; mBackgroundColor = backgroundColor; } @override public void updateDrawState(TextPaint tp){ tp.bgColor = mBackgroundColor; tp.setColor(mTextColor); }}
在XML中要想设置TextView的超链接,可以在strings.xml中定义
打电话
然后在TextView设置text = "@string/link_text"
5.带边框的TextView
使用.9
在onDraw函数中
onDraw{ Paint paint = new Paint(); paint.setColor(android.graphics.Color.BLACK); //绘制上下左右边框即可}
6.设置行间距
使用android:lineSpacingExtra设置精确的行间距
使用android:lineSpaceMultiplier设置默认行间距的倍数
使用setLineSpacing方法设置行间距
7.在未显示完的文本后加省略号
android:ellipsize="start";textView.setEllipsize(TextUtils.TruncateAt.END);
8.TextView实现走马灯效果
android:ellipsize="marquee";android:marqueeRepeatLimit="marquee_forever"android:focusable="true"
9.垂直滚动TextView中的文本
android:scrollbars="vertical"android:scrollbarStyle="outsideOverlay"android:scrollbarFadeDuration="2000"//滚动条出现的时间