gpt4 book ai didi

android - 如何让Android TextView 自动向下滚动到末尾?

转载 作者:太空狗 更新时间:2023-10-29 15:56:20 29 4
gpt4 key购买 nike

我有一个 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);
}
});
}

现在我找到了 here 的部分解决方案.因此最后一行代码说:

((ScrollView) findViewById(R.id.scroller)).post(new Runnable() 
{
public void run()
{
((ScrollView) findViewById(R.id.scroller)).fullScroll(View.FOCUS_DOWN);
}
});

但这只在第一次加载文本文件时有效。如何始终使 TextView 向下滚动到末尾?

最佳答案

只需添加到您的 TextView:
android:gravity="底部"
android:scrollbars = "垂直"

并设置移动方式:
myTextView.setMovementMethod(new ScrollingMovementMethod());

关于android - 如何让Android TextView 自动向下滚动到末尾?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8620153/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com