thank you
thank you

Reputation: 113

How to go from bottom of the page to the top of the page?

I create an form with 15 editText inside NestedScrollView. Suppose second editText is empty. So after clicking Submit button, I want that page directly goes to the 2nd editText from Submit button to show error. But I don't know how to go from Submit button to second editText directly. Can you help me ? Thank you.

Upvotes: 0

Views: 171

Answers (2)

Dev Sebastian
Dev Sebastian

Reputation: 677

A simple approach I generally use is this:

submitBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // sets focus on the editText such that the ScrollView automatically scrolls to the EditText
                editText.requestFocus();        
                // displays the error message on the EditText
                editText.setError("error message" ); 
            }
        });

Upvotes: 1

Lalit Fauzdar
Lalit Fauzdar

Reputation: 6361

For that, you can use scrollTo() or smoothScrollTo() as mentioned here

  1. To make it simpler, create a function as below:

    //Used to smooth scroll the scrollbar to focused view.
    //@param view : parameter view is any view you want to scroll to
    //view.bottom indicates that you want to scroll to the bottom of the view, 
    //you can change it to view.top
    private fun smoothScrollToThis(view: View) {
        scrollView.post { scrollView.smoothScrollTo(0, view.bottom) }
        /* view.post{} here is a runnable function and uses a separate thread to perform
       the operation so the UI doesn't freeze.*/
    }
    

    This will scroll the ScrollBar to the view. Difference between scrollTo and smoothScrollTo is that scrollTo scrolls instantly skipping the in-between part and smoothScrollTo works like an actual scroll by a user showing all the widgets in between while scrolling. For a long layout of ScrollView, you should prefer scrollTo as it's fast.

  2. Now, call the function from wherever you want as:

    smoothScrollToThis(yourEditText) //You can pass any view
    

Upvotes: 1

Related Questions