Replace part of string with drawable or image

Asked

Viewed 71 times

2

I receive from the database a string in formatting "text text ??? text text" and need to transform the "??" in an image or some character, the ideal would be an image or drawable that I can customize better. From what I’ve seen replace only works with string, so I’m out of direction to go.

That’s kind of the idea:

inserir a descrição da imagem aqui

2 answers

2


Insert a Imagespan in a Spannablestring.

Imagespan is built with the drawable to insert and Spannablestring with the text where it will be inserted.

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main2);

    TextView textView = findViewById(R.id.textView);

    String text = "texto ? texto";

    //Posição onde colocar a imegem(posição da marca)
    int imagePos = text.indexOf("?");

    //Criar um SpannableString do texto
    SpannableString spannableString = new SpannableString(text);

    //Obter o drawable a inserir
    Drawable drawable = getResources().getDrawable(R.mipmap.ic_launcher);
    drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());

    //Criar um ImageSpan do drawable
    ImageSpan imageSpan = new ImageSpan(drawable, ImageSpan.ALIGN_BASELINE);

    //Inserir a imagem(ImageSpan) no texto(SpannableString)
    spannableString.setSpan(imageSpan,imagePos,imagePos+1, Spanned.SPAN_INCLUSIVE_INCLUSIVE);

    //Atribuir o texto com a imagem ao TextView
    textView.setText(spannableString);
}

The principle is this. Adjust to your needs.

  • Just in time to create the spannablestring put the string without the mark, otherwise worked perfectly

  • started from Indexoutofboundsexception error: setSpan (51 ... 52) ends Beyond length 51

  • I edited the answer.

  • and to replace "??" instead of "?" how do I do?

  • because I changed where this "?" and the result was image+??

  • 1

    You have to eliminate the "?" surpluses.

  • Since I am developing the backend, I will change the style to be simpler. Thanks

Show 2 more comments

1

Browser other questions tagged

You are not signed in. Login or sign up in order to post.