一次面試過(guò)程中扇住,面試官提出了這么一個(gè)問(wèn)題:怎么獲取Activity視圖層級(jí)的最大深度盈厘,要求手寫(xiě)代碼睁枕。當(dāng)時(shí)立馬有了思路,但是代碼寫(xiě)的并不完整沸手。這個(gè)問(wèn)題的實(shí)現(xiàn)思路很簡(jiǎn)單外遇,首先獲取Window,然后拿到DecorView向下進(jìn)行遞歸遍歷契吉。
代碼如下:
public static int getViewHierarchyMaxDeep(Activity activity) {
View decorView = activity.getWindow().getDecorView();
int height = getDeep(decorView, 1);
Log.e("TAG", activity.getClass().getSimpleName() + " height is:" + height);
return height;
}
// curr為當(dāng)前View的層級(jí)
private static int getDeep(View view, int curr) {
if (view instanceof ViewGroup) {
ViewGroup parent = (ViewGroup) view;
int childCount = parent.getChildCount();
if (childCount > 0) {
// 層級(jí)+1
int max = curr + 1;
for (int i = 0; i < childCount; i++) {
View child = parent.getChildAt(i);
int height = getDeep(child, curr + 1);
if (max < height) {
max = height;
}
}
return max;
} else {
return curr;
}
} else {
return curr;
}
}