android - How to add a callback to an activity that's created in a fragment? -
i have fragment button calls following method when clicked/pressed:
public void onclick() { intent intent = new intent(getactivity(), mynewactivity.class); startactivity(intent) }
however, want pass callback method mynewactivity
called inside activity's ondestroy
method. need callback method call fragment's finish()
method.
i tried using static variables , worked seems bad design. what's best way this? if not through callback method, what's better approach?
use startactivityforresult()
proposed in comments.
use below code:
fragment:
public class myfragment extends fragment { private static final int request_code = 1353; @override public view oncreateview(layoutinflater inflater, @nullable viewgroup container, @nullable bundle savedinstancestate) { view v = inflater.inflate(r.layout.fragment, container, false); v.findviewbyid(r.id.btn_start).setonclicklistener(new view.onclicklistener() { @override public void onclick(view v) { intent intent = new intent(getactivity(), secondactivity.class); startactivityforresult(intent, request_code); } }); return v; } @override public void onactivityresult(int requestcode, int resultcode, intent data) { if (requestcode == request_code) { toast.maketext(getactivity(), "hooray! fragment got result activity!", toast.length_short).show(); } } }
second activity:
public class secondactivity extends activity { @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.second_activity); findviewbyid(r.id.btn_finish).setonclicklistener(new view.onclicklistener() { @override public void onclick(view v) { setresult(activity.result_ok); finish(); } }); } }
Comments
Post a Comment