I have written an application in Xamarin which I'm trying to transfer to Android studio.
The Xamarin Application is split into modules each one containing , a number of objects which represent the model and do all the work, one Activity which acts as a controller and interprets messages from the views and sends them to the model, and a number of fragments which represent the views and are responsible for handling screen events and sending the message to the Activity/controller.
Each fragment is always instantiated as new when it has to be shown. Using this code:
private void show_fragment(int fragment_id, string id) {
Fragment fragment = FragmentFactory.Create(fragment_id);
FragmentManager
.BeginTransaction()
.Replace(Resource.Id.content, fragment)
.AddToBackStack(id)
.CommitAllowingStateLoss();
}
and when the fragment is attached, it keeps a reference to the activity it was attached to using this code:
[Obsolete] //this is for older versions of android
public override void OnAttach(Activity activity) {
base.OnAttach(activity);
do_attach(activity);
}
public override void OnAttach(Context context) {
base.OnAttach(context);
do_attach(context);
}
void do_attach(Context context) {
_context = context;
if (context is IModuleInteraction) {
_parent = (IModuleInteraction)( context as object );
} else {
throw new Exception("Fragment parent type is incorrect");
}
}
when the fragment requires something from the controller, it sends it a request along with a callback, for example let's say that the user selected a product from the list, this is what would happen
In the fragment
_parent.product_selected(product_id, () => update_screen(), (message) => show_error(message) );
so in this case the controller will try to find the product, if it can find the product it will call update_screen()
if it can't it will call show_error(message)
In android studio this all works correctly, my question is how can I pass callbacks to the controller?
Right now what I do is this
Fragment fragment = getFragmentManager.findFragmentById(Resource.Id.content)
if (fragment instanceOf ProductSelectFragment) {
ProductSelectFragment psf = (ProductSelectFragment) fragment;
if (error == null)
psf.update_screen();
else
psf.show_error(error);
}
is there a better way to do this?
thanks in advance for any help you can provide
p.s. I an using the base FragmentManager, not the SupportFragmentManager