android-discuss
android-discuss copied to clipboard
怎么判断一个view在屏幕中是否是可见的?
有这么一个view,他是Visible的,但是可能因为什么原因,它被别的view挡住了,或者在屏幕中我们看不到它了,怎么判断这个view它不可见了?
我看了listview的源码,其中获得firstvisibleitem的方法,是判断item的bottom,如果大于listview的bottom,则不可见在listview下面,如果小于listview的top,则不可见在listview上面。 所以我这样写:
try {
childView.getGlobalVisibleRect(startBounds);
} catch (Exception e) {
return false;
}
Rect parentBounds = new Rect();
try {
mParentView.getGlobalVisibleRect(parentBounds);
} catch (Exception e) {
return false;
}
if(startBounds.bottom > parentBounds.bottom || startBounds.bottom < parentBounds.top){
return false;
}
其中parentview是父控件,childview位于parentview中,parentview是我写的一个可以滑动的viewgroup,但我发现childview滑动后虽然在parentview的下方了,并且不可见,但它所返回的startBounds.bottom仍然小于parentbounds,不知道是哪里出了问题。
android系统源码中有现成的函数实现,具体作用是用来检测textview可见区域的。详细代码可以查看
Editor.java isPositionVisible()函数
Rect r = new Rect(); view.getWindowVisibleDisplayFrame(r); 可以获得可见部分
回复Hackforid
谢谢你的回答,但你可以试一下这个方法,一旦view被遮挡住这个方法仍然返回具体Rect,并且无论如何都会返回一个具体Rect,所以对我来说没有作用,一旦被遮住仍然无法判断可见部分。 看这个方法的源码
public void getWindowVisibleDisplayFrame(Rect outRect) {
if (mAttachInfo != null) {
try {
mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect);
} catch (RemoteException e) {
return;
}
final Rect insets = mAttachInfo.mVisibleInsets;
outRect.left += insets.left;
outRect.top += insets.top;
outRect.right -= insets.right;
outRect.bottom -= insets.bottom;
return;
}
Display d = DisplayManagerGlobal.getInstance().getRealDisplay(Display.DEFAULT_DISPLAY);
d.getRectSize(outRect);
}
如果view被attch,都会返回rect,那么被遮挡住,他仍然没被disattch,所以rect仍然会返回。
还有其他方案么