我有一个动态添加文本的TextView
。
在我的main.xml
文件中,我将属性设置为最大19行和垂直滚动条。
在.java
文件中,我使用textview.setMovementMethod(new ScrollingMovementMethod());
来允许滚动。
滚动效果很好。一旦占据了19行,并且添加了更多的行,它就会开始滚动。问题是,我想让新文本滚动到视图中。
我写出了textview.getScrollY()
的值,无论发生什么,它都将保持为0
(即使我手动向下滚动并添加新的文本行)。
因此,textview.scrollTo(0, textview.getScrollY());
没有为我做任何事情。
有没有其他方法可以用来获取textview
的垂直滚动量?我读过的所有东西都说,无论出于何种意图和目的,我所做的都应该是有效的:/
发布于 2011-09-08 23:06:27
我在TextView源代码中花了一些功夫,但这是我想出来的。它不需要将TextView包装在ScrollView中,而且,据我所知,它可以完美地工作。
// function to append a string to a TextView as a new line
// and scroll to the bottom if needed
private void addMessage(String msg) {
// append the new string
mTextView.append(msg + "\n");
// find the amount we need to scroll. This works by
// asking the TextView's internal layout for the position
// of the final line and then subtracting the TextView's height
final int scrollAmount = mTextView.getLayout().getLineTop(mTextView.getLineCount()) - mTextView.getHeight();
// if there is no need to scroll, scrollAmount will be <=0
if (scrollAmount > 0)
mTextView.scrollTo(0, scrollAmount);
else
mTextView.scrollTo(0, 0);
}
如果您发现此操作失败的情况,请通知我。我很感激能够修复我的应用程序中的任何错误;)
编辑:我应该提一下,我还使用了
mTextView.setMovementMethod(new ScrollingMovementMethod());
在实例化我的TextView之后。
发布于 2012-10-02 19:17:15
在TextView布局中使用android:gravity="bottom"
。例如。
<TextView
...
android:gravity="bottom"
...
/>
不要问我为什么它能工作。
这种方法唯一的问题是,如果你想在文本视图中向上滚动,那么每次插入新文本时,它都会一直被“下拉”到底部。
发布于 2011-01-06 13:39:24
这是我用来滚动到我的聊天文本底部的。
public void onCreate(Bundle savedInstanceState)
{
this.chat_ScrollView = (ScrollView) this.findViewById(R.id.chat_ScrollView);
this.chat_text_chat = (TextView) this.findViewById(R.id.chat_text_chat);
}
public void addTextToTextView()
{
String strTemp = "TestlineOne\nTestlineTwo\n";
//append the new text to the bottom of the TextView
chat_text_chat.append(strTemp);
//scroll chat all the way to the bottom of the text
//HOWEVER, this won't scroll all the way down !!!
//chat_ScrollView.fullScroll(View.FOCUS_DOWN);
//INSTEAD, scroll all the way down with:
chat_ScrollView.post(new Runnable()
{
public void run()
{
chat_ScrollView.fullScroll(View.FOCUS_DOWN);
}
});
}
编辑:这是XML布局
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<!-- center chat display -->
<ScrollView android:id="@+id/chat_ScrollView"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_alignParentRight="true"
android:layout_alignParentLeft="true">
<TextView android:id="@+id/chat_text_chat"
android:text="center chat"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:singleLine="false" />
</ScrollView>
</RelativeLayout>
https://stackoverflow.com/questions/3506696
复制相似问题