2016-01-06 61 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()); 
      } 
     } 
相关问题