Home » Android » Using Fragment in Android

Using Fragment in Android

Fragment allows quick switching to the interface, consuming less resources compared to

, Activity

  • first creates a Activity:
  • with Fragment
  • adds buttons in Fragment for action:

 Android:layout_width= "wrap_content" 
Android:layout_height= "wrap_content"
Android:text= "start Fragment"
Android:id= "@+id/btnStartFragment"
Android:layout_centerVertical= "true"
Android:layout_centerHorizontal= "true" />

  • creates another Fragment's Java, Class, and XML files:

  • Java Class:

public, class, AnotherFragment, extends, Fragment{
public, View, onCreateView (LayoutInflater, inflater, ViewGroup, container, Bundle, savedInstanceState) {
View rootView = inflater.inflate (R.layout.fragment, container, false);
return rootView;

  • XML:

<, XML, version=, 1, encoding=, UTF-8, >
<LinearLayout xmlns:android=, "http://schemas.android.com/apk/res/android",
android:orientation= "vertical", " android:layout_width=", "match_parent",
android:layout_height= "match_parent" >


  • then adds the listening event of the button in the first Activity's Class to replace the Fragment:

, View, rootView = inflater.inflate (R.layout.fragment_fragment, container, false);
RootView.findViewById (R.id.btnStartFragment).SetOnClickListener (new, View.OnClickListener () {
public, void, onClick (View, V) {
GetFragmentManager () // manages Fragment
.beginTransaction () // begins to transform Fragment
.addToBackStack (null) // allows backing
.replace (R.id.fragment, new, AnotherFragment ()) // replaces the original Fragment with AnotherFragment
.commit (); // submits