Android - 使用TextView自动滚动的ScrollView

时间:2012-11-05 10:36:54

标签: java android xml textview scrollview

我在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>

enter image description here

编辑 - 这是我用来向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是在底部添加空白而不是阻止用户滚动到最后一行文本。任何有关我出错的帮助或指导都将非常感激。

1 个答案:

答案 0 :(得分:1)

当你打电话时看起来像是

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中的大写字母开头。

相关问题