Updated 22 December 2016
“Fragments are two or more activities on the screen at the same time”.
In this blog, We have shown the how to use fragments rather than using a lot of activities.
If in your app there is hardly two to three layouts contents than you can easily use activities. But if you have a lot of content in your app to show means 20 to 25 layouts or more than this, than from my opinion you can use Fragments.
We can also see activities being used as a way to add logical flow to an application.
A Fragment is a piece of an application’s user interface or behavior that can be placed in an Activity. Interaction with fragments is done through FragmentManager, which can be obtained via
The core series of lifecycle methods that are called to bring a fragment up to resumed state (interacting with the user) are:
onAttach(Activity)
called once the fragment is associated with its activity.onCreate(Bundle)
called to do the initial creation of the fragment.onCreateView(LayoutInflater, ViewGroup, Bundle)
creates and returns the view hierarchy associated with the fragment.onActivityCreated(Bundle)
tells the fragment that its activity has completed its own. Activity.onCreate()
onViewStateRestored(Bundle)
tells the fragment that all of the saved states of its view hierarchy has been restored.onStart()
makes the fragment visible to the user (based on its containing activity being started).onResume()
makes the fragment begin interacting with the user (based on its containing activity being resumed).As a fragment is no longer being used, it goes through a reverse series of callbacks:
onPause()
the fragment is no longer interacting with the user either because its activity is being paused or a fragment operation is modifying it in the activity.onStop()
the fragment is no longer visible to the user either because its activity is being stopped or a fragment operation is modifying it in the activity.onDestroyView()
allows the fragment to clean up resources associated with its View.onDestroy()
called to do the final cleanup of the fragment’s state.onDetach()
called immediately prior to the fragment no longer being associated with its activity.In this tut, we have made a simple fragment and how to attach that fragment to an activity.
First of all, if you are using android studio for development, then create a blank fragment by following steps:-
Then it gives a black fragment and a layout
Let us the name of the fragment black fragment is DemoFragment.java and fragment_demo.xml
fragment_demo.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 |
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="package com.example.mypackage.DemoFragment"> <TextView android:id="@+id/fragmentText" android:layout_width="match_parent" android:layout_height="match_parent" android:text="@string/my_first_fragment" /> </FrameLayout> |
There is a TextView inside FrameLayout. FrameLayout is a layout which is used to hold a single child view.
Why is FrameLayout always USED with Fragments?
We can basically use RelativeLayout or LinearLayout it will still work. But FrameLayout is designed to block out an area on the screen to display a single item.
You can read more about FrameLayout here: About FrameLayout
DemoFragment.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 |
package com.example.mypackage; import android.app.Activity; import android.net.Uri; import android.os.Bundle; import android.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; /* Activities that contain this fragment must implement the DemoFragment.OnFragmentInteractionListener interface * to handle interaction events. */ public class DemoFragment extends Fragment { // TODO: Rename parameter arguments, choose names that match // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER private static final String ARG_PARAM1 = "yourParam1"; private static final String ARG_PARAM2 = "yourParam2"; // TODO: Rename and change types of parameters private String mParam1; private String mParam2; private OnFragmentInteractionListener mListener; /** * @param param1 Parameter 1. * @param param2 Parameter 2. * @return A new instance of fragment DemoFragment. */ // TODO: Rename and change types and number of parameters public static DemoFragment newInstance(String param1, String param2) { DemoFragment fragment = new DemoFragment(); Bundle args = new Bundle(); args.putString(ARG_PARAM1, param1); args.putString(ARG_PARAM2, param2); fragment.setArguments(args); return fragment; } public DemoFragment() { // Required empty public constructor } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (getArguments() != null) { mParam1 = getArguments().getString(ARG_PARAM1); mParam2 = getArguments().getString(ARG_PARAM2); } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment return inflater.inflate(R.layout.fragment_demo, container, false); } // TODO: Rename method, update argument and hook method into UI event public void onButtonPressed(Uri uri) { if (mListener != null) { mListener.onFragmentInteraction(uri); } } @Override public void onAttach(Activity activity) { super.onAttach(activity); try { mListener = (OnFragmentInteractionListener) activity; } catch (ClassCastException e) { throw new ClassCastException(activity.toString() + " must implement OnFragmentInteractionListener"); } } @Override public void onDetach() { super.onDetach(); mListener = null; } /* * This interface must be implemented by activities that contain this * fragment to allow an interaction in this fragment to be communicated * to the activity and potentially other fragments contained in that * activity. */ public interface OnFragmentInteractionListener { // TODO: Update argument type and name public void onFragmentInteraction(Uri uri); } } |
If you want to access our fragment’s view then
in your onCreateView(),
1 2 3 4 5 6 7 8 |
@Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View fragmentView = inflater.inflate(R.layout.fragment_demo, container, false); ((TextView)fragmentView.findViewById(R.id.fragmentText)).setText("My Text"); return fragmentView; } |
create an view named fragmentView and assign the Inflated view to fragmentView.
By fragmentView, you can access your fragment’s Views.
In this example, I have a MainActivity.java. And a button on that. On press of a button, we will open our demoFragment.java.
activity_main.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
<?xml version="1.0" encoding="utf-8"?> <android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:fitsSystemWindows="true" tools:context="com.example.amangupta.mobikul_cs_cart.MainActivity"> <android.support.design.widget.AppBarLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:theme="@style/AppTheme1.AppBarOverlay"> <android.support.v7.widget.Toolbar android:id="@+id/toolbar" android:layout_width="match_parent" android:layout_height="?attr/actionBarSize" android:background="?attr/colorPrimary" app:popupTheme="@style/AppTheme1.PopupOverlay" /> </android.support.design.widget.AppBarLayout> <FrameLayout android:id="@+id/fragment_container" android:layout_width="match_parent" android:layout_height="match_parent"> <Button android:id="@+id/attachFragment" android:layout_width="280dp" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_marginTop="49dp" android:background="@drawable/mybutton" android:text="@string/attach_fragment_title" android:textColor="#FFFFFF" /> </FrameLayout> </android.support.design.widget.CoordinatorLayout> |
MainActivity.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
package com.example.mypackage; import android.app.Fragment; import android.app.FragmentTransaction; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.View; import android.widget.Button; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); Button attachFragment = (Button) findViewById(R.id.attach_fragment); attachFragment.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Fragment newFragment = new DemoFragment(); FragmentTransaction transaction = getFragmentManager().beginTransaction(); transaction.add(R.id.fragment_container, newFragment); transaction.addToBackStack(null); transaction.commit(); } }); } } |
We can see in above code when attachFragment button is clicked. then DemoFragment adds to the fragment_container. by following code snipped:
1 2 3 4 5 |
Fragment newFragment = new DemoFragment(); FragmentTransaction transaction = getFragmentManager().beginTransaction(); transaction.add(R.id.fragment_container, newFragment); transaction.addToBackStack(null); transaction.commit(); |
And if you want, on the press of the back button the previous container has loaded. Then set
1 |
transaction.addToBackStack(null); |
and override onBackPressed()
1 2 3 4 5 6 7 8 9 10 |
@Override public void onBackPressed() { FragmentManager fm = getFragmentManager(); if (fm.getBackStackEntryCount() > 0) { fm.popBackStack(); } else { super.onBackPressed(); } } |
If you have more details or questions, you can reply to the received confirmation email.
Back to Home
2 comments