TextView文字图片混排并添加点击事件监听,Textview里面的ImageSpan添加点击响应事件

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

String str = "这个一个文字图片混排,文字结尾添加图片";

SpannableString ss = new SpannableString(str + " ");
int len = ss.length();
//图片,更换成自己工程里的图片
Drawable d = ContextCompat.getDrawable(this, (R.mipmap.icon_arror_expand));
d.setBounds(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight());
//构建ImageSpan
ImageSpan span = new ImageSpan(d, ImageSpan.ALIGN_BASELINE);
ss.setSpan(span, len - 1, len, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
ss.setSpan(new ClickableSpan() {
    @Override
    public void onClick(@NonNull View widget) {
        Log.e(TAG,"textView图片点击------");
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(getBaseContext(),"图片点击", Toast.LENGTH_SHORT).show();
            }
        });
    }
}, len - 1, len, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
tv.setText(ss);
//需要设置这个才能点击
tv.setMovementMethod(LinkMovementMethod.getInstance());
//去掉高亮,不然点击时候背景会变高亮
tv.setHighlightColor(getResources().getColor(android.R.color.transparent));

你可能感兴趣的:(android开发,Java,android面试题,android,textView结尾添加图片,textView文字图片混排,textView图片点击事件,ImageSpan点击事件)