Monday, June 24, 2013

How to get the context in a fragment? - Android Apps

Use the following code to get the context in Fragment

public static class SomeFragment extends Fragment{

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        context = activity.getApplicationContext();
    }
}

2 comments:

  1. No need to introduce context variable - since you can always call getContext() in the Fragment

    ReplyDelete
    Replies
    1. Hi Farber,
      I think it's not a proper way. Every time you use getContext(), you call a function so you must deal with run-time stack, saving the state and ... . They are time consuming. But when you use a variable, the complexity of your program become less.

      Delete