android 使用html标签

本文展示如何在Android应用中利用HTML标签来提高界面的个性化和交互性,通过设置字体颜色并嵌入图片,实现更丰富的UI设计。示例代码包括HTML解析、图片获取与显示等关键步骤,旨在提升应用的用户体验。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Android中使用html标签很大程度上提高了开发的灵活性。下面是一个简单的使用示例,设置了字体颜色并在中间嵌入了一张图片。

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

/**
 * Created by hsji on 2015/8/5.
 */
public class HtmlStringActivity extends Activity{
    TextView content;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_html_string);
        content = (TextView) findViewById(R.id.content);

        /**
         * This methos is called when the HTML parser encounters an <img> tag.
         * The source argument is the string from the "src" attribute;
         * the return value should be a Drawable representation of the image or null for a generic replacement image.
         * Make sure you call setBounds() on your Drawable if it doesn't already have its bounds set.
         */
        Html.ImageGetter imageGetter = new Html.ImageGetter(){

            @Override
            public Drawable getDrawable(String source) {
                Drawable drawable = null;
                try {
                     drawable = getResources().getDrawable(Integer.parseInt(source));
                     drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
                }catch (NumberFormatException e){
                    e.printStackTrace();
                }
                return drawable;
            }
        };

        StringBuffer sb = new StringBuffer();
        sb.append("<font color=\"#ff0000\">我</font>")
                .append("<img src=\""+R.drawable.heart+"\"/>")
                .append("<font color=\"#ff0000\">董英</font>");
        Spanned spanned = Html.fromHtml(sb.toString(),imageGetter,null);
        content.setText(spanned);
    }
}

效果如下:

转载于:https://www.cnblogs.com/hsji/p/4704590.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值