我有一个TextView,其内容是从文本文件中复制的。现在每次将文本文件的内容加载到TextView中时,我希望它自动向下滚动到末尾。 以下是我的布局XML文件中的部分内容:
<ScrollView
android:id="@+id/scroller"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:layout_above="@+id/command"
android:layout_alignParentLeft="true"
android:layout_below="@+id/header"
android:fillViewport="true" >
<TextView
android:id="@+id/output"
android:layout_width="fill_parent"
android:layout_height="132dp"
android:bufferType="spannable"
android:editable="false"
android:enabled="false"
android:focusable="true"
android:focusableInTouchMode="false"
android:freezesText="true"
android:inputType="textMultiLine"
android:isScrollContainer="true"
android:scrollbars="vertical"
android:text="@string/output" >
<requestFocus />
</TextView>
</ScrollView>
这就是函数的样子:
public void displayOutput()
{
File sdcard = Environment.getExternalStorageDirectory();
File file = new File(sdcard,"/Android/data/terminalemulatorlog.txt");
StringBuilder text = new StringBuilder();
try
{
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null)
{
text.append(line);
text.append('\n');
}
}
catch (IOException e)
{
Toast.makeText(getApplicationContext(),"Error reading file!",Toast.LENGTH_LONG).show();
}
TextView output=(TextView) findViewById(R.id.output);
output.setText(text);
((ScrollView) findViewById(R.id.scroller)).post(new Runnable()
{
public void run()
{
((ScrollView) findViewById(R.id.scroller)).fullScroll(View.FOCUS_DOWN);
}
});
}
现在我在这里找到了一个部分解决方案。因此,最后一行代码如下:
((ScrollView) findViewById(R.id.scroller)).post(new Runnable()
{
public void run()
{
((ScrollView) findViewById(R.id.scroller)).fullScroll(View.FOCUS_DOWN);
}
});
但是这只在文本文件第一次加载时有效。我该如何始终使TextView滚动到末尾?