Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
542 views
in Technique[技术] by (71.8m points)

android - How to add drawable image inside textview

I need a drawable within the text, just like an emoji, so e.g.

"Please press the button looking like this ?? and then proceed ..."

but with a custom drawable instead of the emoji in my example. (How) is this possible?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I need a drawable within the text

You can Use ImageSpan

  • Span that replaces the text it's attached to with a Drawable that can be aligned with the bottom or with the baseline of the surrounding text. The drawable can be constructed from varied sources:

but with a custom drawable instead of the emoji in my example. (How) is this possible?

Try this working example

public class MainActivity extends AppCompatActivity {

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

        TextView  textView=findViewById(R.id.tv);
        Spannable span = new SpannableString("Please press the button looking like this and then proceed ..");
        Drawable test = getResources().getDrawable(R.drawable.abc);
        test.setBounds(0, 0, 32,32);
        ImageSpan imageSpan = new ImageSpan(test, ImageSpan.ALIGN_BASELINE);
        span.setSpan(imageSpan, 36, 37, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);

        textView.setText(span);
    }


}

RESULT

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...