android - Safest approach for holding an instance of Activity -
what best , safer approach holding instance
of activity
private activity mactivity;
first approach:
@override public void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); mactivity = getactivity(); }
second approach:
@override public view oncreateview(layoutinflater inflater, @nullable viewgroup container, @nullable bundle savedinstancestate) { view view = inflater.from(getactivity()).inflate(r.layout.fragment_main, container, false); mactivity = (activity) view.getcontext(); return view; }
well, depends. advice use getactivity()
.
you can use after onattach(activity activity)
. if @ fragmentmanager
source code, can see there, mactivity
field of fragment
set before calling onattach
.
but have careful, activity not initialized (views,..) before onactivitycreated
gets called.
Comments
Post a Comment