【推荐下载】Android的TextView使用Html来处理图片显示、字体样式、超链接等

时间:2022-07-25 06:36:17 阅读: 最新文章 文档下载
说明:文章内容仅供预览,部分内容可能不全。下载后的文档,内容与下面显示的完全一致。下载之前请确认下面内容是否您想要的,是否完整无缺。
Android TextView 使用 Html 来处理图片显示、字体样式、超链接



2012/02/09 0 一、[Android 实例]实现 TextView 里的文字有不同颜色 eoeeoeandroid/thread-4496-1-1.html

import android.text.Html;TextView t3 = (TextView) findViewById(R.id.text3); t3.setText( /a

Html.fromHtml(

b text3: /b Text with a

a href=\ google\ link

created in the Java source code using HTML. ));

二、TextView 显示 html 文件中的图片 javaeyeda-en.javaeye/blog/712415

我们知道要让 TextView 解析和显示 Html 代码。可以使用 Spanned

text

=

Html.fromHtml(source);tv.setText(text);来实现,这个用起来简单方便。但是,怎样让 TextView 也显示 Html image 节点的图像呢?我们可以看到 fromHtml 还有另一 个重构:fromHtml(String source, Html.ImageGetter imageGetter, Html.TagHandler tagHandler)实现一下 ImageGetter 就可以让图片显示了:ImageGetter imgGetter = new Html.ImageGetter() { @Override public Drawable getDrawable(String source) { Drawable drawable = null; drawable = Drawable.createFromPath(source); // Or fetch it from the URL

//

Important

drawable.setBounds(0,

0,

drawable.getIntrinsicWidth(),

drawable .getIntrinsicHeight()); return drawable; }};至于 TagHandler,我们这里不需要 使用,可以直接传 null。参考文档:tech-droid.blogspot/2010/06/textview-with-html- content.html 英语好的朋友就直接看英文文档吧。 三、Android---文字中插入表情

转载自:blog.163/spf9190@126/blog/static/50207531201091545954587/

这段时间在做一个短信项目,需要实现短信中插入表情的功能,本一位非常困

难,经过一段时间的研究,发现还是比较簡単的,现在总结如下。

以短信输入框为例,短信的输入框是一个 EditText,它的 append 方法不仅可以


加入字符串,还可以添加 HTML 标记。以下就是使用 HTML 标记添加表情的具体 操作。

首先需要构建一个 ImageGetter,作用是通过 HTML 标记获得对应在 res 目录下的 图片:

