2017-07-02 70 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; 
}