TextView 实现跟随标签

5,665 阅读4分钟

一、前言

在设计中经常出现一个长度不确定的文本,后面或是前面跟随一个或是多个标签。在网上查了很多资料,大部分的实现方式都是通过富文本来实现,不能满足多变的要求,标签要可以是图片,还可以是不同的文字,或者是一个布局,有时会加多个标签。后来想到了一种解决方法。将整个部分拆分成多个布局,自由组合,可以满足各种需求,无论标签有多少个,放在前面还是后面都可以实现。

二、具体实现

2.1 文字限制一行时,标签在文字后面

效果图: 文字较少时就像第一行这样,文字较多显示不下时就像二三行那样省略。 image.png

    1. 实现方法一,使用线性布局实现
<LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="horizontal">
            <TextView
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:text="不宽度,不确定字数"
                android:singleLine="true"
                />
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="跟随标签"
                android:background="@color/yellow_FF9B52"/>
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="跟随标签2"
                android:background="@color/blue_74D3FF"/>
        </LinearLayout>
    1. 实现方法二,使用约束布局实现
<androidx.constraintlayout.widget.ConstraintLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <TextView
                android:id="@+id/refund_name"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:singleLine="true"
                android:text="长数据长数据长数据长数据长数据长数据长数据长数据长数据"
                app:layout_constrainedWidth="true"
                app:layout_constraintBottom_toBottomOf="parent"
                app:layout_constraintHorizontal_bias="0"
                app:layout_constraintHorizontal_chainStyle="packed"
                app:layout_constraintLeft_toLeftOf="parent"
                app:layout_constraintRight_toLeftOf="@id/refund_mark_num"
                app:layout_constraintTop_toTopOf="parent" />

            <TextView
                android:id="@+id/refund_mark_num"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:background="@color/yellow_FF9B52"
                android:text="跟随标签"
                android:gravity="center"
                app:layout_constrainedWidth="true"
                app:layout_constraintLeft_toRightOf="@+id/refund_name"
                app:layout_constraintRight_toRightOf="parent"
                app:layout_constraintTop_toTopOf="parent" />

        </androidx.constraintlayout.widget.ConstraintLayout>

2.2 文字多行有限制或者不限制行数,标签在文字后面

效果图:

    1. 文字较少,只够一行时效果:

image.png

    1. 文字显示一行半时效果

image.png

    1. 文字两行显示不下时

image.png

    1. 实现思路:

以上面效果图为例,上面限制文字显示两行,第一行是一个单独的 TextView,第二行就是上面2.1 里面一行文字时实现的效果。当文字较少时,只显示一行,第一行的 TextView 隐藏即可。当文字超过一行少于两行时或者超过两行时,第一行的 TextView 设置显示一行就行,第二行的 TextView 设置显示剩下的文字内容。

    1. 具体的实现代码如下:

xml 文件:

 <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="限制两行,后面跟随标签"
            android:textColor="@color/white"
            android:background="@color/red"
            />
        <androidx.constraintlayout.widget.ConstraintLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginHorizontal="@dimen/m15">

            <TextView
                android:id="@+id/tv_rl_test_tagOne"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="长数据长数据长数据长据长数据长数据长数据长数据长数据长数据长数据长据长数据长数据长数据长数据"
                android:maxLines="1"
                android:textSize="13dp"
                app:layout_constraintTop_toTopOf="parent"
                />

            <TextView
                android:id="@+id/tv_rl_test_tagTwo"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:singleLine="true"
                android:text="长数据长数据长数据长数据长数据长数据长数据长数据长数据"
                app:layout_constrainedWidth="true"
                android:textSize="13dp"
                app:layout_constraintBottom_toBottomOf="parent"
                app:layout_constraintHorizontal_bias="0"
                app:layout_constraintHorizontal_chainStyle="packed"
                app:layout_constraintLeft_toLeftOf="parent"
                app:layout_constraintRight_toLeftOf="@id/tv_rl_test_twoTag"
                app:layout_constraintTop_toBottomOf="@+id/tv_rl_test_tagOne" />

            <TextView
                android:id="@+id/tv_rl_test_twoTag"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:background="@color/yellow_FF9B52"
                android:layout_marginLeft="3dp"
                android:layout_marginTop="2dp"
                android:gravity="center"
                android:paddingLeft="3dp"
                android:paddingTop="1dp"
                android:paddingRight="3dp"
                android:paddingBottom="1dp"
                android:text="标签"
                android:textSize="12dp"
                app:layout_constrainedWidth="true"
                app:layout_constraintLeft_toRightOf="@+id/tv_rl_test_tagTwo"
                app:layout_constraintRight_toRightOf="parent"
                app:layout_constraintTop_toBottomOf="@+id/tv_rl_test_tagOne" />

        </androidx.constraintlayout.widget.ConstraintLayout>

