目录
所遇问题
在APP的开发过程中,遇到TextView显示文本并自动滚动到底
解决思路
TextView显示文本并计算高度,并调用函数 scrollTo 滚动到底部
解决方法
/**
* 获取TextView中内容的高度
* @param textView
* @return
*/
public int getTextViewContentHeight(TextView textView) {
Layout layout = textView.getLayout();
int desired = layout.getLineTop(textView.getLineCount());
int padding = textView.getCompoundPaddingTop() + textView.getCompoundPaddingBottom();
return desired + padding;
}
addLog 函数
/**
* 添加日志函数
* @param log
*/
public void addLog(String log){
if (!TextUtils.isEmpty(log)){
String msgInfo = log;
msgInfo += "\r\n\r\n";
if (tvInfo.getText().length() > 1024 * 10){
tvInfo.setText(msgInfo);
tvInfo.scrollTo(0, 0);
}
else{
tvInfo.append(msgInfo);
int offset = getTextViewContentHeight(tvInfo);//调用getTextViewContentHeight
if (offset > tvInfo.getHeight()) {
tvInfo.scrollTo(0, offset - tvInfo.getHeight());
}
}
}
}