I have a use case where one view is on top of another. Is there anyway to programmatically get all views that are behind the view on top? I would like to know if I can get list of views that are overlapped by the current view
CodePudding user response:
I think you should use FrameLayout
then views will cover each other by order of define after another.
but there is another way to do that is android:translationZ
to translate by z-order.
you can alos use view.bringToFront();
but it can only bring the view to the top of all views and you can not manage z index orders.
CodePudding user response:
In order to get the list of all occluding views with same parent, we check intersection and visibility of all views on top of the current view:
public static ArrayList<View> getOccludingViewsOf(View view){
ArrayList<View> occludingList=new ArrayList<>();
ViewGroup parent=((ViewGroup)view.getParent());
int viewIndex=parent.indexOfChild(view);
int viewSiblingCount=parent.getChildCount();
Rect currentBound=getBoundary(view);
for (int i=viewIndex 1;i<viewSiblingCount;i ){
View view_i= parent.getChildAt(i);
if (view_i.getVisibility()==VISIBLE && currentBound.intersect(getBoundary(view_i))){
occludingList.add(view_i);
}
}
return occludingList;
}
To get the boundary of each view:
public static Rect getBoundary(View view){
int[] pos = new int[2];
view.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
view.getLocationOnScreen(pos);
return new Rect(pos[0], pos[1],
pos[0] view.getMeasuredWidth(), pos[1] view.getMeasuredHeight());
}
To check occlusion with views that have other roots (different parent), include them too (of course if their root are on top of the root of the current view).
Also if custom draw ordering of the parent is enable, instead of view index, we should check the drawing orders of views.
Changing Orders Of View
If you want the view to be the last child on it's parent, Use:
view.bringToFront();
Also, to change the order of view, first remove it from parent and then add it by your desire index:
parentView.removeView(view);
parentView.addView(view,index);