Updated 30 September 2017
In this blog we will set focus or display a particular view in the scroll view. many scenario has to display a particular view in scroll view such as we want to display the error on the particular view when any form submition.
A view group that allows the view hierarchy placed within it to be scrolled. Scroll view may have only one direct child placed within it. To add multiple views within the scroll view, make the direct child we add a view group.
How we will do?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
public static void scrollToView(final View scrollView, final View view) { view.requestFocus(); final Rect scrollBounds = new Rect(); scrollView.getHitRect(scrollBounds); if (!view.getLocalVisibleRect(scrollBounds)) { new Handler().post(new Runnable() { @Override public void run() { int toScroll = getRelativeTop(view) - getRelativeTop(scrollView); ((ScrollView) scrollView).smoothScrollTo(0, toScroll-120); } }); } } public static int getRelativeTop(View myView) { if (myView.getParent() == myView.getRootView()) return myView.getTop(); else return myView.getTop() + getRelativeTop((View) myView.getParent()); } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
public boolean isFormValidated(Profiles profileData, boolean shippingAddressVisible, boolean guestCheckout) { if (guestCheckout && profileData.getBEmailError() != null && !profileData.getBEmailError().isEmpty()) { mBinding.billingAddressForm.addBookEmailTitlelayout.setFocusable(true); mBinding.billingAddressForm.addBookEmailTitlelayout.requestFocus(); Helper.scrollToView(mBinding.scrollView, mBinding.billingAddressForm.addBookEmailTitlelayout ); return false; } if (profileData.getBFirstname().isEmpty()) { mBinding.billingAddressForm.addBookfirstnamelayout.setFocusable(true); mBinding.billingAddressForm.addBookfirstnamelayout.requestFocus(); Helper.scrollToView(mBinding.scrollView, mBinding.billingAddressForm.addBookfirstnamelayout ); return false; }else if (profileData.getBLastname().isEmpty()) { mBinding.billingAddressForm.addBooklastnamelayout.setFocusable(true); mBinding.billingAddressForm.addBooklastnamelayout.requestFocus(); Helper.scrollToView(mBinding.scrollView, mBinding.billingAddressForm.addBooklastnamelayout ); return false; } else if (profileData.getBAddress().isEmpty()) { mBinding.billingAddressForm.addBookStreetAddlayout.setFocusable(true); mBinding.billingAddressForm.addBookStreetAddlayout.requestFocus(); Helper.scrollToView(mBinding.scrollView, mBinding.billingAddressForm.addBookStreetAddlayout ); return false; } // ------------------add your more code ------------------------------ } |
How it look ?
References: – https://developer.android.com/reference/android/widget/ScrollView.html
If you have more details or questions, you can reply to the received confirmation email.
Back to Home
Be the first to comment.