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. Here are the steps  how we convert an activity to a Fragment:
1.     First we need to import the package:
FragmentActivity of Support V4 app package:
Import android.support.v4.app.FragmentActivity;
2.     Change the extends Activity to extends
Fragment. Eg:
public class HomeFragment extends Fragment{
}
3.     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;         
      }
4.      Remove
method onCreate(). 
5.      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 : Intent i = getIntent(); 
becomes Intent i =
super.getActivity().getIntent();
That’s it. Happy Coding…
No comments:
Post a Comment