先在onCreate里添加操作:
et_text1.setMovementMethod(new ScrollingMovementMethod());
xml:
<ScrollView
android:id="@+id/sv_show"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fadeScrollbars="false"
android:scrollbarAlwaysDrawVerticalTrack="true"
android:scrollbars="vertical">
<TextView
android:id="@+id/et_text1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:scrollbars="vertical"
android:height="200px"
android:text="提示信息\n">
</TextView>
</ScrollView>
mainactivity:
// 内层高度超过外层
int offset = getTextViewHeight(et_text1) - et_text1.getHeight();
if (offset < 0) {
System.out.println("内层高度小于外层 offset=" + offset);
offset = 0;
}
else
System.out.println("内层高度超过外层 offset=" + offset);
//滚动offset偏移量
et_text1.scrollTo(0, offset);
getTextViewHeight方法获取每次添加文字TextView实际高度
private int getTextViewHeight(TextView pTextView) {
Layout layout = pTextView.getLayout();
int desired = layout.getLineTop(pTextView.getLineCount());
int padding = pTextView.getCompoundPaddingTop() + pTextView.getCompoundPaddingBottom();
return desired + padding;
}
控制台输出
模拟器app效果