Android use ArrayList to handle Fragments

As you dive into the current world of Android development, you will be dealing more and more with Fragments and less with new Activities. Weather you choose a dropdown or tabbed navigation it is a good idea to create some sort of array of your Fragments that can map to the positions returned by the dropdown or tabs.

Here is the code from my MainActivity:

@Override
		public Fragment getItem(int position) {
			// getItem is called to instantiate the fragment for the given page.
			ArrayList <Fragment> fragments = new ArrayList <Fragment>();
			fragments.add(new ReminderFragment());
			fragments.add(new PatientFragment());
			fragments.add(new StopWatchFragment());
			Fragment fragment = fragments.get(position);
			Bundle args = new Bundle();
			fragment.setArguments(args);
			return fragment;
		}

When a tab is selected this function is run and the position arg sent can be used as an array index for getting the correct fragment. All you have to do is create and ArrayList and add the fragments in the same order as their tabs. This keeps the fuction smaller and more scalable.

Advertisements
Tagged , , ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: