Android富文本处理

在使用Android WebView的项目中,富文本有时候会用,所以在此分享一下富文本的简单实现

如何设置类似<html>...</html>
<html> <head></head> <body> 哈哈哈 <a href="http://m.baidu.com/u/10001" class="referer">@天天</a> 我赞你了哦 </body> </html>

方法:
TextView tv = new TextView(context);
tv.setText(Html.fromHtml("<html>...</html>"));

下来看一下富文本的简单实现Demo:
package com.example.textdemo;

import android.app.Activity;
import android.os.Bundle;
import android.text.Html;
import android.text.Spanned;
import android.widget.TextView;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        String str = "<html><head></head><body>哈哈哈 <a href=\"http://m.baidu.com/u/10001\" class=\"referer\">@天天</a>我赞你了哦</body></html>";
        // Spanned : 块 (类似<span></span>和<div></div>),将字符串str解析成一个一个的块
        Spanned spanned = Html.fromHtml(str);
        TextView tv1 = (TextView) findViewById(R.id.tv1);
        tv1.setText(spanned);
        
        String content = getBlueText("盖聂, 卫庄, 张良, 天明") + "等 <font color=\"#FF0000\">88人</font>觉得很赞";
        TextView tv2 = (TextView) findViewById(R.id.tv2);
        tv2.setText(Html.fromHtml(content));
    }

    /**
     * 为字符串加蓝色
     * @param string
     * @return
     */
	private String getBlueText(String string) {
		return String.format("<font color=\"#0000FF\">%s</font>", string); // string 会替换 %s
	}

}

运行效果图如下:




转载于:https://www.cnblogs.com/smartbetter/p/6647521.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值