android开发中TextView中图文混排显示的实现(批量插入图片)

直接上代码:

package com.example.pengliu.textandimageshowdemo;

import android.graphics.drawable.Drawable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.ImageSpan;
import android.widget.TextView;


public class MainActivity extends AppCompatActivity {

    private TextView textView;
    private String[] str = {
            "这是图片",
            "http://i.imgur.com/DvpvklR.png"
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        textView=findViewById(R.id.textView);
        //需要处理的文本,[image]是需要被替代的文本
        String TMInfo="图片标签普吉\r\n[image1]\r\n阿赛克\r\n[image2]\r\n...\r\n[image3]\r\n";
        int imagecount=getImageNum(TMInfo);
        SpannableString spannable = new SpannableString(TMInfo);
        for (int i=1;i<=imagecount;i++){
            Drawable drawable = getResources().getDrawable(R.mipmap.ic_launcher);
            drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
            //要让图片替代指定的文字就要用ImageSpan
            ImageSpan span = new ImageSpan(drawable, ImageSpan.ALIGN_BASELINE);
            int replaceStartIndex=TMInfo.indexOf("[image"+i+"]");
            //开始替换,注意第2和第3个参数表示从哪里开始替换到哪里替换结束(start和end)
            //最后一个参数类似数学中的集合,[5,12)表示从5到12,包括5但不包括12
            spannable.setSpan(span, replaceStartIndex,replaceStartIndex+String.valueOf("[image"+i+"]").length()
                    , Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
            textView.setText(spannable);
        }
    }

    private int getImageNum(String TMInfo){
        String[] tmInfos=TMInfo.split("image");
        return tmInfos.length-1;
    }
}

显示效果如下:


猜你喜欢

转载自blog.csdn.net/lpcrazyboy/article/details/80327264