gpt4 book ai didi

java - Android ScrollView 仅在您已经到达底部时才滚动到底部

转载 作者:行者123 更新时间:2023-12-02 07:03:32 25 4
gpt4 key购买 nike

我有一个基本的 Android 应用程序,设置了 ScrollView 并动态添加文本。我希望它在添加文本时滚动到底部(这已经发生了),但我只希望它在您已经位于底部时滚动到底部,所以如果您正在阅读某些内容,它不会只是滚动。这是我到目前为止所拥有的。

private void AddText(final String msg){
this.runOnUiThread(new Runnable() {
public void run() {
TextView log = (TextView) findViewById(R.id.chatlog);
if(log.getText().equals("Loading...")){
log.setText(msg);
}else{
ScrollView scroller = (ScrollView) findViewById(R.id.scroll_container);
//set current scroll position
int scroll_pos = scroller.getScrollY();
//scroll to bottom
scroller.fullScroll(ScrollView.FOCUS_DOWN);
//set bottom position
int scroll_bot = scroller.getScrollY();
//add the text
log.append("\r\n" + msg);
//if you weren't at the bottom
//scroll back to where you were.
//This isn't working, scroll bot is the same
//as scroll pos.
if(scroll_pos != scroll_bot){
scroller.scrollTo(0, scroll_pos);
}
//System.out.println("Pos: " + scroll_pos);
//System.out.println("Bot: " + scroll_bot);
}
}
});
}

最佳答案

到目前为止,我发现的最佳解决方案是使用带有可运行对象的scrollView.post()方法,该方法将在文本更改后调用:

final ScrollView scrollView = (ScrollView) findViewById(R.id.consoleTab);
TextView textView = (TextView) findViewById(R.id.consoleView);
boolean autoScroll = (textView.getBottom() - (scrollView.getHeight() + scrollView.getScrollY())) <= 0;
textView.setText(state.getConsole().getText());

if (autoScroll) {
scrollView.post(new Runnable() {
public void run() {
scrollView.fullScroll(ScrollView.FOCUS_DOWN);
}
});
}

关于java - Android ScrollView 仅在您已经到达底部时才滚动到底部,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16356056/

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