我在 ScrollView 中有一个 TextView,它当前滚动到 TextView 的底部。
TextView 动态填充并不断更新(TextView 本质上充当操作控制台)。
但是,我遇到的问题是,当动态文本添加到 ScrollView 时,用户可以将文本滚动到黑色空间,每次向 TextView 添加更多内容时,黑色空间都会增加。
我尝试了各种不同的方法,但没有一个给出正确的结果。我不能使用 maxLines 或定义布局的高度,因为我需要它对于各种屏幕尺寸是动态的,其中可见的行数不断变化。
我最初也以编程方式完成此操作,但是这是随机崩溃的,因此我想将其保留在我的布局中(更好的可用性),示例代码如下:
final int scrollAmount = update.getLayout().getLineTop(update.getLineCount()) - update.getHeight();
if(scrollAmount > 0)
{
update.scrollTo(0, scrollAmount);
}
下面的代码是我当前的布局 xml,用于在添加内容时自动将我的 TextView 滚动到底部:
<ScrollView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_above="@+id/spacer2"
android:layout_below="@+id/spacer1"
android:fillViewport="true" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TextView
android:id="@+id/battle_details"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:textSize="12dp"
android:layout_gravity="bottom" />
</LinearLayout>
</ScrollView>
编辑 - 这是我用来向我的 TextView 添加文本的代码:
private void CreateConsoleString()
{
TextView update = (TextView)findViewById(R.id.battle_details);
String ConsoleString = "";
// BattleConsole is an ArrayList<String>
for(int i = 0; i < BattleConsole.size(); i++)
{
ConsoleString += BattleConsole.get(i) + "\n";
}
update.setText(ConsoleString);
}
编辑 2 - 我像这样向 BattleConsole 添加内容:
BattleConsole.add("Some console text was added");
CreateConsoleString();
总而言之,我唯一的问题是 ScrollView 和/或 TextView 在底部添加了空白,而不是阻止用户在最后一行文本处滚动。任何关于我哪里出错的帮助或指导将不胜感激。
最佳答案
调用时看起来是这样
BattleConsole.get(i)
它有时会返回一个空的 String
,所以您基本上只是在 TextView
中添加新行。
例如,您可以这样做:
StringBuilder consoleString = new StringBuilder();
// I'm using a StringBuilder here to avoid creating a lot of `String` objects
for(String element : BattleConsole) {
// I'm assuming element is not null
if(!"".equals(element)) {
consoleString.append(element);
consoleString.append(System.getProperty("line.separator")); // I'm using a constant here.
}
}
update.setText(consoleString.toString());
如果你能发布BattleConsole
的代码,我可以帮助你更多。
作为脚注:鼓励在 java 中使用 camelCase。根据约定,在 java 中只有类名以大写字母开头。
关于java - Android - 带有 TextView 自动滚动的 ScrollView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13230323/