2016-01-06 34 views

回答

2

如果您有要在其中循環訪問的父視圖的子實例,則可以按照此實現進行操作。

您可以通過View類型,ID或標籤進行搜索。

//layout being the child of the view you have 
View parent = layout.getParent(); 
for (int i = 0; i < parent.getChildCount(); i++) { 
    View v = parent.getChildAt(i); 

    //view type 
    if (v instanceof ImageView) { 
     //whatever 
    } else if (v instanceof TextView) { 
     //whatever 
    } // 

    //by tag 
    if (v.getTag() instanceof yourObject) {//or == yourObject 
     //whatever 
    } else if (v.getTag() instanceof yourOtherObject) {//or == yourOtherObject 
     //whatever 
    } 

    //by id 
    if (v.getId().equals(searchingForView.getId())) { 
     //whatever 
    } else if (v.getId().equals(searchingForOtherView.getId())) { 
     //whatever 
    } 


} 

但是,如果你知道ID,你能明顯做

View parent = layout.getParent(); 
View lookingForThisView = parent.findViewById(R.id.lookingforthisviewid); 
+0

工作:)謝謝 –

+0

@KeepCalm很高興我可以幫助,如果它確實幫助你,標記爲答案! – ElliotM

1

如果你有一個家長對你的看法,你可以通過你的父視圖調用getIdentifier()讓您的孩子的ID。如果你沒有,你可以得到它的ID爲:

getContext().getResources().getIdentifier("yourLayoutID","layout", getContext().getPackageName()); 

後,你如果getIdentifire()返回0你的佈局不存在。

1
View parent = layout.getParent();  
    for(int i=0;i<parent.getChildCount();i++){ 
      View currentChild = parent.getChildAt(i); 
      if(currentChild.getClass() == TextView.class) { 
       Log.d("View Type", "TextView"); 
       Log.d("View Type", "TextView id:" + currentChild.getId()); 
      } 

      if(currentChild.getClass() == ImageView.class) { 
       Log.d("View Type", "ImageView"); 
       Log.d("View Type", "ImageView id:" + currentChild.getId()); 
      } 
     } 
相關問題