여러 개의 프래그먼트를 하나의 액티비티에 조합하여 창이 여러 개인 UI를 구축할 수 있으며, 하나의 프래그먼트를 여러 액티비티에서 재사용할 수 있습니다.
프래그먼트는 액티비티 위에 올라가는 것이므로, 프래그먼트의 수명주기도 액비티티의 수명주기에 종속적입니다. 하지만, 프래그만트만 가질 수 있는 상태 메소드들이 더 추가 되었습니다.
다양한 프래그먼트 콜백 메소드의 사용 예제 (참고자료)
public class SomeFragment extends Fragment {
ThingsAdapter adapter;
FragmentActivity listener;
// This event fires 1st, before creation of fragment or any views
// The onAttach method is called when the Fragment instance is associated with an Activity.
// This does not mean the Activity is fully initialized.
@Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof Activity){
this.listener = (FragmentActivity) context;
}
}
// This event fires 2nd, before views are created for the fragment
// The onCreate method is called when the Fragment instance is being created, or re-created.
// Use onCreate for any standard setup that does not require the activity to be fully created
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ArrayList<Thing> things = new ArrayList<Thing>();
adapter = new ThingsAdapter(getActivity(), things);
}
// The onCreateView method is called when Fragment should create its View object hierarchy,
// either dynamically or via XML layout inflation.
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_some, parent, false);
}
// This event is triggered soon after onCreateView().
// onViewCreated() is only called if the view returned from onCreateView() is non-null.
// Any view setup should occur here. E.g., view lookups and attaching view listeners.
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
ListView lv = (ListView) view.findViewById(R.id.lvSome);
lv.setAdapter(adapter);
}
// This method is called when the fragment is no longer connected to the Activity
// Any references saved in onAttach should be nulled out here to prevent memory leaks.
@Override
public void onDetach() {
super.onDetach();
this.listener = null;
}
// This method is called after the parent Activity's onCreate() method has completed.
// Accessing the view hierarchy of the parent activity must be done in the onActivityCreated.
// At this point, it is safe to search for activity View objects by their ID, for example.
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
}