How to Create Fragment in Android
Create a new project in Android Studio
File – New Android Project
What is a Fragment
- A Fragment is a part of activity.Fragment represents a portion of user interface or an operation that runs witin an avtivity.
- A single activity can contain multiple fragment and many fragments can be reused in many different activities.
- A fragment has its own layout and its own behavior with its own lifecycle callbacks.
- Fragment were added to the Android API in Honeycomb version(API 11).
Fragment Life cycle
When a fragment gets created, it goes through the following state.
oncreate() onAttache() onCreate() onCreateView() onActivityCreated()
When the fragment becomes visible,it goes through these state.
onStart() onResume()
When the fragment goes into the background mode,it goes through theses state.
onPause() onStop()
When the fragment is destroyed, it goes to the following states.
onDestroyView() onDestroy() onDetach()
How to use Fragment
Performing Fragment Transactions
FragmentManager fragmentManager = getSupportFragmentManager(); fragmentManager.beginTransaction() .replace(R.id.container, new fragment(position )) .commit();
How to create Fragment Class
Right click on src/ package-New-Fragment-Fragment(Blank)
Fragment_fragment_one_xml <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="mobilemerit.com.fragmentexample.FragmentOne"> <TextView android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center" android:text="@string/hello_blank_fragment_one" /> </FrameLayout>
FragmentOne.java
public class FragmentOne 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 = "param1"; // TODO: Rename and change types and number of parameters public static FragmentOne newInstance(int position) { FragmentOne fragment = new FragmentOne(); Bundle args = new Bundle(); args.putInt(ARG_PARAM1, position); fragment.setArguments(args); return fragment; } public FragmentOne() { // Required empty public constructor } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment return inflater.inflate(R.layout.fragment_fragment_one, container, false); } // TODO: Rename method, update argument and hook method into UI event @Override public void onAttach(Activity activity) { super.onAttach(activity); ((MainActivity) activity).onSectionAttached (getArguments().getInt(ARG_PARAM1)); } }