我知道我们可以通过视觉在View Hierachy中看到它,但是如何在代码中获取它?
在视图布局过程中,我可以看到以下代码:
LayoutInflater.java
http://androidxref.com/6.0.1_r10/xref/frameworks/base/core/java/android/view/LayoutInflater.java
// Gets the current parser pointer where the node is at the layout level
final int depth = parser.getDepth();
我也在github上发布了中文版https://github.com/JackyAndroid/AndroidInterview-Q-A/issues/22
答案 0 :(得分:0)
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>