【问题标题】:Is it possible inserting Image into TextView using string argument approach?是否可以使用字符串参数方法将图像插入 TextView?
【发布时间】:2016-10-14 15:01:36
【问题描述】:

正如我们在https://stackoverflow.com/a/10144094/3286489 中看到的,我们可以通过 %1$d 等将参数添加到我们的 String 参数中。但我不知道如何在那里添加图像。

我们可以像在https://stackoverflow.com/a/3177667/3286489 中看到的那样使用 spannable 将图像添加到我们的字符串中。但是图片在文字中的位置需要明确说明。

所以我的问题是,有没有一种方法可以将我们的图像插入到 TextView 中(我可以使用 spannable),使用参数化方法 https://stackoverflow.com/a/10144094/3286489

【问题讨论】:

    标签: android spannablestring spannable


    【解决方案1】:

    这是我以前做过的:

    例如。您的字符串可能是:“这是一个 [img]”。

    找到“[img]”的位置,替换为ImageSpan

    编辑:正则表达式模式可能类似于

    String message = "This is an [img]";
    Pattern MY_PATTERN = Pattern.compile("\\[img\\]");
    Matcher matcher = MY_PATTERN.matcher(message);
    // Check all occurrences
    while (matcher.find()) {
        System.out.print("Start index: " + matcher.start());
        System.out.print(" End index: " + matcher.end());
    }
    

    【讨论】:

    • 谢谢马尔文。这就是我现在所做的。但我在想是否可以像我们拥有的字符串资源中的参数功能一样自动完成位置的查找,而不需要我们从字符串中执行 indexOf。
    • 位置是指“[img]”标签的位置还是要使用的图像的位置,例如。 displayImage("This is 2nd image %2$img and first image %1$img", firstImage, secondImage);
    • 是的,类似的东西......所以我不需要做匹配器等。
    • 我猜你仍然需要使用正则表达式,但需要使用捕获组docs.oracle.com/javase/tutorial/essential/regex/groups.html。模式类似于 "\\[([d]*)img\\]" 和字符串 "This is [1img], [2img]"
    • 如果你不使用 indexOf 那么java会问你,你想把图片跨度放在哪里?
    【解决方案2】:
    1. 字符串.xml

      <string name="var">Image %1$s and %2$s</string>
      
    2. MainActivity.java

      TextView textView = (TextView) findViewById(R.id.text);
      String v1 = "%1$s";
      String v2 = "%2$s";
      String test = getString(R.string.var, v1, v2);
      
      Spannable span = Spannable.Factory.getInstance().newSpannable(test);
      
      span.setSpan(new ImageSpan(getBaseContext(), android.R.drawable.star_on),
              test.indexOf(v1), test.indexOf(v1) + v1.length(),
              Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
      
      span.setSpan(new ImageSpan(getBaseContext(), android.R.drawable.star_on),
              test.indexOf(v2), test.indexOf(v2) + v2.length(),
              Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
      
      textView.setText(span);
      

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多