1. 程式人生 > >How To Communicate Between Fragments and Activities in Android

How To Communicate Between Fragments and Activities in Android

Welcome to: how to communicate between fragments and activities in your android applications. If you have not done so already, please check out my previous post on dynamic layout design using weights and fragments that I wrote yesterday! In the above linked post, I briefly talk about how to solve the problem of dealing with different device sizes by letting the android system adjust accordingly! In today’s post, we are going to take a quick look at how fragments can communicate back to the activity – basically how they can call back and forth to pass information when needed. Also, if you ever use fragments, you should always avoid trying to let fragments communicate with one another – it is a bad idea (will explain this later).

Download my new app I created just for this!

Since I was getting this question a lot, I decided to create a simple android app that shows you how to communicate between fragments and activities – with example code.

Wait, there is more: you can choose to listen to it because it can read the tutorial to you as you sit back and enjoy. Download the app now for free and NO ads.

how to communicate between fragments and activities

As shown in the image above, you can simply tell the intent of the arrows. Communication start from the fragment to the activity and then from the activity back to the fragment or to another fragment if you have more than one fragment displayed. So, how do you do this? Not difficult to say the least – as we will see soon!

How To Communicate Between Fragments and Activities – Example

Step One

The first thing while creating your app that uses fragments is to create  your layouts. Once you have created your layouts which could be a list view or anything you want, you can then create your Fragment class.

Inside your onCreateView method of your fragment, you should inflate that view – again, a list view is a good example here. You normally return a view inside this method. Now, using a list view for example, you would probably like to do something whenever a user selects an item from that list like pop open a dialog to let them confirm their actions or load a whole new view to display the details for that particular item. So, how do you accomplish that?

You simply want to implement an OnClickListener then override its onClick method (this depends on what type of view you have – which could be a grid view or just a list view). Overriding such a method provides you with certain arguments like position – which is important when you really want to deal with particular items in a list and you can then pass the value back to the activity!

Step Two

The second step after inflating your view and implementing a click listener (as an example), you want to define an interface and then create a method – always remember than interface methods do not have bodies in them – it is the responsibility of the implementing class to override them and do what they want with them. You can define your interface from within the fragment class or as a standalone class in your project src folder.

Step Three

The third step is to implement that interface in your main activity. You will do something along the lines of MainActivity extends Activity implements FragmentOne.OnContactSelectedListener  – from there on, you will have to override the method you defined earlier (from the fragment) in your activity. If your method inside your fragment expected an integer argument, remember to define it exactly as it is in your activity(same signature).

Step Four

Now that you have that covered, here comes the beauty of interfaces – whenever a user clicks an item, you can grab the position of that item (from the onClick method) and pass it back to the activity by simply calling the interface method. After that, you can pick it from the activity – inside the method you overrode and do some really awesome stuff with that position like query the database or get a value from a list array depending on which position you get back! Pretty cool right?

Let us try and create some stuff here.

MainActivity.java

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647 /*** The main activity that communicates with the fragment(s)* @author Elisha Chirchir - Simple Developer* @since - 2014**/publicclassMainActivity extendsActivity implementsNewsItemsFragment.OnNewsItemSelectedListener{privateNewsItemsFragment mItemsFragment;@OverridepublicvoidonCreate(Bundle saveInstanceState){super.onCreate(saveInstanceState);setContentView(R.layout.main);//Instantiate some stuff here like view componentsmItemsFragment=newNewsItemsFragment();//Now you can set the fragment to be visible heresetFragment(mItemsFragment);}publicvoidsetFragment(Fragment frag){FragmentManager fm=getFragmentManager();if(fm.findFragmentById(R.id.container)==null){fm.beginTransaction().add(R.id.container,frag).commit();}}//Override the method here@OverridepublicvoidonNewsItemPicked(intposition){//Do something with the position value passed backToast.makeText(activity,"Clicked "+position,Toast.LENGTH_LONG).show();}}

Now we can create our Fragment class here – the order is up to you really!

NewsItemsFragment.java

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263 /*** Fragment that inflates a list view to display news headlines* @author - Elisha Chirchir - Simple Developer Blog* @since - 2014*/publicclassNewsItemsFragment extendsListFragment implementsAdapterView.OnItemClickListener{Activity activity;publicstaticList newsHeadlines=newArrayList(){{add("Android Is Awesomerrrrrrrrrrrrrrrrrrr");add("A teenager asks Miss America To Prom and gets suspended");add("The Congress in The History of the United States is..");add("How To Drive Safely When No One else Is.");add("Learn How To Program On Your Own");add("How To Communicate Between Fragments and Activities");add("What to do when you have nothing to do");add("The next big thing is here - your awesome app!");}};@OverridepublicvoidonAttach(Activity activity){super.onAttach(activity);this.activity=activity;}@OverridepublicvoidonActivityCreated(Bundle savedInstanceState){super.onActivityCreated(savedInstanceState);ArrayAdapter adapter=newArrayAdapter(activity,R.layout.simple_row_item,newsHeadlines);setListAdapter(adapter);getListView().setOnItemClickListener(this);}@OverridepublicView onCreateView(LayoutInflater inflater,ViewGroup container,Bundle savedInstanceState){returninflater.inflate(R.layout.head_lines_fragment,container,false);}@OverridepublicvoidonItemClick(AdapterView<?>parent,View view,intposition,longid){Toast.makeText(activity,"Clicked "+position,Toast.LENGTH_LONG).show();try{((OnNewsItemSelectedListener)activity).onNewsItemPicked(position);}catch(ClassCastException cce){}}publicinterfaceOnNewsItemSelectedListener{publicvoidonNewsItemPicked(intposition);}}

Summary of How To communicate between fragments and activities

The reason why fragments are very powerful is because they do almost anything you would do inside an activity. That being said, you could decide to instead of passing back just the position, you could do other manipulations like query the database to get the details from tables and then pass back the string value for the news articles. You can do a hell lot more to say the least.

As you can see, communication between fragments and activities is made so much easier through interfaces in Java and you can really do whatever you want. For example, inside the method we overrode in the activity, we could do something else like load a new fragment to display the details or even start a new intent to open a web page and other crazy things you can imagine!

This post is getting longer so I will halt it here for today and perhaps continue next time with other exciting stuff in android fragments! You can always visit the Google docs for more information on Fragments.

If you found this post helpful, p[ease consider sharing it with your friends using the buttons below! Thank you for stopping by and have fun coding!