android - Launching Activity from Fragment -
i have activity single fragment asks user login. once person logs in, new activity launched. question is, once the person enters credentials , hits login button on fragment should
a)the fragment alert current activity first , there start new activity. example, here fragment:
public class loginfragment extends fragment implements view.onclicklistener { private button loginbutton; private clickedinterface clickedinterface; public loginfragment() { // required empty public constructor } static interface clickedinterface{ public void buttonclicked(view v); } @override public view oncreateview(layoutinflater inflater, viewgroup container, bundle savedinstancestate) { view view = inflater.inflate(r.layout.fragment_login, container, false); loginbutton = (button)view.findviewbyid(r.id.fragment_login_loginbutton); loginbutton.setonclicklistener(this); return view; } @override public void onattach(activity activity) { super.onattach(activity); this.clickedinterface = (clickedinterface)activity; } @override public void ondetach() { super.ondetach(); clickedinterface = null; } @override public void onclick(view v) { switch (v.getid()){ case r.id.fragment_login_loginbutton:{ clickedinterface.buttonclicked(v); break; } } }
and here activity using clickedinterface method:
@override public void buttonclicked(view v) { switch (v.getid()){ case r.id.fragment_login_loginbutton:{ //do stuff break; } } }
or
b)launch new activity right fragment?
thank you
it totally depends on business logic have in fragment, , whether you're using in multiple activities. example, might have share button, , button sends intent rate app in play store.
in sharing scenario, might want each activity have different share text. in case, reference of activity, check implements interface, delegate activity:
// share scenario (delegate activity) if (getactivity() instanceof mycallback) { ((mycallback)getactivity()).launchmyintent(); // todo handle callback in activity }
however, if know fact want 1 behaviour regardless of in app (like rating button), might make sense send intent straight fragment.
// rating scenario (send intent fragment getactivity().startactivity(myintent);
Comments
Post a Comment