android - Alternative way for Fragment to Activity communication -


note, official way fragment activity communication, according http://developer.android.com/training/basics/fragments/communicating.html

public class headlinesfragment extends listfragment {     onheadlineselectedlistener mcallback;      // container activity must implement interface     public interface onheadlineselectedlistener {         public void onarticleselected(int position);     }      @override     public void onattach(activity activity) {         super.onattach(activity);          // makes sure container activity has implemented         // callback interface. if not, throws exception         try {             mcallback = (onheadlineselectedlistener) activity;         } catch (classcastexception e) {             throw new classcastexception(activity.tostring()                     + " must implement onheadlineselectedlistener");         }     }      @override     public void onlistitemclick(listview l, view v, int position, long id) {         // send event host activity         mcallback.onarticleselected(position);     } } 

however, had came across code performs following technique.

    @override     public void onlistitemclick(listview l, view v, int position, long id) {         // send event host activity         ((onheadlineselectedlistener)this.getactivity()).onarticleselected(position);     } 

i tested far works, after configuration change, still latest activity.

i wondering, there catch behind method, besides method recommended google? instance, can getactivity return null?

you should fine second way - first way "shortcut", stores activity in local variable instead of "fetching" via getactivity() each time used.


Comments

Popular posts from this blog

SVG stroke-linecap doesn't work for circles in Firefox? -

routes - Laravel 4 Wildcard Routing to Different Controllers -

cross browser - XSLT namespace-alias Not Working in Firefox or Chrome -