前置配置
// 绑定前端视图
TextView logView = activity.findViewById(R.id.MainActivityAddLineMsg);
// 设置是否可以手滑滚动,如果没有设置,则不能滑动
logView.setMovementMethod(ScrollingMovementMethod.getInstance());
用法
可以手动调用,然后滚动到最后一行
// Tv 追加内容
logView.append("你好" + new Date() + "\n");
// 自动滚动
int offset=logView.getLineCount()*logView.getLineHeight();
if(offset>logView.getHeight()){
logView.scrollTo(0,offset-logView.getHeight());
}
封装
也可以封装成函数,自动滚动到最后一行
传入 TV 和 str:
void showMsg(TextView logView, String str){
@SuppressLint("SimpleDateFormat") SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss.SSS");
Date date = new Date();
String formattedDate = formatter.format(date);
runOnUiThread(()->{
// 设置是否可以手滑滚动,如果没有设置,则不能滑动
logView.setMovementMethod(ScrollingMovementMethod.getInstance());
logView.append(formattedDate + str + "\n");
int offset=logView.getLineCount()*logView.getLineHeight();
if(offset>logView.getHeight()){
logView.scrollTo(0,offset-logView.getHeight());
}
});
}
用的时候需要 showMsg(TV, MSG);
传入 str:
void showMsg(String str){
@SuppressLint("SimpleDateFormat") SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss.SSS");
Date date = new Date();
String formattedDate = formatter.format(date);
runOnUiThread(()->{
TextView logView = activity.findViewById(R.id.MainActivityAddLineMsg);
// 设置是否可以手滑滚动,如果没有设置,则不能滑动
logView.setMovementMethod(ScrollingMovementMethod.getInstance());
logView.append(formattedDate + str + "\n");
int offset=logView.getLineCount()*logView.getLineHeight();
if(offset>logView.getHeight()){
logView.scrollTo(0,offset-logView.getHeight());
}
});
}
用的时候需要 showMsg(MSG);
评论 (0)