Member-only story
Android Interview Question Answer : Fragment and Activity Explained
Continue your Android interview preparation with Part 4 of our series! Covering advanced concepts, best practices, and real-world Android development interview questions. Read Part 3 here link on Retrofit
Fragment and Activity
What is a Fragment? How does it differ from an Activity?
- A Fragment is a reusable UI component that can be embedded in an Activity. while activity is an independent component that can not be loaded in another activity.
What is the lifecycle events/method’s of an Activity in sequence?
- Method/Event in sequence
onCreate()
,onStart()
,onResume()
,onPause()
,onStop()
,onDestroy()
.- while closing activity what event called: The
onPause()
,onStop()
, andonDestroy()
methods are called in that order while closing activity.
What is the lifecycle events/method of a Fragment in sequance ?
onAttach()
, onCreate()
, onCreateView()
, onViewCreated()
, onStart()
, onResume()
, onPause()
, onStop()
, onDestroyView()
, onDestroy()
, onDetaWch()
.
In what scenario does the onDestroy get called directly after onCreate?
When you write the finish() method in onCreate() then it only gets called
What is the difference between
onCreate()
andonStart()
in an Activity?
- The onCreate() method is Called when the Activity is created. Used to initialize resources like views, variables, etc.
- The onStart() method is Called when the Activity becomes visible but not yet interactive.
How do you pass data between a Fragment and an Activity?
To pass data between activity and fragment we can use ViewModel.
How do you pass data from Fragment to an Activity without ViewModel?
We can use an interface to share data between activities and fragments. To do that we can define an interface and implement that in the activity and we can pass that implementation to the fragment to get a callback when we need to pass data from fragment to activity.
public class MainActivity extends AppCompatActivity implements MyFragment.OnDataPass {
@Override
public void onDataPass(String data) {
// Handle the data passed from Fragment
}
}