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

extends Activity -> 
extends Fragment

Change onCreate to onCreateView

protected void onCreate(Bundle savedInstanceState) -> 
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState)
setContentView(R.layout.activity_bugs) ->
View view = inflater.inflate(R.layout.activity_bugs, container,false);
return view;

Options Menu

Add to onCreateView

setHasOptionsMenu(true);

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.

public boolean onCreateOptionsMenu(Menu menu) ->

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

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