1
  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) {
            }
        }
    }

I created a recursive function to access child items of view group, but the parentLayout.getChildAt(i); returns a View, which contains children too, so I need to access that, but after casting I get the error java.lang.ClassCastException: android.support.v7.widget.AppCompatImageView cannot be cast to android.view.ViewGroup

MrRobot9
  • 2,402
  • 4
  • 31
  • 68

2 Answers2

2

You need to check if it is a ViewGroup before casting to 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
}
Andrew G
  • 2,596
  • 2
  • 19
  • 26
2

ViewGroup is a sub class of View. So if the object you have is an instance of ViewGroup, then yes you certainly can.

You should check if the view is an instanceof ViewGroup before you do your casting to ensure no exceptions are thrown.

ucsunil
  • 7,378
  • 1
  • 27
  • 32