[英]Best Android control for displaying scrollable multiline text
I'm starting to write an ebook type of program in Android and don't know the best alternative to Apple's UITextView. 我开始在Android中编写电子书类型的程序,并且不知道Apple的UITextView的最佳替代品。
It needs to display multiline read-only text and be scrollable. 它需要显示多行只读文本并且可以滚动。
You already know this class - it is TextView
- you can adjust it to be scrollable. 您已经知道这个类 - 它是
TextView
- 您可以将其调整为可滚动。
In XML view template put android:scrollbars="vertical"
: 在XML视图模板中输入
android:scrollbars="vertical"
:
<TextView
android:id="@+id/myText"
android:scrollbars="vertical"
In java code put then: 在java代码中放入:
mTextView = (TextView) findViewById(R.id.myText);
mTextView.setMovementMethod(ScrollingMovementMethod.getInstance());
If you want your TextView
to scroll automatically to the bottom after the text is changed, add the code like below: 如果您希望
TextView
在文本更改后自动滚动到底部,请添加如下代码:
mTextView.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
@Override
public void afterTextChanged(Editable s) {
scrollToLastLine(mTextView);
}
private void scrollToLastLine(TextView tv) {
int scrollY = 0;
if (!TextUtils.isEmpty(tv.getText())) {
final int linesCount = tv.getLineCount();
if (linesCount > 0) {
scrollY = Math.max(0,
tv.getLayout().getLineTop(linesCount)
- tv.getHeight());
}
}
tv.scrollTo(0, scrollY);
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.