public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ViewGroup decorView = (ViewGroup) getWindow().getDecorView();
final FrameLayout frameLayout = decorView.findViewById(android.R.id.content);
View main = frameLayout.getChildAt(0);
View main1 = findViewById(R.id.main_layout);
int[] maxDepth = {0};
dfs(decorView, 1, maxDepth);
Log.d("gzl", "" + maxDepth[0]);
}
private void dfs(View root, int level, int[] maxDepth) {
maxDepth[0] = Math.max(level, maxDepth[0]);
if (root instanceof ViewGroup) {
ViewGroup viewGroup = (ViewGroup) root;
for (int i = 0; i < viewGroup.getChildCount(); i++) {
View child = viewGroup.getChildAt(i);
dfs(child, level + 1, maxDepth);
}
}
}
}
レイアウト/ activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
android:id="@+id/main_layout"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.gongzelong.decorviewdepthdemo.MainActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"/>
</FrameLayout>
</LinearLayout>
</android.support.constraint.ConstraintLayout>