All about Fragment in Android
Hello friends hi. This post is regarding all about Fragment in Android. Fragment is also one of the most important and useful topic in Android. So in this post we will learn the following points about Fragment...
1)- What is Fragment?
2)- What is the lifecycle of Fragment?
3)- How to implement Fragment?
4)- Difference between Activity and Fragment?
These points are also very important for any interview..... So let's get start....
1)- So the first point is what is Fragment?
The answer is quite simple, A Fragment is a part of an Activity. It is also called as the sub-activity with their own lifecycle. There can be more than one Fragment in an Activity and the fragment lifecycle is affected by the activity lifecycle.
2)- What is the lifecycle of Fragment?
Fragment lifecycle can be demonstrate using the following picture....
3)- How to implement Fragment?
*** Basic code in XML:
<fragment android:id="@+id/fragments" android:layout_width="match_parent" android:layout_height="match_parent" />
import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.ViewGroup; public class FirstFragment extends Fragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment return inflater.inflate(R.layout.fragment_first, container, false); } }
4)- Difference between Activity and Fragment?
Here are the main difference between Activity and Fragment....
*** Activity is independent where as the Fragment is dependent on the Activity.
*** Activity is Comparatively heavy where as the fragment is light weighted.
*** We must have to mention the Activity in our Manifest.xml file where as fragment does not need to be declared in the Manifest file.
*** Activity is having their own lifecycle where as the Fragment lifecycle is decided by the Activity lifecycle in which it is hosted.
*** Activity can be created without a Fragment where as a Fragment can not be created without an Activity.

Comments
Post a Comment