Android TextView可显示完整的最大行数

问题:
在安卓开发中,设计师通常要求文字显示在一块固定区域,我们一般如下定义
height = 30dp;
或者
height = wrap_content;
maxHeight = 30dp;
这样的写法通常情况下是没有问题的, 但是如果用户手动设置了文字大小则可能出现部分文字显示不全的场景
在这里插入图片描述
解决方法:
先上效果
在这里插入图片描述
可以看到蓝色区域要比红色区域的文字显示的合理很多
代码:

<TextView
        android:id="@+id/text"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="19sp"
        android:background="#00fff0"
        android:text="Hello World!"/>
    <TextView
        android:id="@+id/text_error"
        android:layout_width="match_parent"
        android:layout_height="35dp"
        android:background="#ff0000"/>
       
		mContent = findViewById(R.id.text);
        mContent.setText(TEXT);
        TextView errorText = findViewById(R.id.text_error);
        errorText.setText(TEXT);
        getLine(mContent, 80, new CallBack() {
            @Override
            public void onSuccess(int line) {
                mContent.setMaxLines(line);
            }
        });
/**返回textview可显示完整的最大行数
     *
     * @param textView
     * @param MaxHeightDp
     * @param callBack
     */
    private void getLine(final TextView textView, final int MaxHeightDp, final CallBack callBack) {
        textView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                if(textView.getMeasuredHeight() != 0) {
                    int lineHeight = textView.getMeasuredHeight()/ (textView.getLineCount() == 0 ? 1 : textView.getLineCount());
                    if(lineHeight == 0) return;
                    int maxLine = dip2px(MaxHeightDp)/lineHeight;
                    textView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                    if(callBack != null) callBack.onSuccess(maxLine);
                }
            }
        });
    }

解析:
1.addOnGlobalLayoutListener 设置监听, 在view绘制完成后的回调;
addOnGlobalLayoutListener 介绍https://blog.csdn.net/linghu_java/article/details/46544811
2.textView.getMeasuredHeight() 获取textview 的绘制高度
此处需要textview height=wrapcontent 且不可以设置maxHeight或者maxline等类似的属性,否则测量结果不准;
3.获得TextView 的行高
int lineHeight = textView.getMeasuredHeight()/ (textView.getLineCount() == 0 ? 1 : textView.getLineCount());
4.获得可显示的最大行数
int maxLine = dip2px(MaxHeightDp)/lineHeight;
5.为了避免频繁的操作ui,在得到有效结果后删除监听removeOnGlobalLayoutListener;
6.setMaxLines 返回的最大行数需要手动设置哦

注意:
因为textview的高度必须为wrap,为了不影响您的设计逻辑, 您可以创建一个属性相同的独立的TextView来计算最大行数。

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值