It seems like a nice way to simplify how arguments are set for fragments so I'm curious why it's not commonly depicted for creating explicit intents for starting activities?
The newInstance() method of Class class and Constructor class is used to create a new instance of the class. The newInstance() method of Class class can invoke zero-argument constructor, whereas newInstance() method of Constructor class can invoke any number of arguments.
To get the current fragment that's active in your Android Activity class, you need to use the supportFragmentManager object. The supportFragmentManager has findFragmentById() and findFragmentByTag() methods that you can use to get a fragment instance.
There's nothing wrong with creating a static
method to build the Intent
to start an activity, or even having a static
method that starts the activity. You can also go with an IntentBuilder
pattern, where you expose a builder-style API that generates the Intent
, for scenarios where a simple method would be unworkable. I take that approach in my CWAC-Cam2 library, for example.
Google hasn't been promoting the pattern, though you will see this sort of code if you generate a service from the Android Studio wizard, IIRC. However, Google isn't really in the business of trying to show every possible programming pattern.
The biggest limitation that I know of is that there is no enforcement mechanism. While you can offer these sorts of facilities, there is nothing stopping developers from bypassing or ignoring them. IOW, the classic create-an-Intent
-and-go API is "public", and you cannot somehow make it private. So, your activity needs to assume the worst, and have whatever defensive programming you feel is appropriate.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With