Question

I have a HorizontalScrollView containing a LinearLayout, which in turn contains a couple of FrameLayouts. Each FrameLayout contains the layout of a Fragment. Now I'm trying to get the view, i.e. FrameLayout, which is currently visible or in focus within the HorizontalScrollView. As soon as I have the view in focus I could get it's index within the LinearLayout.

I've tried the following, but nothing works:

  • HorizontalScrollView.findFocus() - returns null
  • LinearLayout.findFocus() - returns null
  • LinearLayout.getFocusedChild() - returns null
  • FrameLayout.hasFocus() - returns false for all FrameLayouts

I could also try to figure out which child of the LinearLayout has focus, by doing calculations based on current X-position of each child. However, calling getX() on each child always returns "0.0".

Does anyone have an idea how to get the view in focus (or even better it's index within the LinearLayout)?

Was it helpful?

Solution

Using the answer to this question: android-how-to-check-if-a-view-inside-of-scrollview-is-visible I came up with the following solution:

Rect scrollBounds = new Rect();
MyHorizontalScrollView.getDrawingRect(scrollBounds);
Rect childBounds = new Rect();      
for (int i = 0; i < MyLinearLayout.getChildCount(); i++) {
    MyLinearLayout.getChildAt(i).getHitRect(childBounds);
    if(scrollBounds.contains(childBounds)) {
        IndexOfVisibleChild = i;
        return;
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top