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?

2 Answers 2

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());
}
Sign up to request clarification or add additional context in comments.

5 Comments

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.
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);
Ya, something like that... So I don't need to do matcher etc.
I guess you still need to use Regex but with Capturing Group docs.oracle.com/javase/tutorial/essential/regex/groups.html. And the pattern would be something like "\\[([d]*)img\\]" with String "This is [1img], [2img]"
If you don't use indexOf so java will ask you, where do you want to put the image span?
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);
    

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.