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

android - Why am I getting the message 'Youractivity.java is not an activity subclass or alias' -

python - How do I create a list index that loops through integers in another list -

c# - “System.Security.Cryptography.CryptographicException: Keyset does not exist” when reading private key from remote machine -