Best Way: Save & Restore TextView Position in ScrollView

前端 未结 1 1833
庸人自扰
庸人自扰 2020-12-28 18:33

What i want is, upon the device changes orientation, the top line on the screen when in Portrait remains the top line on screen in Landscape. And vice versa.

As the

1条回答
  •  一生所求
    2020-12-28 19:30

    I am so proud to say, I got a perfect solution to this now.

    Sh.... (sorry I am too excited about it. If you find any mistakes/bugs/weakness on it, please DO give me your valuable suggestions and please feel free to correct me. :-)

    Cut the crap. Here you go !!!

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        final ScrollView scrollView = (ScrollView) findViewById(R.id.Trial_C_ScrollViewContainer);
        final TextView textView = (TextView) scrollView.getChildAt(0);
        final int firstVisableLineOffset = textView.getLayout().getLineForVertical(scrollView.getScrollY());
        final int firstVisableCharacterOffset = textView.getLayout().getLineStart(firstVisableLineOffset);
        outState.putInt(ScrollViewContainerTextViewFirstVisibleCharacterOffset, firstVisableCharacterOffset);
    }
    
    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        final int firstVisableCharacterOffset = savedInstanceState.getInt(ScrollViewContainerTextViewFirstVisibleCharacterOffset);
    
        final ScrollView scrollView = (ScrollView) findViewById(R.id.Trial_C_ScrollViewContainer);
        scrollView.post(new Runnable() {
            public void run() {
                final TextView textView = (TextView) scrollView.getChildAt(0);
                final int firstVisableLineOffset = textView.getLayout().getLineForOffset(firstVisableCharacterOffset);
                final int pixelOffset = textView.getLayout().getLineTop(firstVisableLineOffset);
                scrollView.scrollTo(0, pixelOffset);
            }
        });
    }
    

    That's it. :-)

    If it helps you, please clap your hands. <-- this is important!!

    And if you wish to, click that little upright triangle. (make sure you have clapped your hands first!)

    0 讨论(0)
提交回复
热议问题