Scroll layout when keyboard show up without focus changing in Android


This is tricky situation when user see softkeyboard show-up, but the are couple of edittext or button hiding behind it.
To tackle this, we can add focus listener and make scrollview scroll to bottom without focus changing.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
    /**
     * Scroll to bottom without focus changing
     * @param scrollView
     */
    public static void scrollToBottom(ScrollView scrollView) {

        scrollView.postDelayed(new Runnable() {
            @Override
            public void run() {

                View lastChild = scrollView.getChildAt(scrollView.getChildCount() – 1);
                int bottom = lastChild.getBottom() + scrollView.getPaddingBottom();
                int sy = scrollView.getScrollY();
                int sh = scrollView.getHeight();
                int delta = bottom – (sy + sh);

                scrollView.smoothScrollBy(0, delta);
            }
        }, 2000);
    }

And the implementation :

1
2
3
4
5
6
7
8
9
10
11
12
        mEditText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {

                // When keyboard appear, we will scroll to bottom
                // to enable user see the submit button
                if(hasFocus && !showBottomScrollview) {
                    showBottomScrollview = true;
                    UtilityClass.scrollToBottom(scrollView);
                }
            }
        });

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.