是否可以将 View 投射到 ViewGroup?
Is it possible to cast View to ViewGroup?
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);
returns 一个 View
,它也包含子项,所以我需要访问它,但是铸造后我得到错误 java.lang.ClassCastException: android.support.v7.widget.AppCompatImageView cannot be cast to android.view.ViewGroup
在转换为 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
}
ViewGroup 是 View 的子 class。因此,如果您拥有的对象是 ViewGroup 的实例,那么是的,您当然可以。
您应该在进行转换之前检查视图是否是 ViewGroup 的实例,以确保不会抛出异常。
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);
returns 一个 View
,它也包含子项,所以我需要访问它,但是铸造后我得到错误 java.lang.ClassCastException: android.support.v7.widget.AppCompatImageView cannot be cast to android.view.ViewGroup
在转换为 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
}
ViewGroup 是 View 的子 class。因此,如果您拥有的对象是 ViewGroup 的实例,那么是的,您当然可以。
您应该在进行转换之前检查视图是否是 ViewGroup 的实例,以确保不会抛出异常。