To show a different image on each slide, you'll need to add some code that defines the correct image for each page. Since you're just trying to display a few predefined images, I'm guessing that you've already loaded the images into your project's drawable directory. With that assumption in mind, I'll walk you through the missing pieces in the example you're following.
If you haven't done so already, create your ScreenSlidePageFragment
class, and modify the code to look something like this:
public class ScreenSlidePageFragment extends Fragment {
private static final String ARG_RESOURCE_ID = "resource_id";
private int id; // resource id of the static image to display in this page
public ScreenSlidePageFragment() {
// Required empty public constructor
}
// Your program should call this to create each instance of this Fragment.
public static ScreenSlidePageFragment newInstance(int id) {
ScreenSlidePageFragment fragment = new ScreenSlidePageFragment();
Bundle args = new Bundle();
args.putInt(ARG_RESOURCE_ID, id);
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
id = getArguments().getInt(ARG_RESOURCE_ID);
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_screen_slide_page, container, false);
// assign our image's resource id here
ImageView imageView = (ImageView) view.findViewById(R.id.image);
imageView.setImageResource(id);
return view;
}
Because we want each fragment to display an image with a different resource id, I added a parameter (id
) that you can pass to the fragment when you create it.
Now, we just need to make some minor changes to ScreenSlidePagerActivity
. First, add a static array that contains the drawable image resources that you want to use. It should look something like this:
private static final int[] IMAGES = {R.drawable.image1, R.drawable.image2, R.drawable.image3, R.drawable.image4};
Finally, modify your PagerAdapter, so that getCount
returns the size of your array, and getItem
looks up the appropriate resource id for each page before creating each slide's fragment.
private class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter {
public ScreenSlidePagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
if (position < IMAGES.length)
return ScreenSlidePageFragment.newInstance(IMAGES[position]);
else
return null;
}
@Override
public int getCount() {
return IMAGES.length;
}
}