Android实现TextView前面加标签的方法

好好的textView前面加了个标签...
这要是单行还好,直接一个drawable了事
但是多行...我可以自定义一个ShapeDrawable,实现drawableLeft,但是有个问题,如果是这样的话,drawable是会随字体居中的,那显示效果就很怪异了!

一、通过span
这个是最靠谱的解决方法了吧,其实span可以帮我们解决几乎所有关于textview的问题,可是貌似很多人(包括我)都不了解她。
具体可以了解下
https://blog.csdn.net/qq_16430735/article/details/50427978

二、自定义TextView
废话少说,直接上工具类代码:

public class TagTextView extends AppCompatTextView {

    private StringBuffer content_buffer;

    private TextView tv_tag;

    private View view;//标签布局的最外层布局

    private Context mContext;

    //必须重写所有的构造器,否则可能会出现无法inflate布局的错误!
    public TagTextView(Context context) {
        super(context);
        mContext = context;
    }

    public TagTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        mContext = context;
    }

    public TagTextView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        mContext = context;
    }

    public void setContentAndTag(String content, List<String> tags) {
        content_buffer = new StringBuffer();
        for (String item : tags) {//将每个tag的内容添加到content后边,之后将用drawable替代这些tag所占的位置
            content_buffer.append(item);
        }
        content_buffer.append(content);
        SpannableString spannableString = new SpannableString(content_buffer);
        for (int i = 0; i < tags.size(); i++) {
            String item = tags.get(i);
            View view = LayoutInflater.from(mContext).inflate(R.layout.tag, null);//R.layout.tag是每个标签的布局
            tv_tag = view.findViewById(R.id.tv_tag);
            tv_tag.setText(item);
            Bitmap bitmap = convertViewToBitmap(view);
            Drawable d = new BitmapDrawable(bitmap);
            d.setBounds(0, 0, tv_tag.getWidth(), tv_tag.getHeight());//缺少这句的话,不会报错,但是图片不回显示
            ImageSpan span = new ImageSpan(d, ImageSpan.ALIGN_BOTTOM);//图片将对齐底部边线
            int startIndex;
            int endIndex;
            startIndex = getLastLength(tags, i);
            endIndex = startIndex + item.length();
            Log.e("tag", "the start is" + startIndex + "the end is" + endIndex);
            spannableString.setSpan(span, startIndex, endIndex, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
        setText(spannableString);
        setGravity(Gravity.CENTER_VERTICAL);
    }

    private static Bitmap convertViewToBitmap(View view) {
        view.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED), View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
        view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());
        view.buildDrawingCache();
        Bitmap bitmap = view.getDrawingCache();
        return bitmap;

    }

    private int getLastLength(List<String> list, int maxLength) {
        int length = 0;
        for (int i = 0; i < maxLength; i++) {
            length += list.get(i).length();
        }
        return length;
    }
}

tag布局:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">
    <TextView
        android:id="@+id/tv_tag"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical"
        android:layout_marginBottom="2dp"
        android:layout_marginEnd="5dp"
        android:background="@drawable/bg_blue_20"
        android:gravity="center_vertical"
        android:paddingBottom="2dp"
        android:paddingLeft="3dp"
        android:paddingRight="3dp"
        android:text="标签"
        android:textColor="@android:color/white"
        android:textSize="12sp"/>
</LinearLayout>

layout_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".activity.TagTextViewActivity">
    <com.smt.saveviewtocream.utils.TagTextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

具体使用(kotlin)

class TagTextViewActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_tag_text_view)

        val tags: MutableList<String> = ArrayList()
        tags.add("置顶")
        tags.add("置顶1")
        tags.add("置顶2")
        textView.setContentAndTag(
            "今天是个好日子",
            tags
        )
    }
}

结果:


推荐阅读更多精彩内容