activity 部分:

//要显示的数据源
        String tagSrc = "文字是人类用表意符号记录表达信息以传之久远的方式和工具。现代文字大多是记录语言的工具。人类往往先有口头的语言后产生书面文字,很多小语种,有语言但没有文字。文字的不同体现了国家和民族的书面表达的方式和思维不同。文字使人类进入有历史记录的文明社会。";
        TextView tvTagOnes = (TextView) findViewById(R.id.tv_rl_test_tagOne);
        TextView tvTagTwo = (TextView) findViewById(R.id.tv_rl_test_tagTwo);
        tvTagOnes.setText(tagSrc);
        tvTestOne.setText(tagSrc);
        //判断第一行是否可以完整显示
        tvTagOnes.post(new Runnable() {
            @Override
            public void run() {
             //获取第一个 textview 显示的内容
                String lineContent = Utils.INSTANCE.getTextLineContent(tvTagOnes, 0, tagSrc);
                LogUtils.e(tagSrc + "---------" + lineContent);
                if (TextUtils.equals(tagSrc,lineContent)){//可以显示完整
                    tvTagOnes.setVisibility(View.GONE);
                    tvTagTwo.setText(tagSrc);
                }else {//显示不完整,需要分行
                    tvTagOnes.setVisibility(View.VISIBLE);
                    String srcTwoContent = tagSrc.substring(lineContent.length(), tagSrc.length());
                    tvTagTwo.setText(srcTwoContent);
                }
            }
        });

获取 TextView 显示的内容:

 /**
     * 获取textview某行内容
     */
    fun getTextLineContent(textView: TextView?, line: Int, src: String?): String {
        var result: String = ""
        if (textView == null || src.isNullOrEmpty()) {
            return result
        }
        LogUtils.e("$line--line-->${textView.lineCount}"  )
        if (line > textView.lineCount) {
            return result
        }
        val layout = textView.layout
        val sb = StringBuilder(src)
        LogUtils.e("--start-${layout.getLineStart(line)}----end---${layout.getLineEnd(line)}")
        return sb.subSequence(layout.getLineStart(line), layout.getLineEnd(line)).toString()
    }

2.3 标签在文字前面时

效果图: image.png 实现思路和上面标签在文字后面一样。第一行的标签是一个控件,标签后面的文字是一个单独的 TextView,第二行也是一个单独的 TextView。如果想限制文字行数,直接对第二行的 TextView 限制就行。 xml 布局:

 <!--        前面跟随标签-->
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="前面跟随标签"
            android:textColor="@color/white"
            android:background="@color/red"
            />

        <androidx.constraintlayout.widget.ConstraintLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginHorizontal="@dimen/m15">


            <TextView
                android:id="@+id/tv_rl_test_tagFront"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="标签"
                android:background="@color/yellow_FF9B52"
                app:layout_constraintTop_toTopOf="parent"
                app:layout_constraintStart_toStartOf="parent"/>

            <com.kiwilss.xview.widget.textview.AlignTextView
                android:id="@+id/tv_rl_test_frontOne"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:text="任意显示一行任意显示一行任意显示一行任意显示一行任意显示一行"
                app:layout_constraintTop_toTopOf="parent"
                app:layout_constraintStart_toEndOf="@+id/tv_rl_test_tagFront"
                android:maxLines="1"
                />

            <com.kiwilss.xview.widget.textview.AlignTextView
                android:id="@+id/tv_rl_test_frontTwo"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="任意显示一行任意显示一行任意显示一行任意显示一行任意显示一行"
                app:layout_constraintTop_toBottomOf="@+id/tv_rl_test_tagFront"/>
        </androidx.constraintlayout.widget.ConstraintLayout>

