In order to avoid memory leaks I want to remove all the listeners and the watchers from an android view. For the TextWatcher, I know I have to save each reference added with addTextChangedListener() in a data structure and remove it later (in the onDestroy) with removeTextChangedListener(). But for the other listeners of a view, is there a way that I can find them all to set them to null. So far I have been using this on most of my views (EDIT: all the views that has been assigned any listener; plus this is called in onDestroy() and/or in onDestroyView() depending on the case):
public static void releaseView(View view){
if(view != null ){
view.removeCallbacks(null);
if(!(view instanceof AdapterView)) {
view.setOnClickListener(null);
view.setOnTouchListener(null);
view.setOnLongClickListener(null);
view.setOnDragListener(null);
view.setOnFocusChangeListener(null);
view.setOnKeyListener(null);
if (view instanceof TextView) {
((TextView) view).setOnEditorActionListener(null);
((TextView) view).setKeyListener(null);
if(view instanceof CheckBox)
((CheckBox) view).setOnCheckedChangeListener(null);
}
}
else {
if (view instanceof ListView) {
((ListView) view).setOnItemClickListener(null);
((ListView) view).setOnItemLongClickListener(null);
((ListView) view).setOnItemSelectedListener(null);
((ListView) view).setOnScrollListener(null);
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) //if Marshamallow => API 23
((ListView) view).setOnScrollChangeListener(null);
((ListView) view).setAdapter(null);
//return;
}
if (view instanceof Spinner) {
((Spinner) view).setOnItemSelectedListener(null);
//return;
}
if (view instanceof GridView) {
((GridView) view).setOnItemSelectedListener(null);
((GridView) view).setAdapter(null);
}
}
}
}
Yet I still get some the views called by this method leaked. Is there anything that I am missing. Can someone please correct me if I made a mistake here.