Android:无法销毁活动

and*_*one 10 android destroy android-activity

我使用以下代码删除每个视图组上的子项:

protected void onDestroy() {
    super.onDestroy();
    this.liberarMemoria();
}

public void liberarMemoria(){
     imagenes.recycleBitmaps(); 
     this.unbindDrawables(findViewById(R.id.RelativeLayout1));
     System.gc();
}
private void unbindDrawables(View view) {
    if (view.getBackground() != null) {
    view.getBackground().setCallback(null);
}
if (view instanceof ViewGroup) {
    for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++) {
        unbindDrawables(((ViewGroup) view).getChildAt(i));
    }
    ((ViewGroup) view).removeAllViews();
    }
}
Run Code Online (Sandbox Code Playgroud)

其中视图:R.id.RelativeLayout1是ListView.

但这样做我有例外:

E/AndroidRuntime(582): java.lang.RuntimeException: Unable to destroy activity {...}: java.lang.UnsupportedOperationException: removeAllViews() is not supported in AdapterView
Run Code Online (Sandbox Code Playgroud)

我怎么解决这个问题?

ina*_*ruk 11

那么,错误日志几乎解释了它:不要叫removeAllViews()AdapterView.并且您的代码在某些时候ViewGroup也符合AdapterView.

只需使用/ wrapper instanceof检查或处理异常来判断这种情况.trycatch


Der*_*rzu 7

验证ViewGroup是否不是AdapterView的实例.

做那样的事情:

if (!(view instanceof AdapterView<?>))
    ((ViewGroup) view).removeAllViews();
Run Code Online (Sandbox Code Playgroud)

所以,在你的代码上:

if (view instanceof ViewGroup) {
    for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++) {
        unbindDrawables(((ViewGroup) view).getChildAt(i));
    }
    if (!(view instanceof AdapterView<?>))
        ((ViewGroup) view).removeAllViews();
}
Run Code Online (Sandbox Code Playgroud)