Friday, May 29, 2015

How to Convert an Android Activity to a Fragment — Step-by-Step

Earlier I developed an android application using the Activity. But now the trend is to develop the android application using the Fragments. So I thought of converting the Activity based android application to Fragment based Android application. Earlier I thought it’s very difficult to do it. But It’s very simple.

Overview

Here are the steps how we convert an activity to a Fragment:

Prerequisite

  • Basic knowledge of Android Activities and Fragments.
  • If you are using the Support Library, the article uses android.support.v4.app.Fragment types as shown below. Newer projects may use the AndroidX equivalents (androidx.fragment.app.Fragment).

Steps

  1. First we need to import the package: FragmentActivity of Support V4 app package:
Import android.support.v4.app.FragmentActivity;
  1. Change the extends Activity to extends Fragment. Eg:
public class HomeFragment extends Fragment{

}
  1. Add the method onCreateView and move everything from onCreate of Activity to onCreateView except super.onCreate() and setContentView()
public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState) {
    View v = null;
    v = inflater.inflate(R.layout.fragment_home, parent, false);

    // Content of previous onCreate() here
    // ...

    // Don't use this method, it's handled by inflater.inflate() above :
    // setContentView(R.layout.fragment_home);

    return v;
}
  1. Remove method onCreate().

  2. Everywhere you access the Activity with "this" or just something or "this.something" replace with super.getActivity(). or use the value saved in the onCreateView

Example:

// Before (in Activity)
Intent i = getIntent();

// In Fragment
Intent i = super.getActivity().getIntent();

That’s it. Happy Coding…

No comments: