When a fragment gets created, it goes through the following state.
oncreate() onAttache() onCreate() onCreateView() onActivityCreated()
onStart() onResume()
onPause() onStop()
onDestroyView() onDestroy() onDetach()
FragmentManager fragmentManager = getSupportFragmentManager(); fragmentManager.beginTransaction() .replace(R.id.container, new fragment(position )) .commit();
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>
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)); } }
Tags: Fragment in Android