Replace part of string with drawable or image

2

I get the database a string in formarto "text text text ??? text text" and I 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 have no direction to follow.

The idea is more or less this:

    
asked by anonymous 15.01.2018 / 13:17

2 answers

2

Insert a ImageSpan into SpannableString .

ImageSpan is built with the drawable to insert and the 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.

    
15.01.2018 / 15:08
1

Well I usually use fromHtml () to display html-formatted text in a text view, take a look here link the person shows how to display text and image in text view

    
15.01.2018 / 13:33