As many of the developer face this problem to scroll the view to specific view to focus the child view of scroll view. Let’s see an example, we have huge form where user need to fill to submit. But in the big form if user is missing any filling field or view then it is very difficult for user to finds the field which are missing to fill. Now we need to scroll the view to this specific view and focus this view for the user, then it becomes easy for the user to understand to finding the missing information to filled.
<ScrollView android:id="@+id/scrollView2" android:layout_width="match_parent" android:layout_height="0dp" card_view:layout_constraintBottom_toBottomOf="parent" card_view:layout_constraintEnd_toEndOf="parent" card_view:layout_constraintStart_toStartOf="parent"> <LinearLayout android:id="@+id/detail_layout" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="#f1f6fb" android:orientation="vertical" tools:visibility="visible"> <com.google.android.material.textfield.TextInputLayout android:id="@+id/number_inputlayout"> <com.google.android.material.textfield.TextInputEditText android:id="@+id/number_edittext" android:layout_width="match_parent" android:layout_height="wrap_content" /> </com.google.android.material.textfield.TextInputLayout> .............. ............. </LinearLayout> </ScrollView>
Here is solution.
private fun scrollToView(scrollViewParent: ScrollView, view: View) { // Get deepChild Offset val childOffset = Point() getDeepChildOffset(scrollViewParent, view.parent, view, childOffset) // Scroll to child. scrollViewParent.smoothScrollTo(0, childOffset.y) } private fun getDeepChildOffset( mainParent: ViewGroup, parent: ViewParent, child: View, accumulatedOffset: Point ) { val parentGroup = parent as ViewGroup accumulatedOffset.x += child.left accumulatedOffset.y += child.top if (parentGroup == mainParent) { return } getDeepChildOffset(mainParent, parentGroup.parent, parentGroup, accumulatedOffset) }
That is. Now it becomes easy to user to identify the view which is missing to filled. Ref
Happy Coding.
I am a very enthusiastic Android developer to build solid Android apps. I have a keen interest in developing for Android and have published apps to the Google Play Store. I always open to learning new technologies. For any help drop us a line anytime at contact@mobologicplus.com