Scroll to a specific view in scroll view

前端 未结 15 1461
醉梦人生
醉梦人生 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:52

    Here's a solution that works if the target view is not a direct child of your ScrollView:

    public int findYPositionInView (View rootView, View targetView)
    {
      return findYPositionInView (rootView, targetView, 0);
    }
    
    
    // returns -1 if targetView not found
    private int findYPositionInView (View rootView, View targetView, int yCumulative)
    {
      if (rootView == targetView)
        return yCumulative;
    
      if (rootView instanceof ViewGroup)
      {
        ViewGroup parentView = (ViewGroup)rootView;
        for (int i = 0;  i < parentView.getChildCount ();  i++)
        {
          View child = parentView.getChildAt (i);
          int yChild = yCumulative + (int)child.getY ();
    
          int yNested = findYPositionInView (child, targetView, yChild);
          if (yNested != -1)
            return yNested;
        }
      }
    
      return -1; // not found
    }
    

    Use it like this:

    int yScroll = findYPositionInView (scrollView, targetView);
    scrollView.scrollTo (0, yScroll);
    

    Further, if you wish to set focus, do this:

    targetView.requestFocus ();
    

    And, if you want the keyboard to show, do this:

    if (targetView instanceof EditText)
    {
      targetView.post (new Runnable ()
      {
        @Override public void run ()
        {
          InputMethodManager imm = (InputMethodManager)context.getSystemService (Context.INPUT_METHOD_SERVICE);
          imm.showSoftInput (targetView, InputMethodManager.SHOW_FORCED);
        }
      });
    }
    

提交回复
热议问题