Android - Horizo​​ntalScrollView - 获取焦点视图(或其索引)

Sch*_*pfe 4 android android-layout android-scrollview android-scroll

我有一个HorizontalScrollView包含a LinearLayout,其中包含几个FrameLayouts.每个都FrameLayout包含一个的布局Fragment.现在我正在尝试获取视图,即FrameLayout当前可见或焦点在视图内HorizontalScrollView.只要我有焦点的视图,我就可以得到它的索引LinearLayout.

我尝试了以下,但没有任何作用:

  • Horizo​​ntalScrollView.findFocus() - 返回null
  • LinearLayout.findFocus() - 返回null
  • LinearLayout.getFocusedChild() - 返回null
  • FrameLayout.hasFocus() - 为所有FrameLayouts 返回false

我还可以LinearLayout通过根据每个孩子的当前X位置进行计算来确定哪个孩子有焦点.但是,呼叫getX()每个孩子总是返回"0.0".

有没有人知道如何获得焦点的视图(甚至更好的是它的索引LinearLayout)?

Sch*_*pfe 6

使用这个问题的答案:android-how-to-check-if-a-view-inside-of-scrollview-is-visible我提出了以下解决方案:

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;
    }
}
Run Code Online (Sandbox Code Playgroud)