38

I have a GridView within a NestedScrollView. I have used the code below to resize the GridView whenever the content of the GridView is changed. This works fine, however the NestedScrollView scrolls to the very bottom when I swipe from fragment 3 of the app back to fragment 2 (where the NestedScrollView resides). This doesn't happen when swiping from fragment 1 to fragment 2, oddly. It also doesn't happen directly after resizing the GridView.

How can I repress the NestedScrollView from scrolling to the bottom?

private static void resizeGridView(GridView gridView, int items, int columns) {
    ViewGroup.LayoutParams params = gridView.getLayoutParams();
    params.height = singleGridHeight * items;
    gridView.setLayoutParams(params);
    gridView.requestLayout();
}

The following system methods are called when swiping between fragments: enter image description here

Luke Allison
  • 2,644
  • 3
  • 18
  • 36

2 Answers2

182

Add android:descendantFocusability="blocksDescendants" to the child layout in NestedScrollView

Joseph Paddy
  • 1,835
  • 1
  • 12
  • 8
  • 9
    Are you kidding me? This actually worked! Thank you so much. – Luke Allison Nov 15 '16 at 06:06
  • 3
    Unbelievable, this trick ended up solving *many* little UI glitches that we've been experiencing for quite some time now. We have many levels deep of nested recycler/scroll views in all sorts of screens, and this 1 line finally helped us understand the problem. – Matthew Housser Feb 17 '17 at 18:52
  • 1
    Hero! I've been searching for that solution for such a long time! Unbeliavable that it is THAT easy! Thank you! – romaneso May 21 '17 at 10:40
  • Awesome! Works also with simple ScrollViews – Bronx Oct 22 '18 at 11:07
  • Wow this saved me literally 2 days... I have wasted a day already. Thanks a bunch! – mpellegr Dec 12 '18 at 16:46
  • This works. Thumbs up for future reference. May the force be with y'all. Mamba out – ralphgabb Dec 19 '18 at 06:03
  • 1
    EditText's after this not focusable – Peter Mar 20 '19 at 15:45
  • Worked like a charm !!!, just added one thing is, after adding the above solution, EditText will not get focused then on EditText touch listener just add yourChildView.setDescendantFocusability(ViewGroup.FOCUS_AFTER_DESCENDANTS); . Your EditText will get focus. – Shailesh Feb 22 '21 at 12:32
1

If I add nestedScrollView.scrollTo(0, 0); to the end of the onLayoutChanged() method of the GridView the issue is resolved. However, it would make more sense to prevent the nestedScrollView from automatically scrolling in the first place.

Ideas?

Luke Allison
  • 2,644
  • 3
  • 18
  • 36