开发者

How to maintain the scrolling state while orientation change in android

开发者 https://www.devze.com 2023-01-18 15:28 出处:网络
I have created one custom view that contains the horizontalscrollview. Now when i changes the orientation its scroll state change to 0 every time.

I have created one custom view that contains the horizontalscrollview. Now when i changes the orientation its scroll state change to 0 every time.

I got the previous scroll state by using onSaveInstanceState(Bundle savedInstanceState) and onRestoreInstanceState(Bundle savedInstanceState) . in onRestoreInstanceState i am using following method to get reposition the scroll,

hoz_scroll.scrollTo(hoz_x_pos, hoz_scroll.g开发者_Python百科etScrollY());

But there is not effect at all. Help appreciated. Thanks.


If you have to call onCreate every time orientation change the position resets. You can avoid it by adding orientation changed to manifest but not sure if current scroll state is intact. I have researched it couple of days ago.If your interface has stadar dimentions on every orientation then you might find an equation by sampling many scroll values.

Create a map with the getScrollY() with values on landscape and portait that displays the same text. More values are better. Then use Polynomial interpolation to create a polynomial equation using matlab or papper. More values -> more accuracy http://en.wikipedia.org/wiki/Polynomial_interpolation

also scrolling to a position must be done like this

hoz_scroll.post(new Runnable() {

    public void run() {
        scroller.scrollTo(hoz_x_pos,hoz_scroll.getScrollY());
    }
});


I believe you need to set

android:configChanges="orientation"

in your activity's element in AndroidManifest.xml.

Then you need to override public void onConfigurationChanged(Configuration config) in your activity.


Put this code in your Activity to not have it scroll when orientation changes. You don't even need to code.

@Override
public void onConfigurationChanged(Configuration config){
    super.onConfigurationChanged(config);
}


here is a working solution:

private ScrollView scroll;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_content);


    TextView title=(TextView) findViewById(R.id.textView1);
    TextView content=(TextView) findViewById(R.id.textView2);

    title.setText(getIntent().getStringExtra("title"));
    content.setText(getIntent().getStringExtra("content"));

    scroll = (ScrollView) findViewById(R.id.scrollView1);
    if(savedInstanceState!=null){
        final int y=savedInstanceState.getInt("position");
        scroll.post(new Runnable() {

            public void run() {
                scroll.scrollTo(0,y);
            }
        });
    }
}

@Override
protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    outState.putInt("position", scroll.getScrollY());
}
0

精彩评论

暂无评论...
验证码 换一张
取 消