TextView 实现跟随标签

TextView 实现跟随标签

一、前言

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

二、具体实现

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前面加标签的方法

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 216,692评论 6 501
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,482评论 3 392
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 162,995评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,223评论 1 292
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,245评论 6 388
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,208评论 1 299
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,091评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,929评论 0 274
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,346评论 1 311
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,570评论 2 333
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,739评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,437评论 5 344
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,037评论 3 326
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,677评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,833评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,760评论 2 369
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,647评论 2 354