我想检查
View
中的 ScrollView
当前在 Android 中是否可见。我还没有检查它是否被聚焦,但它当前是否正在屏幕上显示。 View
中是否有方法可以告诉我视图当前是否可见?
这段代码对我有用:
public static boolean isVisible(final View view) {
if (view == null) {
return false;
}
if (!view.isShown()) {
return false;
}
final Rect actualPosition = new Rect();
view.getGlobalVisibleRect(actualPosition);
final Rect screen = new Rect(0, 0, getScreenWidth(), getScreenHeight());
return actualPosition.intersect(screen);
}
int[] location = new int[2];
view.getLocationOnScreen(location);
或
Rect rect = new Rect();
view.getGlobalVisibleRect(rect);
现在使用这个位置或矩形来检查它是否在你的可见范围内。如果它只是整个屏幕,请检查
getResources().getDisplayMetrics()
.
正如 Antek 在下面的评论中所指出的,视图可能仍然消失或不可见,这里的返回值告诉它最后一次绘制的位置。因此,将上述与边界相关的条件与
view.isShown()
或 view.getVisibility() == VISIBLE
结合起来应该可以解决这个问题。
zegee29 的 回答很有帮助。虽然我也想建议使用
view.getGlobalVisibleRect(actualPosition)
的结果,因为在某些情况下 Rect.intersects()
返回 true
当项目根本不可见时,所以结果代码是:
fun View.isVisible(): Boolean {
if (!isShown) {
return false
}
val actualPosition = Rect()
val isGlobalVisible = getGlobalVisibleRect(actualPosition)
val screenWidth = Resources.getSystem().displayMetrics.widthPixels
val screenHeight = Resources.getSystem().displayMetrics.heightPixels
val screen = Rect(0, 0, screenWidth, screenHeight)
return isGlobalVisible && Rect.intersects(actualPosition, screen)
}
或者你可能只是
getGlobalVisibleRect(actualPosition)
的结果
Диана Γаниева的Java变体 发布https://stackoverflow.com/a/66907184/2323972
boolean isViewOnScreen(View target)
{
if (!target.isShown())
{
return false;
}
final var actualPosition = new Rect();
final var isGlobalVisible = target.getGlobalVisibleRect(actualPosition);
final var screenWidth = Resources.getSystem().getDisplayMetrics().widthPixels;
final var screenHeight = Resources.getSystem().getDisplayMetrics().heightPixels;
final var screen = new Rect(0, 0, screenWidth, screenHeight);
return isGlobalVisible && Rect.intersects(actualPosition, screen);
}
尝试
if(view.isShown()) {
// Visible
} else {
// Invisible
}
public boolean checkVisiblity(查看视图){
if(view.isShown()) 返回真; 别的 返回假;
}
函数 View.getVisibility() 可以有以下值:
View.VISIBLE(0):视图可见。
View.INVISIBLE(1):视图是不可见的,但它仍然占用布局空间。
View.GONE (2):视图消失了。完全隐藏,就好像没加view一样
您可以查看以下链接以获取更多信息。 如何检查视图在 Android 中是否可见?