source code:
if(view != null && view.getParent() != null) {
((ViewGroup)view.getParent()).removeView(view);
}
如你所见,view和view.getParent()不能为null调用removeView, 但这是我们得到的例外:
java.lang.NullPointerException
at android.view.ViewGroup.removeFromArray(ViewGroup.java:3528)
at android.view.ViewGroup.removeViewInternal(ViewGroup.java:3726)
at android.view.ViewGroup.removeViewInternal(ViewGroup.java:3690)
at android.view.ViewGroup.removeView(ViewGroup.java:3622)
at xxxx.removeView(yyyy.java:zzzz) // here's code above
private void removeFromArray(int index) {
final View[] children = mChildren;
if (!(mTransitioningViews != null && mTransitioningViews.contains(children[index]))) {
children[index].mParent = null; // !!!! ViewGroup.java:3528
}
index对应一个子视图,所以子[index]应该是我们代码中的“view”,而mParent应该是“view.getParent()”,那么为什么这里抛出一个NullPointerException?
if(view != null && view.getParent() != null) {
((ViewGroup)view.getParent()).removeView(view);
}
public void removeView(View view) {
removeViewInternal(view);
}
private void removeViewInternal(View view) {
final int index = indexOfChild(view);
if (index >= 0) {
removeViewInternal(index, view);
}
}
public int indexOfChild(View child) {
final int count = mChildrenCount;
final View[] children = mChildren;
for (int i = 0; i < count; i++) {
if (children[i] == child) {
return i;
}
}
return -1;
}
private void removeViewInternal(int index, View view) {
......
removeFromArray(index);
}
private void removeFromArray(int index) {
final View[] children = mChildren;
if (!(mTransitioningViews != null && mTransitioningViews.contains(children[index]))) {
children[index].mParent = null; // !!!! ViewGroup.java:3528
}
答案 0 :(得分:0)
您没有对View []子项进行空检查。在Array of Object类型中,默认情况下,每个索引位置都使用空值初始化。
View[] children = new View[10]; //Here Array is not null. but all elements inside it are null
for(int i=0;i<children.length;i++){
System.out.println(children[i] == null); //certainly true
}
//proper initialization
for(int i=0;i<children.length;i++){
children[i] = new View();
}