SpannableString的常用用法

2024-01-24 13:20

本文主要是介绍SpannableString的常用用法,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

1、BackgroundColorSpan 背景色
2、ClickableSpan 文本可点击,有点击事件
3、ForegroundColorSpan 文本颜色(前景色)
4、MaskFilterSpan 修饰效果,如模糊(BlurMaskFilter)、浮雕(EmbossMaskFilter)
5、MetricAffectingSpan 父类,一般不用
6、RasterizerSpan 光栅效果
7、StrikethroughSpan 删除线(中划线)
8、SuggestionSpan 相当于占位符
9、UnderlineSpan 下划线
10、AbsoluteSizeSpan 绝对大小(文本字体)
11、DynamicDrawableSpan 设置图片,基于文本基线或底部对齐。
12、ImageSpan 图片
13、RelativeSizeSpan 相对大小(文本字体)
14、ReplacementSpan 父类,一般不用
15、ScaleXSpan 基于x轴缩放
16、StyleSpan 字体样式:粗体、斜体等
17、SubscriptSpan 下标(数学公式会用到)
18、SuperscriptSpan 上标(数学公式会用到)
19、TextAppearanceSpan 文本外貌(包括字体、大小、样式和颜色)
20、TypefaceSpan 文本字体
21、URLSpan 文本超链接


以上是SpannableString的可用类型,这里只对ClickableSpan 、ImageSpan 、URLSpan 这3种做讲解。其他类似。
注:下文中,ClickableSpan的第二种方法,当要改变的数据有多次重复的时候,会有bug,解决办法,请参阅

http://blog.csdn.net/u014620028/article/details/51096023

先来布局文件:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="match_parent"android:layout_height="match_parent"android:orientation="vertical"><TextView
        android:id="@+id/tv_show"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_gravity="center_horizontal"android:layout_marginTop="50dp"android:text="Hello World!"/>
</LinearLayout>

有的地方会用到Toast,这里附上单例Toast(不用等上一个消失,下一个才会出现,只用一个)

public class Utils {private static Toast toast;/*** 单例吐司*/public static void showToast(Context context, String msg) {if (toast == null) {toast = Toast.makeText(context, msg, Toast.LENGTH_SHORT);}toast.setText(msg);toast.show();}
}

代码讲解:
先初始化

String content = "滚滚长江东逝水,浪花淘尽英雄。是非成败转头空,青山依旧在,几度夕阳红。白发渔樵(qiáo)江渚(zhǔ)上,惯看秋月春风。一壶浊酒喜相逢,古今多少事,都付笑谈中。";SpannableString spannableString = new SpannableString(content);

1、ClickableSpan 第一种用法:给单个局部文字加颜色和点击事件

