Scroll to a specific view in scroll view

前端 未结 15 1446
醉梦人生
醉梦人生 2020-12-04 14:08

I have added a scrollview and the subchilds inside the scrollview. At some point i need to scroll to a specific view.



1. 

        
15条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-04 14:44

    I think I have found more elegant and error prone solution using

    ScrollView.requestChildRectangleOnScreen

    No math involved, and contrary to other proposed solutions, it will handle correctly scrolling both ways up and down.

    void scrollToRow(ScrollView scrollView, LinearLayout linearLayout, TextView textViewToShow) {
        Rect textRect = new Rect(); //coordinates to scroll to
        textViewToShow.getHitRect(textRect); //fills textRect with coordinates of TextView relative to its parent (LinearLayout) 
        scrollView.requestChildRectangleOnScreen(linearLayout, textRect, false); //ScrollView will make sure, the given textRect is visible
    }
    

    It is a good idea to wrap it into postDelayed to make it more reliable, in case the ScrollView is being changed at the moment

    private void scrollToRow(final ScrollView scrollView, final LinearLayout linearLayout, final TextView textViewToShow) {
        long delay = 100; //delay to let finish with possible modifications to ScrollView
        scrollView.postDelayed(new Runnable() {
            public void run() {
                Rect textRect = new Rect(); //coordinates to scroll to
                textViewToShow.getHitRect(textRect); //fills textRect with coordinates of TextView relative to its parent (LinearLayout) 
                scrollView.requestChildRectangleOnScreen(linearLayout, textRect, false); //ScrollView will make sure, the given textRect is visible
            }
        }, delay);
    }
    

    Just nice isn`t?

提交回复
热议问题