fredag 8 februari 2013

Android : Fragments (a reminder)

Everyone is propably used to fragments by now, this is a quick reminder what methods to override for different purposes. Google has two helpful pages on fragments, the reference class page for Fragment, can be found here http://developer.android.com/reference/android/app/Fragment.html and their general for Fragments, http://developer.android.com/guide/components/fragments.html.

This will be a shortpacked for most methods i usually override as a reminder for myself!

Keyboard shortcuts to open the generate code dialog is  ALT + Insert for IntelliJ IDEA

ALT + Shift + S for Eclipse users.

Screenshot from IntelliJ IDEA.




src/MyFragment.java
import android.app.Activity;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;



/**
 *  MyFragment - Does Exactly Nothing! :)
 */
public class MyFragment extends Fragment {

    private IUpdate myListener;

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        // We have any listeners that need to communicate
        // with our activity, lets attach them here.
        myListener = (IUpdate) activity;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // A custom xml view involved
        // Lets inflate it here!
        return inflater.inflate(R.layout.secret_layout, container, false);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        // Manage & find all the containers/widgets
        // in our layout.
        View myView = getView();
    }

    @Override
    public void onResume() {
        super.onResume();
        // We have something that might have changed while coming back
        // from another view? Settings ? Lets check & then update.
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        // If our activity gets destroyed.
        // I.e we changed from portrait to landscape.
        // Anything we need to remember ?
        //
        // Remember, this do not get called just by hiding your view!
        // It's the activity it depends on.
    }
}

This should be methods i tend to override depending on what i'm doing when i'm creating a new Fragment.
A small skeleton fragment to keep me on track, hopefully it's helpful!

Now, family time!