Don't use getActivity().getSystemService
since the fragment may not be attached to an activity all the time.
Instead store the inflator object you obtained in onCreateView() to an instance variable.
private LayoutInflator inflator =nulll;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
this.inflator= inflator;
View myFragmentView = inflater.inflate(R.layout.your_fragment_layout, container,false);
return myFragmentView;
}
public void yourMethodWhereYouNeedInflator()
{
if(this.inflator!=null)
{
View myView = inflater.inflate(R.layout.my_layout);
}
}
Using parent Activity obtained via getActivity()
as Context is not advised for many reasons. It has the potential to cause memory leaks since any View you are going to inflate will hold a reference to the Activity. Any drawable that attached to any such view will also hold reference to the activity. You will soon run into heavy memory leaks if you happen to store such drawable in an global collection. You may use getActivity().getApplicationContext();
but getActivity()
will return null if it is called before onAttach() is called by the android runtime. but onCreateView()
is guaranteed to be called beforeonAttach(). Hence the better solution is to store the inflater you obtain at onCreateView()
into an instance variable;