Android Programming The Big Nerd Ranch Guide, 3rd Edition

(Brent) #1

Chapter 11  Using ViewPager


220

In CrimePagerActivity, set the ViewPager’s pager adapter and implement its getCount() and
getItem(int) methods.


Listing 11.2  Setting up pager adapter (CrimePagerActivity.java)


public class CrimePagerActivity extends AppCompatActivity {


private ViewPager mViewPager;
private List mCrimes;


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_crime_pager);


mViewPager = (ViewPager) findViewById(R.id.crime_view_pager);


mCrimes = CrimeLab.get(this).getCrimes();
FragmentManager fragmentManager = getSupportFragmentManager();
mViewPager.setAdapter(new FragmentStatePagerAdapter(fragmentManager) {


@Override
public Fragment getItem(int position) {
Crime crime = mCrimes.get(position);
return CrimeFragment.newInstance(crime.getId());
}


@Override
public int getCount() {
return mCrimes.size();
}
});
}
}


Let’s go through this code. After finding the ViewPager in the activity’s view, you get your data set
from CrimeLab – the List of crimes. Next, you get the activity’s instance of FragmentManager.


Then you set the adapter to be an unnamed instance of FragmentStatePagerAdapter.
Creating the FragmentStatePagerAdapter requires the FragmentManager. Remember that
FragmentStatePagerAdapter is your agent managing the conversation with ViewPager. For your agent
to do its job with the fragments that getItem(int) returns, it needs to be able to add them to your
activity. That is why it needs your FragmentManager.


(What exactly is your agent doing? The short story is that it is adding the fragments you return to your
activity and helping ViewPager identify the fragments’ views so that they can be placed correctly. More
details are in the section called For the More Curious: How ViewPager Really Works.)


The pager adapter’s two methods are straightforward. The getCount() method returns the number of
items in the array list. The getItem(int) method is where the magic happens. It fetches the Crime
instance for the given position in the data set. It then uses that Crime’s ID to create and return a
properly configured CrimeFragment.

Free download pdf