2017-08-02 66 views
0

我知道我們可以在View Hierachy中看到它,但是如何在代碼中獲得它?如何使用java代碼知道android活動中DecorView的深度?

視圖的佈局過程中,我可以看到下面的代碼: 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
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> 
相關問題