ImageGetter imageGetter = new ImageGetter() { @Override public Drawable getDrawable(String source) { int id = Integer.parseInt(source);

//根据 id 从资源文件中获取图片对象 Drawable d = getResources().getDrawable(id); d.setBounds(0, 0, d.getIntrinsicWidth(),d.getIntrinsicHeight()); return d; } }; 然后就可以直接往 EditText 视图中添加

inputLable.append(Html.fromHtml( img src=‘ clickedImageId ‘/ , imageGetter, null)); 其中 Html.fromHtml( img src=‘ clickedImageId ‘/ 就是 HTML 的图片标记,在 Android 中支持了部分 HTML 标记的使用(这方面我还在继续研究),HTML 标记必 须被 Html.fromHtml 修饰。imageGetter 即为之前创建的 ImageGetter 类型的对象。 很简单的几句代码就解决了问题,不仅在 EditText 中,在 TextView 中同样可以这 样插入图片。 效果图:

四、android 短信字符转表情显示过程 android 的短信实现方式普通用户适应的话 需要长时间的使用才能习惯,将 andorid 的短信模式设置成我们常用的(一般人用 户)的习惯。在查看字符转图片的过程中可以猜测出腾讯的 QQ 表情的原理应该是 一样的只是在传送非常用的表情时是将 byte 数据转换为 image.以下代码摘录至 android 源码里面的 MMS 项目,其中的

package com.android.mms.ui 里的 MessageListItem.java package com.android.mms.util 里的 SmileyParser.java /***

*

*此方法描述的是:注意此方法在做表情转换的准备了

*

@author:wujun@cqghong,ppwuyi@sohu * @version: 2010-5-13 下午 03:31:13 */ private void bindCommonMessage(final MessageItem msgItem) { if (mDownloadButton != null)


{ mDownloadButton.setVisibility(View.GONE);

mDownloadingLabel.setVisibility(View.GONE); } // Since the message text should be concatenated with the sender’s // address(or name), I have to display it here instead of // displaying

it

by

the

Presenter.

mBodyTextView.setTransformationMethod(HideReturnsTransformationMethod.getInstan ce());

// Get and/or lazily set the formatted message from/on the // MessageItem. Because the

MessageItem instances come from a // cache (currently of size ~50), the hit rate on

avoiding the // expensive formatMessage() call is very high. CharSequence formattedMessage = msgItem.getCachedFormattedMessage(); if (formattedMessage == null)

{

//肯定为 null 应为 msgItem.formattedMessage 从诞生来就没被注意过一次

formattedMessage = formatMessage(msgItem.mContact, msgItem.mBody, //重点到了 msgItem.mSubject,

msgItem.mTimestamp,

msgItem.mHighlight);

}

msgItem.setCachedFormattedMessage(formattedMessage); mBodyTextView.setText(formattedMessage);

if (msgItem.isSms()) { hideMmsViewIfNeeded(); } else { Presenter presenter = PresenterFactory.getPresenter(

MmsThumbnailPresenter

,

mContext,

this,

msgItem.mSlideshow); presenter.present();

if (msgItem.mAttachmentType != WorkingMessage.TEXT) { inflateMmsView(); mMmsView.setVisibility(View.VISIBLE);

setOnClickListener(msgItem);

drawPlaybackButton(msgItem); } else { hideMmsViewIfNeeded(); } }

drawLeftStatusIndicator(msgItem.mBoxId); drawRightStatusIndicator(msgItem); }//---- --------------------------------------------------------------------------

/*** * *此方法描述的是:开始转换了哦 * @author:wujun@cqghong,ppwuyi@sohu * @version: 2010-5-13 下午 03:32:52 */ private CharSequence formatMessage(String contact, String body, String subject, String timestamp, String highlight) { CharSequence


template = mContext.getResources().getText(R.string.name_colon); //遇到 主题: xliff:g id= SUBJECT %s /xliff:g

SpannableStringBuilder buf =

//把他当作

new

StringBuffer 只是它可以放的不是 String 而已他能放跟多类型的东西

SpannableStringBuilder(TextUtils.replace(template, new String[] { %s }, new CharSequence[] { contact }); //替换成联系人

boolean hasSubject = !TextUtils.isEmpty(subject); //主题 if (hasSubject) { buf.append(mContext.getResources().getString(R.string.inline_subject, subject)); //buff 在是 联系人 主题 XXXX eg wuyi 主题:dsadasdsa 我爱我家 }

if (!TextUtils.isEmpty(body)) { if (hasSubject) { buf.append( - //如果内容有主题有就 - eg wuyi 主题:sdsadsadsa - } SmileyParser parser = SmileyParser.getInstance(); //

表情类了哦 buf.append(parser.addSmileySpans(body)); //追查 急切关注中 } if (!TextUtils.isEmpty(timestamp)) { buf.append( \n int startOffset = buf.length(); // put a one pixel high spacer line between the message and the time stamp as requested

// by the spec. //把之间的信息和时间戳的要求间隔一个像素的高线 buf.append( \n

//由规范

buf.setSpan(new AbsoluteSizeSpan(3), startOffset, buf.length(),

Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

startOffset

=

buf.length();

buf.append(timestamp); startOffset,

buf.setSpan(new buf.length(),

AbsoluteSizeSpan(12),

Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); // Make the timestamp text not as dark 改变某区域颜色时间的地方为特殊颜色

int

color

=

buf.setSpan(new buf.length(),

mContext.getResources().getColor(R.color.timestamp_color); ForegroundColorSpan(color),

startOffset,

Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); } if (highlight != null) { int highlightLen = highlight.length();

String s = buf.toString().toLowerCase(); int prev = 0; while (true) { int index = s.indexOf(highlight, prev); if (index == -1) { break; } buf.setSpan(new


StyleSpan(Typeface.BOLD), index, index highlightLen, 0); prev = index highlightLen; } } return buf; }

//------------------------------------------------------------

/** * Adds ImageSpans to a CharSequence that replace textual emoticons such * as :-) with a graphical version. * * @param text A CharSequence possibly containing emoticons * @return A CharSequence annotated with ImageSpans covering any * recognized

emoticons. *添加 ImageSpans 一个 CharSequence 的表情符号代替文字等 *如用图形 版本:-) *核心是把表情字符替换成 ImageSpans 的对象 */ public CharSequence addSmileySpans(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; } 总结:

android 在将字符转化为表情图像其核心代码为

builder.setSpan(new ImageSpan(mContext, resId), matcher.start(), matcher.end(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);原理过程是先匹配到表情字符然后通 new ImageSpan(上下文,表情地址)绘制出一个 ImageView 然后替换掉表情字符。 五、 Android TextView 支持的 HTML 标签

a href= ... b big blockquote br cite dfn div align= ... em font size= ... color= ... face= ... h1 h2 h3 h4 h5 h6 i img src= ... p small strike strong sub sup tt u cnblogs/playing/archive/2011/03/17/1987033.html

There is a lovely method on the android.text.Htmlclass, fromHtml() , that converts


HTML into a Spannablefor use with a TextView .However, the documentation does not stipulate what HTML tags are supported, which makes this method a bit hit-or-miss. More importantly, it means that you cannot rely on what it will support from release to release.I have filed an issuerequesting that Google formally document what it intends to support. In

the interim, from a quick look at the source code, heres what seems to be supported as of Android 2.1: a href= ... 定义链接内容 b 定义粗体文字 b blod 的缩写 big 义大字体的文字 blockquote 引用块标签

属性:

Common-- 一般属性

cite-

- 被引用内容的 URI br 定义换行 cite 表示引用的 URI dfn 定义标签 dfn defining instance 的缩写

div align= ...

h1

h2

em 强调标签 em emphasis 的缩写 h3

h4

h5

h6

i 定义斜体文字

font size= ... color= ... face= ... img src= ... strike

p 段落标签,里面可以加入文字,列表, small 定义小字体的文字

定义删除线样式的文字 不符合标准网页设计的理念,不赞成使用. strike

strikethrough 的缩写 strong 重点强调标签 sub 下标标签 sub subscript 的缩 sup 上标标签 sup superscript 的缩写 tt 定义 monospaced 字体的文字不 赞成使用.此标签对中文没意义 tt teletype or monospaced text style 的意思 u 义带有下划线的文字 u underlined android:text

text

style 的意思一、在 xml 文件中使用

>二、但是不能将中文设置成粗体,将中文设置成粗体的方法是:

TextView tv =( TextView) findViewById( R. id . TextView01) ;TextPaint tp =tv. getPaint ( ) ;tp. setFakeBoldText( true) ;Selecting, Highlighting, or Styling Portions of TextYou can highlight or style the formatting of strings or substrings of text in a TextView object. There are two ways to do this:If you use a string resource, you can add some simple styling, such

as bold or italic using HTML notation. The currently supported tags are: B (bold), I (italic), U (underline), TT (monospace), BIG, SMALL, SUP (superscript), SUB (subscript), and STRIKE (strikethrough). So, for example, in res/values/strings.xml you could declare this: resource /i

string id= @ id/styled_welcome_message We are b i so

/b glad to see you. /string /resources To style text on the fly, or to add highlighting or


more complex styling, you must use the Spannable object as described next.To style text

on the fly, you must make sure the TextView is using Spannable storage for the text (this

will always be true if the TextView is an EditText), retrieve its text with getText(), and call setSpan(Object, int, int, int), passing in a new style class from the android.text.style package and the selection range.The following code snippet demonstrates creating a string

with a highlighted section, italic section, and bold section, and adding it to an EditText object.// Get our EditText object.EditText vw = (EditText)findViewById(R.id.text);// Set the EditText’s text.vw.setText( Italic, highlighted, bold. // If this were just a TextView, we could do:// vw.setText( Italic, highlighted, bold. , TextView.BufferType.SPANNABLE);// to force it to use Spannable storage so styles can be attached.// Or we could specify that in

the XML.// Get the EditText’s internal text storageSpannable str = vw.getText();// Create our

span

sections,

and

assign

a

format

to 0,

each.str.setSpan(new

7,

StyleSpan(android.graphics.Typeface.ITALIC),

Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);str.setSpan(new BackgroundColorSpan(0xFFFFFF00),

8,

19,

Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);str.setSpan(new StyleSpan(android.graphics.Typeface.BOLD),

21,

str.length()

-

1,

Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);I sometimes have the case to arrange the image next to the characters.We can do it by putting TextView and ImageView into Layout.But today I introduce the other way using only TextView.The following sample code is how to show the image next to text.(show four image(left, top, right, bottom of text))final TextView textView = (TextView)findViewById(R.id.diet_log_label);final Drawable

iconDrawable

=

getResources().getDrawable(R.drawable.icon);textView.setCompoundDrawablesWithIntri nsicBounds(iconDrawable,

iconDrawable,

iconDrawable,

iconDrawable);//

ortextView.setCompoundDrawablesWithIntrinsicBounds(R.drawable.icon,


R.drawable.icon, R.drawable.icon, R.drawable.icon);To show only left image, write setCompoundDrawablesWithIntrinsicBounds(iconDrawable, null, null, null) tips:感谢大家的阅读,本文由我司收集整编。仅供参阅!


本文来源:https://www.wddqw.com/doc/22e9effe350cba1aa8114431b90d6c85ec3a8895.html