簡體   English   中英

如何在Android中更改方向時保持滾動狀態

[英]How to maintain the scrolling state while orientation change in android

我創建了一個包含horizo​​ntalscrollview的自定義視圖。 現在,當我更改方向時,其滾動狀態每次都會更改為0。

我通過使用onSaveInstanceState(Bundle savedInstanceState)onRestoreInstanceState(Bundle savedInstanceState)獲得了上一個滾動狀態。 onRestoreInstanceState我正在使用以下方法來重新定位滾動,

hoz_scroll.scrollTo(hoz_x_pos, hoz_scroll.getScrollY());

但是根本沒有效果。 幫助表示贊賞。 謝謝。

如果必須在每次更改方向時調用onCreate,則將重置位置。 您可以通過添加更改為清單的方向來避免它,但是不確定當前滾動狀態是否完整。 我已經研究了幾天,如果您的界面在每個方向上都有穩定的尺寸,那么您可能會通過采樣許多滾動值來找到一個方程式。

使用getScrollY()創建一個地圖,該地圖的landscape和portait值顯示相同的文本。 值越多越好。 然后使用多項式插值法通過matlab或papper創建多項式方程式。 更多值->更准確http://en.wikipedia.org/wiki/Polynomial_interpolation

還必須像這樣滾動到某個位置

hoz_scroll.post(new Runnable() {

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

我相信你需要設定

android:configChanges="orientation"

AndroidManifest.xml中您活動的元素中。

然后,您需要在活動中覆蓋public void onConfigurationChanged(Configuration config)

這是一個可行的解決方案:

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());
}

將此代碼放在“活動”中,以便在方向更改時不會滾動。 您甚至不需要編寫代碼。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM