java - Does this situation cause Memory Leak? -
i writing android project, write these code, want know if code cause memory leak.
as see set "onitemselectedlistener" in foldactivity, implement "itemselectedlistener" in foldfragment, fragment monitor listener, worried when fragment replaced, can fragment retrieve gc?
i think fragment has reference foldactivity cause gc can never retrieve has been replaced other fragment.
public class folderactivity extends activity { // ... spinner spinner; protected void oncreate(bundle savedinstancestate) { // ... final view spinnerview = inflater.inflater(r.layout.category_spinner, null); spinner = spinnerview.findviewbyid(r.id.categoryspinner); // ... } protected void onpostcreate(bundle savedinstancestate) { // ... if (getfragmentmanager.findfragmentbyid(r.id.fragment) == null) { fragment folderfragment = new folderfragment(); if (getintent().hasextra(extra_dir)) { bundle args = new bundle(); args.putstring(folderfragment.extra_dir, getintent().getstringextra(extra_dir)); folderfragment.setarguments(args); } } showfragment(folderfragment); } public void showfragment(fragment fragment) { spinner.setonitemselectedlistener((folderfragment)fragment); getfragmentmanager() .begintransaction() .addtobackstack(null) .replace(r.id.fragment, fragment) .commit(); } }
public class foldfragment extends fragment implements adapterview.onitemselectedlistener { @override public void onitemselected(adapterview<?> parent, view view, int position, long id) { log.d(log_tag, "item selected"); } @override public void onnothingselected(adapterview<?> parent) { log.d(log_tag, "nothing selected"); } }
you don't have worry leaking reference adding fragment listener via setonitemselectedlistener
method. can see in the source, method overwrites reference original listener, remove reference. nice aspect of android api design: setting listener rather adding one, typical in swing, example, less cause memory leak.
Comments
Post a Comment