【问题标题】:get string length from resources before variable inserted在插入变量之前从资源中获取字符串长度
【发布时间】:2020-09-02 17:25:06
【问题描述】:

在我的TextViews 之一中,我想将一些文本设置为这样的粗体:

为此,我使用以下内容:

final SpannableStringBuilder sb = new SpannableStringBuilder(itemView.getContext().getResources().getString( R.string.ActivityIShared_with, sharedTo.get( getAdapterPosition() ) ));
final StyleSpan bss = new StyleSpan(android.graphics.Typeface.BOLD);
sb.setSpan(bss, 0, 11, Spannable.SPAN_INCLUSIVE_INCLUSIVE);
tv_SharedWith.setText(sb);

在哪里

<string name="ActivityIShared_with">Shared with: %1$s</string>

如您所见,此代码有效。但是,我需要手动计算 R.string.ActivityISharedwith 的长度,直到 %1$s 的部分为 11 才能使其加粗。

也许几天后,我会改变那句话,我想避免每次都计算它的长度。

如果没有 sharedTo.get( getAdapterPosition() ) 的部分,我怎样才能得到它的长度?没有变量的字符串。

谢谢

【问题讨论】:

  • 你试过正则表达式吗? ` String mydata = "String with: 1s$s";模式 pattern = Pattern.compile("^[A-Za-z, ]+:"); Matcher matcher = pattern.matcher(mydata);` 像这样的东西,你需要将模式作为静态变量,因为每次编译都会消耗很多

标签: java android string


【解决方案1】:

您可以在字符串中使用粗体标记并以 HTML 形式显示它,而不是这样做。请看下面的代码

String text = itemView.getContext().getResources().getString( R.string.ActivityIShared_with, sharedTo.get( getAdapterPosition));

SpannableStringBuilder styledString;

if(SDK_INT &gt; N) styledString = (SpannableStringBuilder) Html.fromHtml(,Html.FROM_HTML_MODE_COMPACT) else styledString = (SpannableStringBuilder) Html.fromHtml(result)

tv_Sharewith.setText(styledString.toString());

【讨论】:

    【解决方案2】:

    据我所知,您基本上是在尝试将字符串与某种样式连接起来。您可以直接尝试,只需稍作修改即可解决您的问题

    添加此方法

    public static SpannedString buildString(String boldText, String regularText) {
        final SpannableStringBuilder builder = new SpannableStringBuilder();
        int start = builder.length();
        builder.append(boldText);
        builder.setSpan(new StyleSpan(BOLD), start, builder.length(), SPAN_INCLUSIVE_EXCLUSIVE);
        builder.append(regularText);
        return new SpannedString(builder);
    }
    

    改变

    <string name="ActivityIShared_with">Shared with: %1$s</string>
    

    <string name="ActivityIShared_with">Shared with:</string>
    

    并使用方法

    buildString(context.getString(R.string.ActivityIShared_with), sharedTo.get(getAdapterPosition()));
    

    这样您就不必计算引用ActivityIShared_with的文本长度

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-02-06
      • 2015-09-17
      • 1970-01-01
      • 1970-01-01
      • 2011-05-24
      • 2014-05-11
      • 1970-01-01
      相关资源
      最近更新 更多