Converting An Activity Into A Fragment

How to converting an activity into a fragment.

Copy and rename the activity

FooActivity.java -> FooFragment.java

Change superclass

{CODE()}extends Activity -> extends Fragment{CODE}

Change onCreate to onCreateView

{CODE(wrap="0")}protected void onCreate(Bundle savedInstanceState) -> public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState){CODE}

{CODE(wrap="0")}setContentView(R.layout.activity_bugs) -> View view = inflater.inflate(R.layout.activity_bugs, container,false); return view;{CODE}

Options Menu

Add to onCreateView

{CODE()}setHasOptionsMenu(true);{CODE} If you do not add this, the overriden methods will not be called.

Override onCreateOptionsMenu

The fragment version includes inflator and does not return a value.

{CODE()}public boolean onCreateOptionsMenu(Menu menu) ->

public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { super.onCreateOptionsMenu(menu, inflater); }{CODE}

Other Tasks

finish() needs to be called via getActivity()

findViewById() needs to be called via the view created in onCreateView()

getBaseContext() needs to be replaced by getActivity()

Recrate Original Activity

Create a new FragmentActivity using the fragment

Remove The Original Activity