activity 部分:

  //前面加标签
        TextView tvFront = (TextView) findViewById(R.id.tv_rl_test_tagFront);
        TextView tvFrontOne =  findViewById(R.id.tv_rl_test_frontOne);
        TextView tvFrontTwo =  findViewById(R.id.tv_rl_test_frontTwo);

        tvFrontOne.setText(tagSrc);
        //获取tvFrontOne显示的内容
        tvFrontOne.post(new Runnable() {
            @Override
            public void run() {
                //获取第一行显示的内容
                String lineContent = Utils.INSTANCE.getTextLineContent(tvFrontOne, 0, tagSrc);
                if (TextUtils.equals(lineContent,tagSrc)){
                    //一行可以完整显示
                    tvFrontTwo.setVisibility(View.GONE);
                }else {
                    //需要多行才能显示
                    tvFrontTwo.setVisibility(View.VISIBLE);
                    String nextContent = tagSrc.substring(lineContent.length(), tagSrc.length());
                    tvFrontTwo.setText(nextContent);
                }
            }
        });

三、解决对齐问题

image.png 如图,图中第一行和第二行并没有对齐,使用 TextView 时,当文字显示不行时就会自动换行,所以会无法对齐,不对齐就会不够美观。解决方法是让文字两端对齐。如下图: image.png 网上有很多方法可以实现文字两端对齐,这里介绍一种自定义 View 的方法,感觉还可以,中英文混合也可以对齐: AlignTextView:

public class AlignTextView extends AppCompatTextView {

    private boolean alignOnlyOneLine;

    public AlignTextView(Context context) {
        this(context, null);
    }

    public AlignTextView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public AlignTextView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context, attrs);
    }

    private void init(Context context, AttributeSet attrs) {
        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.AlignTextView);
        alignOnlyOneLine = typedArray.getBoolean(R.styleable.AlignTextView_alignOnlyOneLine, false);
        typedArray.recycle();
        setTextColor(getCurrentTextColor());
    }

    @Override
    public void setTextColor(int color) {
        super.setTextColor(color);
        getPaint().setColor(color);
    }

    protected void onDraw(Canvas canvas) {
        CharSequence content = getText();
        if (!(content instanceof String)) {
            super.onDraw(canvas);
            return;
        }
        String text = (String) content;
        Layout layout = getLayout();

        for (int i = 0; i < layout.getLineCount(); ++i) {
            int lineBaseline = layout.getLineBaseline(i) + getPaddingTop();
            int lineStart = layout.getLineStart(i);
            int lineEnd = layout.getLineEnd(i);
            if (alignOnlyOneLine && layout.getLineCount() == 1) {//只有一行
                String line = text.substring(lineStart, lineEnd);
                float width = StaticLayout.getDesiredWidth(text, lineStart, lineEnd, getPaint());
                this.drawScaledText(canvas, line, lineBaseline, width);
            } else if (i == layout.getLineCount() - 1) {//最后一行
                canvas.drawText(text.substring(lineStart), getPaddingLeft(), lineBaseline, getPaint());
                break;
            } else {//中间行
                String line = text.substring(lineStart, lineEnd);
                float width = StaticLayout.getDesiredWidth(text, lineStart, lineEnd, getPaint());
                this.drawScaledText(canvas, line, lineBaseline, width);
            }
        }

    }

    private void drawScaledText(Canvas canvas, String line, float baseLineY, float lineWidth) {
        if (line.length() < 1) {
            return;
        }
        float x = getPaddingLeft();
        boolean forceNextLine = line.charAt(line.length() - 1) == 10;
        int length = line.length() - 1;
        if (forceNextLine || length == 0) {
            canvas.drawText(line, x, baseLineY, getPaint());
            return;
        }

        float d = (getMeasuredWidth() - lineWidth - getPaddingLeft() - getPaddingRight()) / length;

        for (int i = 0; i < line.length(); ++i) {
            String c = String.valueOf(line.charAt(i));
            float cw = StaticLayout.getDesiredWidth(c, this.getPaint());
            canvas.drawText(c, x, baseLineY, this.getPaint());
            x += cw + d;
        }
    }
}

attrs: 显示一行时使用,感觉没什么用处。

<declare-styleable name="AlignTextView">
        <attr name="alignOnlyOneLine" format="boolean"/>
    </declare-styleable>

四、其他实现方式

查找了很多资料,网上也有其他的实现方式,各有优缺点,可以用来参考。

TextView文本尾部添加标签,支持自动换行

android TextView添加标签,一个或多个

TextView多行文字超出时如何在省略号后添加图标

android TextView文字换行内容末尾紧跟图标或其他控件的实现

android之文本前面或后面多标签

Android之旅:突然想玩的TextView前面加标签的方法