1、[Android實例]實現TextView裏的文字有不一樣顏色html
轉eoe:http://www.eoeandroid.com/thread-4496-1-1.htmljava
import android.text.Html;
TextView t3 = (TextView) findViewById(R.id.text3);
t3.setText(
Html.fromHtml(
"<b>text3:</b> Text with a " +
"<a href=/"http://www.google.com/">link</a> " +
"created in the Java source code using HTML."));android
2、TextView顯示html文件中的圖片app
轉javaeye:http://da-en.javaeye.com/blog/712415ide
咱們知道要讓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。
參考文檔:
http://tech-droid.blogspot.com/2010/06/textview-with-html-content.html英語好的朋友就直接看英文文檔吧。fetch
3、Android---文字中插入表情ui
轉:http://blog.163.com/spf9190@126/blog/static/50207531201091545954587/this
這段時間在作一個短信項目,須要實現短信中插入表情的功能,本一位很是困難,通過一段時間的研究,發現仍是比較簡単的,如今總結以下。google
以短信輸入框爲例,短信的輸入框是一個EditText,它的append方法不只能夠加入字符串,還能夠添加HTML標記。如下就是使用HTML標記添加表情的具體操做。spa
首先須要構建一個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 的短信實現方式普通用戶適應的話須要長時間的使用才能習慣,將andorid的短信模式設置成咱們經常使用的(通常人用戶)的習慣。在查看字符轉圖片的過程當中能夠猜想出騰訊的QQ表情的原理應該是同樣的
只是在傳送很是用的表情時是將byte數據轉換爲image.
轉載請註明:QQ:273733055 ppwuyi@sohu.com
/***
*
* 此方法描述的是: 注意此方法在作表情轉換的準備了
* @author:wujun@cqghong.com,ppwuyi@sohu.com
* @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.getInstance());
// 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.com,ppwuyi@sohu.com
* @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 = //把他看成StringBuffer只是它能夠放的不是 String 而已他能放跟多類型的東西
new 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);
buf.setSpan(new AbsoluteSizeSpan(12), startOffset, buf.length(),
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
// Make the timestamp text not as dark 改變某區域顏色 時間的地方爲特殊顏色
int color = mContext.getResources().getColor(R.color.timestamp_color);
buf.setSpan(new ForegroundColorSpan(color), startOffset, buf.length(),
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而後替換掉表情字符。
5、文檔
public static Spanned fromHtml (String source, Html.ImageGetter imageGetter, Html.TagHandler tagHandler)
Since: API Level 1
Returns displayable styled text from the provided HTML string. Any <img> tags in the HTML will use the specified ImageGetter to request a representation of the image (use null if you don't want this) and the specified TagHandler to handle unknown tags (specify null if you don't want this).
This uses TagSoup to handle real HTML, including all of the brokenness found in the wild.