2017-07-02 93 views
0

對於下面發佈的佈局,我試圖遍歷整個佈局並顯示佈局中每個視圖的ID。 我試過貼在下面的代碼與方法如何獲取視圖的唯一ID

vg.getId() 

,但它顯示的每個視圖相同的ID在佈局

請你告訴我怎麼去每個視圖的唯一ID佈局

輸出

ew_1 I/ActMain: vg.getId() :2131427422 
07-02 14:48:25.383 32647-32647/com.example.alteenos.test_traversethroughaview_1 I/ActMain: vg.getId() :2131427422 
07-02 14:48:25.383 32647-32647/com.example.alteenos.test_traversethroughaview_1 I/ActMain: vg.getId() :2131427422 
07-02 14:48:25.383 32647-32647/com.example.alteenos.test_traversethroughaview_1 I/ActMain: vg.getId() :2131427422 

辣油牛逼

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
android:id="@+id/actMain_mainContainer" 
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" 
android:orientation="vertical" 
tools:context="com.example.altenos.test_traversethroughaview_1.ActMain"> 

    <Button 
     android:id="@+id/actMain_btn_change" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:text="@string/decision_postponed" /> 

     <LinearLayout 
      android:id="@+id/actMain_linlay_1" 
      android:layout_width="match_parent" 
      android:layout_height="wrap_content" 
      android:orientation="horizontal"> 
      <Button 
       android:id="@+id/actMain_btn_yes" 
       android:layout_width="wrap_content" 
       android:layout_height="wrap_content" 
       android:text="@string/decision_accepted" /> 
      <Button 
       android:id="@+id/actMain_btn_no" 
       android:layout_width="wrap_content" 
       android:layout_height="wrap_content" 
       android:text="@string/decision_rejected" /> 
     </LinearLayout> 

     <TextView 
      android:id="@+id/actMain_tv_display" 
      android:layout_width="match_parent" 
      android:layout_height="wrap_content" /> 

     <LinearLayout 
      android:id="@+id/actMain_linlay_2" 
      android:layout_width="match_parent" 
      android:layout_height="wrap_content" 
      android:orientation="horizontal"> 
     </LinearLayout> 

代碼

private int countViews(ViewGroup vg) { 
    int childCount = vg.getChildCount(); 
    for (int i = 0; i < childCount; i++) { 
     Log.i(TAG, "vg.getId() :" + vg.getId()); 

     //if (vg.getChildAt(i) instanceof ViewGroup) { 
      //childCount += countViews((ViewGroup) vg.getChildAt(i)); 
     //} 
    } 
    return childCount; 
} 

回答

1

應登錄在未查看的ViewGroup

private int countViews(ViewGroup vg) { 
    int childCount = vg.getChildCount(); 
    for (int i = 0; i < childCount; i++) { 
     Log.i(TAG,"vg.getId() :",vg.getChildAt(i).getId()); 
     //Log.i(TAG, "vg.getId() :" + vg.getId()); Not this one 

     //if (vg.getChildAt(i) instanceof ViewGroup) { 
      //childCount += countViews((ViewGroup) vg.getChildAt(i)); 
     //} 
    } 
    return childCount; 
}