Issue
The Android Developer Guide states that activities are launched via Intents:
Intent intent = new Intent(this, SignInActivity.class);
startActivity(intent);
For Fragments, the usual way to display it on the screen is as follows:
ExampleFragment fragment = new ExampleFragment();
fragmentTransaction.add(R.id.fragment_container, fragment);
fragmentTransaction.commit();
Why is it that in one case I have to specify a class, and in the other an object? I.e., I would like to use something like
Activity nextActivity = new SignInActivity();
Intent intent = new Intent(this, nextActivity);
startActivity(intent);
Solution
Because Activity
lifecycle is managed by Android whereas Fragment
lifecycle is tied to the Activity in which it is contained.
As mentioned, Activity
lifecycle is managed by Android. This is required, among other things, for Android to manage the system resources and also to take care of the back stack.
Fragment
, on the other hand, was introduced to modularize and better organize the UI for devices with different sizes. According the the documentation:
Starting with HONEYCOMB,
Activity
implementations can make use of theFragment
class to better modularize their code, build more sophisticated user interfaces for larger screens, and help scale their application between small and large screens.
To answer the latter part of your question, you can indeed pass the results of an activity to a second activity. But you should never create an instance of an Activity
class for that. The right way is to use the startActivityForResult()
and send the resulting value to the destination activity through the Intent
.
Answered By - Rajesh
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.