GMs*_*soF 3 android android-layout
我一直在从这里搜索很多类似的答案,但没有一个可以准确地工作。我想计算自定义视图的可见区域,该视图可以被屏幕边缘遮挡,也可以被滚动视图的边缘遮挡,请看下图:
如上所述,黑色是我的屏幕,红色是我的自定义视图,向上滚动一点,我想测量 B 的面积。
如上所述,黑色是我的屏幕,红色是我的自定义视图,蓝色是滚动视图。自定义视图是滚动视图的子视图,它向上滚动一点。我想测量B的面积。
1 )我已经尝试过View.getWindowVisibleDisplayFrame,,,,,但没有一个能准确工作。乍一看它们看起来不错,但是当我滚动视图时,视图从屏幕上消失,不知何故,它向我显示了视图的完整高度和宽度,该视图甚至没有显示在屏幕内。View.getLocalVisibleRectView.getGlobalVisibleRect
2)我尝试View.getLocationOnScreen()手动getLocationInWindow()计算偏移量,获取XY坐标并加上/减去视图(和屏幕)的高度和宽度,但发现这也不容易,因为屏幕顶部总是有额外的菜单栏等,并且会弄乱结果。
3)虽然这在我的情况下不太可能,但我想知道,如果我的视图顶部有一个绝对布局并部分遮挡它,我仍然可以找到该区域吗?(两个布局都在同一个活动中)
我的问题是,有没有简单又准确的方法来计算我想要的面积?
好吧,我从一个开源广告框架中找到了答案:
/**
* Whether the view is at least certain % visible
*/
boolean isVisible(@Nullable final View rootView, @Nullable final View view, final int minPercentageViewed) {
// ListView & GridView both call detachFromParent() for views that can be recycled for
// new data. This is one of the rare instances where a view will have a null parent for
// an extended period of time and will not be the main window.
// view.getGlobalVisibleRect() doesn't check that case, so if the view has visibility
// of View.VISIBLE but it's group has no parent it is likely in the recycle bin of a
// ListView / GridView and not on screen.
if (view == null || view.getVisibility() != View.VISIBLE || rootView.getParent() == null) {
return false;
}
if (!view.getGlobalVisibleRect(mClipRect)) {
// Not visible
return false;
}
// % visible check - the cast is to avoid int overflow for large views.
final long visibleViewArea = (long) mClipRect.height() * mClipRect.width();
final long totalViewArea = (long) view.getHeight() * view.getWidth();
if (totalViewArea <= 0) {
return false;
}
return 100 * visibleViewArea >= minPercentageViewed * totalViewArea;
}
Run Code Online (Sandbox Code Playgroud)
我在使用时犯了一个错误View.getGlobalVisibleRect,当视图从屏幕上消失时,此方法将返回 false,尽管该mClipRect对象仍然提供值。以上就是正确的使用方法。
| 归档时间: |
|
| 查看次数: |
3062 次 |
| 最近记录: |