spannableString.setSpan(new ClickableSpan() {@Overridepublic void updateDrawState(TextPaint ds) {super.updateDrawState(ds);//设置指定区域的文字变蓝色ds.setColor(Color.BLUE);//设置指定区域的文字有下划线ds.setUnderlineText(true);}@Overridepublic void onClick(View widget) {Utils.showToast(MainActivity.this, "点击了");}}, 0, 7, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);//加上这句话,才有点击效果tv_show.setMovementMethod(LinkMovementMethod.getInstance());//把spannableString设置到TextView上tv_show.setText(spannableString);

效果图:
这里写图片描述

2、ClickableSpan 的第二种用法:给多个局部文字加颜色

ArrayList<String> list = new ArrayList<String>();list.add("长江");list.add("青山");list.add("夕阳红");list.add("秋月春风");for (int i = 0; i < list.size(); i++) {final String temp = list.get(i);String temp_content = content;int start = 0;while (temp_content.contains(temp)) {spannableString.setSpan(new ClickableSpan() {@Overridepublic void updateDrawState(TextPaint ds) {// TODO Auto-generated method stubsuper.updateDrawState(ds);// 设置指定区域的文字变红色ds.setColor(Color.BLUE);//设置指定区域的文字有下划线ds.setUnderlineText(false);}@Overridepublic void onClick(View widget) {Utils.showToast(MainActivity.this, "点击了" + temp);}}, start + temp_content.indexOf(temp), start + temp_content.indexOf(temp) + temp.length(),Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);tv_show.setText(spannableString);tv_show.setMovementMethod(LinkMovementMethod.getInstance());start = temp_content.indexOf(temp) + temp.length();temp_content = temp_content.substring(start);}}

效果图:
这里写图片描述

3、URLSpan ,超链接,点击指定区域,根据输入的链接跳转。设计网络,最好加上网络权限

 <uses-permission android:name="android.permission.INTERNET" />

(1)调用默认的

spannableString.setSpan(new URLSpan("https://hao.360.cn/"), 2, 5, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);tv_show.setText(spannableString);tv_show.setMovementMethod(LinkMovementMethod.getInstance());

效果图:
这里写图片描述

(2)默认是有下划线,颜色是红色,假如不喜欢,自己模仿URLSpan写一个

/*** 自定义的URLSpan,设置字体是蓝色,没有下划线*/spannableString.setSpan(new MyUrlSpan("https://hao.360.cn/"), 10, 15, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);tv_show.setText(spannableString);tv_show.setMovementMethod(LinkMovementMethod.getInstance());

效果图:
这里写图片描述
URLSpanMyUrlSpan源码在附录。区别在于updateDrawState()

4、ImageSpan (把指定区域的文字,换成图片)

 Drawable d = getResources().getDrawable(R.mipmap.ic_launcher);d.setBounds(0, 0, 100, 100);spannableString.setSpan(new ImageSpan(d), 3, 6, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);tv_show.setText(spannableString);tv_show.setMovementMethod(LinkMovementMethod.getInstance());

效果图:
这里写图片描述

5、还可组合使用,这里以URLSpan 和ImageSpan 为例

 spannableString.setSpan(new MyUrlSpan("https://hao.360.cn/"), 10, 15, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);Drawable d = getResources().getDrawable(R.mipmap.ic_launcher);
d.setBounds(0, 0, 100, 100);
spannableString.setSpan(new ImageSpan(d), 3, 6, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
tv_show.setText(spannableString);
tv_show.setMovementMethod(LinkMovementMethod.getInstance());

效果图:
这里写图片描述


附录:
URLSpan 源码

/** Copyright (C) 2006 The Android Open Source Project** Licensed under the Apache License, Version 2.0 (the "License");* you may not use this file except in compliance with the License.* You may obtain a copy of the License at**      http://www.apache.org/licenses/LICENSE-2.0** Unless required by applicable law or agreed to in writing, software* distributed under the License is distributed on an "AS IS" BASIS,* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.* See the License for the specific language governing permissions and* limitations under the License.*/package android.text.style;import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Parcel;
import android.provider.Browser;
import android.text.ParcelableSpan;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;public class URLSpan extends ClickableSpan implements ParcelableSpan {private final String mURL;public URLSpan(String url) {mURL = url;}public URLSpan(Parcel src) {mURL = src.readString();}public int getSpanTypeId() {return getSpanTypeIdInternal();}/** @hide */public int getSpanTypeIdInternal() {return TextUtils.URL_SPAN;}public int describeContents() {return 0;}public void writeToParcel(Parcel dest, int flags) {writeToParcelInternal(dest, flags);}/** @hide */public void writeToParcelInternal(Parcel dest, int flags) {dest.writeString(mURL);}public String getURL() {return mURL;}@Overridepublic void onClick(View widget) {Uri uri = Uri.parse(getURL());Context context = widget.getContext();Intent intent = new Intent(Intent.ACTION_VIEW, uri);intent.putExtra(Browser.EXTRA_APPLICATION_ID, context.getPackageName());try {context.startActivity(intent);} catch (ActivityNotFoundException e) {Log.w("URLSpan", "Actvity was not found for intent, " + intent.toString());}}
}

MyUrlSpan源码

package com.chen.demo;import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Parcel;
import android.provider.Browser;
import android.text.ParcelableSpan;
import android.text.TextPaint;
import android.text.style.ClickableSpan;
import android.util.Log;
import android.view.View;/*** Created by lenovo on 2016/3/25.*/
public class MyUrlSpan extends ClickableSpan implements ParcelableSpan {private final String mURL;public MyUrlSpan(String url) {mURL = url;}public MyUrlSpan(Parcel src) {mURL = src.readString();}public int getSpanTypeId() {return getSpanTypeIdInternal();}/*** @hide*/public int getSpanTypeIdInternal() {return 0;}public int describeContents() {return 0;}public void writeToParcel(Parcel dest, int flags) {writeToParcelInternal(dest, flags);}/*** @hide*/public void writeToParcelInternal(Parcel dest, int flags) {dest.writeString(mURL);}public String getURL() {return mURL;}@Overridepublic void onClick(View widget) {Uri uri = Uri.parse(getURL());Context context = widget.getContext();Intent intent = new Intent(Intent.ACTION_VIEW, uri);intent.putExtra(Browser.EXTRA_APPLICATION_ID, context.getPackageName());try {context.startActivity(intent);} catch (ActivityNotFoundException e) {Log.w("URLSpan", "Actvity was not found for intent, " + intent.toString());}}@Overridepublic void updateDrawState(TextPaint ds) {super.updateDrawState(ds);ds.setUnderlineText(false);ds.setColor(Color.BLUE);}
}

ClickableSpan源码

/** Copyright (C) 2008 The Android Open Source Project** Licensed under the Apache License, Version 2.0 (the "License");* you may not use this file except in compliance with the License.* You may obtain a copy of the License at**      http://www.apache.org/licenses/LICENSE-2.0** Unless required by applicable law or agreed to in writing, software* distributed under the License is distributed on an "AS IS" BASIS,* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.* See the License for the specific language governing permissions and* limitations under the License.*/package android.text.style;import android.text.TextPaint;
import android.view.View;/*** If an object of this type is attached to the text of a TextView* with a movement method of LinkMovementMethod, the affected spans of* text can be selected.  If clicked, the {@link #onClick} method will* be called.*/
public abstract class ClickableSpan extends CharacterStyle implements UpdateAppearance {/*** Performs the click action associated with this span.*/public abstract void onClick(View widget);/*** Makes the text underlined and in the link color.*/@Overridepublic void updateDrawState(TextPaint ds) {ds.setColor(ds.linkColor);ds.setUnderlineText(true);}
}

这篇关于SpannableString的常用用法的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/639817

相关文章

全面掌握 SQL 中的 DATEDIFF函数及用法最佳实践

《全面掌握SQL中的DATEDIFF函数及用法最佳实践》本文解析DATEDIFF在不同数据库中的差异,强调其边界计算原理,探讨应用场景及陷阱,推荐根据需求选择TIMESTAMPDIFF或inte... 目录1. 核心概念:DATEDIFF 究竟在计算什么?2. 主流数据库中的 DATEDIFF 实现2.1

MySQL中的LENGTH()函数用法详解与实例分析

《MySQL中的LENGTH()函数用法详解与实例分析》MySQLLENGTH()函数用于计算字符串的字节长度,区别于CHAR_LENGTH()的字符长度,适用于多字节字符集(如UTF-8)的数据验证... 目录1. LENGTH()函数的基本语法2. LENGTH()函数的返回值2.1 示例1:计算字符串

Java中的数组与集合基本用法详解

《Java中的数组与集合基本用法详解》本文介绍了Java数组和集合框架的基础知识,数组部分涵盖了一维、二维及多维数组的声明、初始化、访问与遍历方法,以及Arrays类的常用操作,对Java数组与集合相... 目录一、Java数组基础1.1 数组结构概述1.2 一维数组1.2.1 声明与初始化1.2.2 访问

Spring Boot中WebSocket常用使用方法详解

《SpringBoot中WebSocket常用使用方法详解》本文从WebSocket的基础概念出发,详细介绍了SpringBoot集成WebSocket的步骤,并重点讲解了常用的使用方法,包括简单消... 目录一、WebSocket基础概念1.1 什么是WebSocket1.2 WebSocket与HTTP

MySQL 中的 CAST 函数详解及常见用法

《MySQL中的CAST函数详解及常见用法》CAST函数是MySQL中用于数据类型转换的重要函数,它允许你将一个值从一种数据类型转换为另一种数据类型,本文给大家介绍MySQL中的CAST... 目录mysql 中的 CAST 函数详解一、基本语法二、支持的数据类型三、常见用法示例1. 字符串转数字2. 数字

Python中你不知道的gzip高级用法分享

《Python中你不知道的gzip高级用法分享》在当今大数据时代,数据存储和传输成本已成为每个开发者必须考虑的问题,Python内置的gzip模块提供了一种简单高效的解决方案,下面小编就来和大家详细讲... 目录前言:为什么数据压缩如此重要1. gzip 模块基础介绍2. 基本压缩与解压缩操作2.1 压缩文

golang中reflect包的常用方法

《golang中reflect包的常用方法》Go反射reflect包提供类型和值方法,用于获取类型信息、访问字段、调用方法等,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值... 目录reflect包方法总结类型 (Type) 方法值 (Value) 方法reflect包方法总结

C# 比较两个list 之间元素差异的常用方法

《C#比较两个list之间元素差异的常用方法》:本文主要介绍C#比较两个list之间元素差异,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧... 目录1. 使用Except方法2. 使用Except的逆操作3. 使用LINQ的Join,GroupJoin

解读GC日志中的各项指标用法

《解读GC日志中的各项指标用法》:本文主要介绍GC日志中的各项指标用法,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录一、基础 GC 日志格式(以 G1 为例)1. Minor GC 日志2. Full GC 日志二、关键指标解析1. GC 类型与触发原因2. 堆

MySQL数据库中ENUM的用法是什么详解

《MySQL数据库中ENUM的用法是什么详解》ENUM是一个字符串对象,用于指定一组预定义的值,并可在创建表时使用,下面:本文主要介绍MySQL数据库中ENUM的用法是什么的相关资料,文中通过代码... 目录mysql 中 ENUM 的用法一、ENUM 的定义与语法二、ENUM 的特点三、ENUM 的用法1