【问题标题】:Is there any way to change the color of an already applied BackgroundColorSpan in a SpannableString?有什么方法可以更改 SpannableString 中已应用的 BackgroundColorSpan 的颜色?
【发布时间】:2020-05-04 08:29:46
【问题描述】:

我实际上正在做的是我以HTML 的形式存储SpannableString,但它有一个BackgroundColorSpan,它的颜色有一个aplha 通道。现在我(通过试验)知道,每当我尝试存储它时,我的颜色的 aplha 通道就会从文本中消失(由于无法使用HTML)。

现在我想知道的是,有没有一种方法可以提取 SpannableString 中的所有 BackgroundColorSpan 实例并更改它们的颜色属性?所有BackgroundColorSpan 实例都具有相同的颜色,我只想在向用户呈现文本之前为它们的颜色添加一个alpha 通道(通过更改它们的颜色)。

我想出了一种方法来使用getSpans 提取所有BackgroundColorSpan 实例,但我仍然找不到改变它们颜色的方法。

相关代码如下:

SpannableString spannableDescString = new SpannableString(trimTrailingWhitespace(Html.fromHtml(note.getDesc())));
BackgroundColorSpan[] highlightSpanArray = spannableDescString.getSpans(0,spannableDescString.length(),BackgroundColorSpan.class);

if(highlightSpanArray.length!=0){
    for(BackgroundColorSpan item : highlightSpanArray){
        //what should I put here to change every item's color
    }
}

desc.setText(spannableDescString);

【问题讨论】:

    标签: android background textview android-spannable


    【解决方案1】:

    没关系,我得到了答案here

    我所要做的就是删除当前跨度并将其替换为我需要的颜色的BackgroundColorSpan。这是代码sn-p。

    SpannableString spannableDescString = new SpannableString(trimTrailingWhitespace(Html.fromHtml(note.getDesc())));
    BackgroundColorSpan[] highlightSpanArray = spannableDescString.getSpans(0,spannableDescString.length(),BackgroundColorSpan.class);
    
        if(highlightSpanArray.length!=0){
    
             for(BackgroundColorSpan item : highlightSpanArray){
                 //what should i put here to change every items color
    
                 // get the span range
                 int start = spannableDescString.getSpanStart(item);
                 int end = spannableDescString.getSpanEnd(item);
    
                 // remove the undesired span
                 spannableDescString.removeSpan(item);
    
                 // set the new span with desired color
                 spannableDescString.setSpan(new BackgroundColorSpan(Color.RED),start,end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                }
            }
    
            desc.setText(spannableDescString);
    

    我只是不知道我是否能找到各个跨度的开始和结束。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-10-24
      • 2016-03-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-02
      相关资源
      最近更新 更多