Question

I have no idea why they used a factory method for creating instances of ScreenSlidePageFragment. what is wrong with passing pageNumber in constructor and assigning it to mPageNumber there, and of course getting rid of this factory method and ARG_PAGE?! Here is the code:

public class ScreenSlidePageFragment extends Fragment {
/**
 * The argument key for the page number this fragment represents.
 */
public static final String ARG_PAGE = "page";

/**
 * The fragment's page number, which is set to the argument value for {@link #ARG_PAGE}.
 */
private int mPageNumber;

/**
 * Factory method for this fragment class. Constructs a new fragment for the given page number.
 */
public static ScreenSlidePageFragment create(int pageNumber) {
    ScreenSlidePageFragment fragment = new ScreenSlidePageFragment();
    Bundle args = new Bundle();
    args.putInt(ARG_PAGE, pageNumber);
    fragment.setArguments(args);
    return fragment;
}

public ScreenSlidePageFragment() {
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    mPageNumber = getArguments().getInt(ARG_PAGE);
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    // Inflate the layout containing a title and body text.
    ViewGroup rootView = (ViewGroup) inflater
            .inflate(R.layout.fragment_screen_slide_page, container, false);

    // Set the title view to show the page number.
    ((TextView) rootView.findViewById(android.R.id.text1)).setText(
            getString(R.string.title_template_step, mPageNumber + 1));

    return rootView;
}

/**
 * Returns the page number represented by this fragment object.
 */
public int getPageNumber() {
    return mPageNumber;
}

}

Was it helpful?

Solution

What is wrong with doing what you propose is that the data will be lost on a configuration change. The arguments Bundle is automatically part of the saved instance state of the fragment, and so that data will automatically be retained on a configuration change. Otherwise, by default, you would lose your page number when the user rotates the screen or does any other configuration change.

There are other ways that you could address the problem (e.g., put the page number in the onSavedInstanceState() Bundle yourself). The factory method and arguments Bundle is just a simple and effective way of addressing the issue, but it is not the only way.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top