2016-09-15 88 views
0
private void scaleAllViews(ViewGroup parentLayout) { 

     int count = parentLayout.getChildCount(); 
     Log.d(TAG, "scaleAllViews: "+count); 
     View v = null; 
     for (int i = 0; i < count; i++) { 
      try { 
       v = parentLayout.getChildAt(i); 

       if(((ViewGroup)v).getChildCount()>0){ 
        scaleAllViews((ViewGroup)v); 
       }else{ 
        if (v != null) { 
         v.setScaleY(0.9f); 
        } 
       } 

      } catch (NullPointerException e) { 
      } 
     } 
    } 

我创建了一个递归函数来访问视图组的子项,但parentLayout.getChildAt(i);返回View,其中包含孩子太多,所以我需要访问,但铸造后我得到的错误java.lang.ClassCastException: android.support.v7.widget.AppCompatImageView cannot be cast to android.view.ViewGroup是否可以将View转换为ViewGroup?

回答

2

你在投射到ViewGroup之前需要检查它是否为ViewGroup

if(v instanceof ViewGroup) { 
    // now this is a safe cast 
    ViewGroup vg = (ViewGroup) vg; 
    // ... use this ViewGroup 
} else { 
    // It's some other type of View 
} 
2

ViewGroup是View的子类。所以如果你拥有的对象是ViewGroup的一个实例,那么你肯定可以。

在执行转换之前,您应该检查视图是否为instanceof ViewGroup,以确保不引发异常。

相关问题