Android Convert onCreate() to Fragment

onCreate() is mandatory for both an Activity and Fragment. They differ a bit. To see how to change your Activity to a Fragment take a look at the previous step.

Before:

protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.outer_layout);
}

After:

private LinearLayout ll;
private FragmentActivity fa;

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

fa = super.getActivity();
ll = (LinearLayout) inflater.inflate(R.layout.outer_layout, container, false);

return ll;
}
You’ll use the FragmentActivity object fa and get the Activity from the parent class. You’ll also return a View object, this should be the most outer element in most cases. In this case a LinearLayout called outer_layout.
Posted in Android, Tips and Tricks Tagged with: , ,