Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adapting Model View Presenter pattern to Android With Fragment Tabs

I am working on porting an application from windows mobile to android and I have run into a bit of a problem. The existing application uses the MVP pattern and has distinct "presenter" classes, which are to be reused in the port (it's quite an extensive application and rewriting it just isn't possible, and the C# code is all being reused using mono for android). These take a view implementing an interface, which in android I have achieved by creating activities which implement the appropriate interface, instantiating a presenter and passing themselves as an argument. This all seems to work fine for our purposes, or was until ice cream sandwich came out and I tried to implement it using fragments.

Quite a few of the activities utilise tabs, and in order to use the action bar and some of the other new features I am trying to convert the tabbed activities to tabbed fragments with a viewpager, and this is where I am hitting some problems. From what I have read implementing each tab as a fragment seems to be the preferred method, but I am confused as to how exactly I can allow the presenter to communicate with the fragment through the activity. At the moment the presenter calls the activity's interface methods which then directly access spinners, textviews etc to get and set values as required.As each of these ui elements are declared in the activity this is trivial. If I move all of these ui elements to fragments however it doesn't seem I can access them without implementing a whole new set of interfaces between each activity and fragment. I have tried generating a reference in the activity to ui elements in the fragments (by getting the fragment root view and then finding the view I want inside that), however the viewpager doesn't always load the fragments so this won't work, and even when it has loaded them the layout doesn't get inflated until the activity is in the running state, so I always get null values returned.

I know it's a bit of a strange question, but how can I go about allowing my presenter classes to interact with the ui elements now stored in separate fragment tabs? I feel like I must be going about it in completely the wrong way but I just can't see how it should be done, so if anyone could offer some advice on how I could go about it that would be great.

like image 529
user1193719 Avatar asked Jul 03 '12 02:07

user1193719


1 Answers

How about creating a single presenter for all the Fragments in your FragmentAcivity and then let this single presenter implement an interface for each Fragment (aka Tab). Then instantiate this presenter from your instance of FragmentActivity from which the presenter will have a reference to all the Fragments.

like image 63
Vering Avatar answered Oct 14 '22 01:10

Vering