gpt4 book ai didi

android - 屏幕旋转后如何恢复textview滚动位置?

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:42:10 25 4
gpt4 key购买 nike

在我的 Android 布局中,我有一个 TextView。此 TextView 显示相当大的可跨越文本,并且能够滚动。现在当手机旋转时,View 被销毁并创建,我必须再次 setText() TextView,将滚动位置重置为开头。

我知道我可以使用 getScrolly() 和 scrollTo() 滚动到像素位置,但是由于 View 宽度的变化,线条变长了,像素位置 400 的线条现在可能是 250。所以这个不是很有帮助。

我需要一种方法来在 onDestroy() 中找到 TextView 中的第一条可见行,然后需要一种方法使 TextView 在旋转后滚动到这段特定的文本。

有什么想法吗?

最佳答案

这是一个老问题,但我在寻找同一问题的解决方案时来到这里,所以这就是我想出的。我结合了对这三个问题的回答的想法:

我试图只从我的应用程序中提取相关代码,所以请原谅任何错误。另请注意,如果您旋转到横向并返回,它可能不会在您开始时的相同位置结束。例如,假设“Peter”是肖像中第一个可见的词。当您旋转到横向时,“Peter”是该行的最后一个词,第一个是“Larry”。当您向后旋转时,“Larry”将可见。

private static float scrollSpot;

private ScrollView scrollView;
private TextView textView;

protected void onCreate(Bundle savedInstanceState) {
textView = new TextView(this);
textView.setText("Long text here...");
scrollView = new ScrollView(this);
scrollView.addView(textView);

// You may want to wrap this in an if statement that prevents it from
// running at certain times, such as the first time you launch the
// activity with a new intent.
scrollView.post(new Runnable() {
public void run() {
setScrollSpot(scrollSpot);
}
});

// more stuff here, including adding scrollView to your main layout
}

protected void onDestroy() {
scrollSpot = getScrollSpot();
}

/**
* @return an encoded float, where the integer portion is the offset of the
* first character of the first fully visible line, and the decimal
* portion is the percentage of a line that is visible above it.
*/
private float getScrollSpot() {
int y = scrollView.getScrollY();
Layout layout = textView.getLayout();
int topPadding = -layout.getTopPadding();
if (y <= topPadding) {
return (float) (topPadding - y) / textView.getLineHeight();
}

int line = layout.getLineForVertical(y - 1) + 1;
int offset = layout.getLineStart(line);
int above = layout.getLineTop(line) - y;
return offset + (float) above / textView.getLineHeight();
}

private void setScrollSpot(float spot) {
int offset = (int) spot;
int above = (int) ((spot - offset) * textView.getLineHeight());
Layout layout = textView.getLayout();
int line = layout.getLineForOffset(offset);
int y = (line == 0 ? -layout.getTopPadding() : layout.getLineTop(line))
- above;
scrollView.scrollTo(0, y);
}

关于android - 屏幕旋转后如何恢复textview滚动位置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5381964/

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