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

sql - VB.NET Operand type clash: date is incompatible with int error -

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

python - TypeError: Scalar value for argument 'color' is not numeric in openCV -