代码之家  ›  专栏  ›  技术社区  ›  lacas

Android获取视图类型

  •  50
  • lacas  · 技术社区  · 14 年前

    我该怎么做?

    final View view=FLall.getChildAt(i);
    
    if (view.getType()==ImageView) {
    ...
    }
    
    4 回复  |  直到 14 年前
        1
  •  139
  •   Felix    14 年前

    如果,由于某种奇怪的原因,你不能使用 朝日啤酒

    if (view instanceof ImageView) {
        ImageView imageView = (ImageView) view;
        // do what you want with imageView
    }
    else if (view instanceof TextView) {
        TextView textView = (TextView) view;
        // do what you want with textView
    }
    else if ...
    
        2
  •  18
  •   Community CDub    9 年前

    我尝试了以下方法,结果成功了:

    View view=FLall.getChildAt(i);
    Log.i("ViewName", view.getClass().getName());
    
        3
  •  8
  •   Arash    11 年前

    对于其他检查这个问题的人,在某些情况下 instanceof 不工作(我不知道为什么!),例如,如果要检查视图类型是否为 ImageView ImageButton (我测试了这种情况),得到的结果是一样的,所以你可以这样扫描:

    //v is your View
        if (v.getClass().getName().equalsIgnoreCase("android.widget.ImageView")) {
            Log.e("imgview", v.toString());
            imgview = (ImageView) v;
        } else if (v.getClass().getName().equalsIgnoreCase("android.widget.ImageButton")) {
            Log.e("imgbtn", v.toString());
            imgbtn = (ImageButton) v; 
        }