0

我正在尝试使用 for 循环来使用SpannableStringBuild列表中的字符串添加格式,但是在 中TextView,尽管已附加所有字符串,但只有初始 for 循环中附加的字符串保持其格式。相关代码如下:

String openingsText = "";
            SpannableStringBuilder spannableOpening = new SpannableStringBuilder(openingsText);
            ForegroundColorSpan foregroundColor = new ForegroundColorSpan(
                    ContextCompat.getColor(getContext(),R.color.clickable));
            UnderlineSpan underlineSpan = new UnderlineSpan();

            for (Songs opening: Item.getOpeningThemes()){
                String song = opening.getSong();

                if (Item.getOpeningThemes().size()>1) {
                    String openingNumber = song.substring(0,song.indexOf(":")+2);
                    String openingName = song.substring(song.indexOf(":")+2,song.indexOf("(eps")-1);
                    String openingEpisodes = song.substring(song.indexOf("(eps")-1);
                    spannableOpening.append(openingNumber);
                    SpannableString openingNameSpanned = new SpannableString(openingName);
                    openingNameSpanned.setSpan(underlineSpan,0,openingNameSpanned.length(),
                            Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                    openingNameSpanned.setSpan(foregroundColor,0,openingNameSpanned.length(),
                            Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                    spannableOpening.append(openingNameSpanned);
                    spannableOpening.append(openingEpisodes+ "\n");

                }else{
                    SpannableString openingNameSpanned = new SpannableString(opening.getSong());
                    openingNameSpanned.setSpan(underlineSpan,0,openingNameSpanned.length(),
                            Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                    openingNameSpanned.setSpan(foregroundColor,0,openingNameSpanned.length(),
                            Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                    spannableOpening.append(openingNameSpanned);
                }

            }
            openingThemesText.setText(spannableOpening);
4

1 回答 1

1

由于我们不能重复使用格式化样式的实例两次,所以必须做的就是移动格式化的声明,例如UnderlineSpan underlineSpan = new UnderlineSpan();在 for 循环中。

于 2021-09-07T18:13:23.757 回答