检查布局是否包含任何ImageView或TextView android

时间:2016-01-06 16:05:02

标签: android android-layout

您好我想知道有没有办法检查父母布局的孩子?

有无ID?

3 个答案:

答案 0 :(得分: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);

答案 1 :(得分:1)

如果您的视图有父级,则可以通过在父视图上调用getIdentifier()来获取您孩子的ID。如果你没有,你可以通过以下方式获得它的身份证明

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

之后如果getIdentifire()返回0,则表示布局不存在。

答案 2 :(得分: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());
            }
        }