2012-11-05 141 views
1

我在ScrollView中有一个TextView,它目前滚动到TextView的底部。Android - 使用TextView自动滚动的ScrollView

TextView被动态填充不断更新(TextView本质上充当动作控制台)。

但是,我遇到的问题是,当动态文本添加到滚动视图时,用户可以滚动浏览文本到黑色空间,每当更多内容添加到黑色空间时增加到TextView。

我已经尝试了各种不同的应用,但是没有一个给出了正确的结果。我不能使用maxLines或定义布局的高度,因为我需要这对于各种屏幕尺寸是动态的,这些屏幕的行数可以不断变化。

我也orginally这样做pro​​gromatically,然而这是坠毁在随机时间,因此想保持它在我的布局(更好usabilty),下面的示例代码:

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将空白空间添加到底部,而不是阻止用户在文本的最后一行滚动。任何帮助或指导我哪里去错了将不胜感激。

+0

难道你不是在文本中添加新的换行符吗?向我们展示您更新'TextView'的代码。 –

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

+0

我已经实现了你的StringBuilder代码,不幸的是我遇到了同样的问题。 BattleConsole不应该有一个空字符串,因为在调用CreateConsoleString()来更新TextView之前,我总是硬编码一些要添加到ArrayList的文本。我在自己的问题中添加了我如何添加到BattleConsole的代码。谢谢 –

+0

你可以附上截图吗? –

+0

我已经添加了问题的屏幕截图,滚动视图位于间隔线下方和上方,您可以看到。谢谢 –