Reputation: 113
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
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
Reputation: 6361
For that, you can use scrollTo()
or smoothScrollTo()
as mentioned here
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.
Now, call the function from wherever you want as:
smoothScrollToThis(yourEditText) //You can pass any view
Upvotes: 1