1

As we see in https://stackoverflow.com/a/10144094/3286489, we could add arguments into our String parameter through the %1$d etc. But I don't know how to add image there.

We could add image to our String as we see in https://stackoverflow.com/a/3177667/3286489 using spannable. But the position of the image within the text need to explicitly stated.

So my question is, is there a way where we could insert our image into the TextView (I'm okay using spannable), using parameterized approach as https://stackoverflow.com/a/10144094/3286489?

Community
  • 1
  • 1
Elye
  • 53,639
  • 54
  • 212
  • 474

2 Answers2

1

Here's what I've done before:

eg. your string could be: "This is an [img]".

Find the position of "[img]" and replace it with ImageSpan

EDIT: Regex pattern could be something like

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());
}
Malvin
  • 692
  • 5
  • 8
  • Thanks Malvin. That's what I did now. But I'm thinking if there's the finding of position could be done automatically like the argument feature in string resources we have, without us needing to do indexOf from the string. – Elye Jun 14 '16 at 04:14
  • By position do you mean the position of "[img]" tag or the position of the image to be used, eg. `displayImage("This is 2nd image %2$img and first image %1$img", firstImage, secondImage);` – Malvin Jun 14 '16 at 04:22
  • Ya, something like that... So I don't need to do matcher etc. – Elye Jun 14 '16 at 04:23
  • I guess you still need to use Regex but with Capturing Group https://docs.oracle.com/javase/tutorial/essential/regex/groups.html. And the pattern would be something like "\\\[([d]*)img\\\]" with String "This is [1img], [2img]" – Malvin Jun 14 '16 at 04:31
  • If you don't use indexOf so java will ask you, where do you want to put the image span? – Holi Boom Jun 14 '16 at 04:43
0
  1. string.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);
    
Holi Boom
  • 1,346
  • 1
  • 12
  • 29