问题:
在安卓开发中,设计师通常要求文字显示在一块固定区域,我们一般如下定义
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来计算最大行数。