Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Move newInstance method before constructor #8

Closed
passsy opened this issue Sep 26, 2017 · 1 comment
Closed

Move newInstance method before constructor #8

passsy opened this issue Sep 26, 2017 · 1 comment

Comments

@passsy
Copy link
Contributor

passsy commented Sep 26, 2017

The static newInstance() method of Fragments is a common way to create new Fragment instances. The same pattern can be used for Activities to build an Intent in a type safe way, namely newIntent(). Those building functions replace the constructors.

public static class MyFragment extends Fragment {

  public MyFragment() { }  // Required empty constructor

  public static MyFragment newInstance(String foo, int bar) {
    MyFragment f = new MyFragment();
    Bundle args = new Bundle();
    args.putString(ARG_FOO, foo);
    args.putInt(ARG_BAR, bar);
    f.setArguments(args);
    return f;
  }

You can then access this data at a later point:

@Override
public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  Bundle args = getArguments();
  if (args != null) {
    // Use initialisation data
  }
}

There aren't many use cases for public static methods in Java other than initializer helper methods. Utils methods are also public static but they normally exist in util classes where all methods are public static. That's the reason why it is safe to move all methods with this signature above the constructor.

@passsy
Copy link
Contributor Author

passsy commented Sep 26, 2017

Implemented

@passsy passsy closed this as completed Sep 26, 2017
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Development

No branches or pull requests

1 participant