android - 有什么方法可以直接将 span 设置为 spannable 文本?

标签 android spannable

这可能是个错误,但我需要知道...:) 我正在开发一个 android 应用程序,在我想在单个 TextView 中显示两个字体并找到 this One very useful,A custom typeface span that extends typeface span , 根据我的理解,我们正在创建一个 spannable,如下使用两个词

String firstWord = "first ";
String secondWord = "second";
// Create a new spannable with the two strings
Spannable spannable = new SpannableString(firstWord+secondWord);

然后像这样使用我们的自定义跨度为该词设置两个字体

// Set the custom typeface to span over a section of the spannable object
spannable.setSpan( new CustomTypefaceSpan("sans-serif",CUSTOM_TYPEFACE), 0,              
firstWord.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
spannable.setSpan( new CustomTypefaceSpan("sans-serif",SECOND_CUSTOM_TYPEFACE),   rstWord.length(), secondWord.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

现在我的问题是,我有一个大量文本,所以如果我能够将跨度直接放在我的文本中,这对我们来说会更容易是否可以像我们放置<b>bold </b> 一样将跨度直接放置到文本中?因为我需要使用我的自定义字体跨度,如 <typeface1> sample </typeface1> <typeface2> Doc </typeface2> .

我需要的是,将设置的跨度对文本所做的更改直接应用于文本

这可能吗,如果可能的话,我需要在我的文本中写成跨度,我怎样才能做到这一点..还是我完全错了?

谢谢大家

最佳答案

很晚才回答,但你要求的很简单。

例如,假设我们要将引号之间的所有内容更改为斜体。

    String s =  "\"Hello my name is Edward\" Hola, my nombre es Edward";        
    Pattern p = Pattern.compile("\"([^\"]*)\"");
    Matcher m = p.matcher(text);
    Spannable spannable = new SpannableString(s);
    while (m.find()) {        
      int textLocation = text.indexOf(m.group(1)); 

      // Set the custom typeface to span over a section of the spannable object       
       spannable.setSpan( new CustomTypefaceSpan("sans-serif",my_italic_font),
       textLocation-1, textLocation + m.group(1).length(),spannable.SPAN_EXCLUSIVE_EXCLUSIVE);                   

      // Set the text of a textView with the spannable object
      TextView textbox = (TextView) v.findViewById(R.id.cardtextbox);

    }
    textbox.setText( spannable );

s 的结果会是

“你好,我叫爱德华” Hola,我的名字是爱德华

现在您可以使用正则表达式模式来代替引号,例如 <b>bold </b> ;

之后您还可以使用简单的 .replace() 删除标签;

关于android - 有什么方法可以直接将 span 设置为 spannable 文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17744664/

相关文章:

java - Android TextView 设置 HTML 图像后没有正方形的图像

java - 如何通过 id 组合两个对象列表并在 kotlin 中选择非空值

android - TFLite 演示模型上的静态图像精度低

java - 使用图像和环绕图像的文本编辑 TextView

android - 无法完全正确地获得 Spanable

android - 如何设置 spannable textview 之间的边距?

java - 如何在 Android 中获取上一个 Activity 中的切换按钮值?

android - JsonSyntaxException 无法解析为类型

android - 从 fragment 设置 viewPager 的 currentItem

android - 在 TextView 中使用 SpannableStringBuilder 的段落间距