Tuesday, August 21, 2018

Android getting application context in Fragments

If your activity class extends Activity, you can get application context using getApplicatoinContext(). But this method won’t be available when your Activity extends from Fragment.
Method 1
When your activity extends Fragment, use getActivity () to get the context of the activity.
public class MainActivity extends Fragment {
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        // Getting application context
        Context context = getActivity();
    }
}

No comments:

Post a Comment

AJAX - Quick Guide