2016-09-15 89 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,以確保不引發異常。

相關問題