Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
396 views
in Technique[技术] by (71.8m points)

android - ScrollView .scrollTo not working? Saving ScrollView position on rotation

Ok.. I must be overlooking something real simple here, but i think i'm trying to do something fairly basic.. Simply retain the scrollbar position of a ScrollView on orientation change...

Here is the code for my onSaveInstanceState and onRestoreInstanceState.. sView is the container for the ScrollView layout. Within my scrollview is a linearlayout with a lot of textviews.

    @Override 
public void onSaveInstanceState(Bundle outState) 
{
    //---save whatever you need to persist—

    outState.putInt("sViewX",sView.getScrollX());
    outState.putInt("sViewY",sView.getScrollY());

super.onSaveInstanceState(outState);

}

@Override
public void onRestoreInstanceState(Bundle savedInstanceState) 
{
    super.onRestoreInstanceState(savedInstanceState);

    sViewX = savedInstanceState.getInt("sViewX");   
    sViewY = savedInstanceState.getInt("sViewY");

    sView.scrollTo(sViewX, sViewY);

}

If I set a Toast with the values of sViewX and sViewY on the Restore, the values are kept and correct.

Edit: I just tried to do a sView.scrollTo(0,150); in my onCreate.. just to see if that would open the activity at 150px down, and it didn't. I think my issue has to do with the .scrollTo method.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I figured it out.

Since I'm using setText to TextViews in my onCreate, calling .scrollTo won't work.

So now I'm using the following:

sView.post(new Runnable() {
    @Override
    public void run() {
        sView.scrollTo(sViewX, sViewY);
    } 
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...