Tuesday, March 12, 2013

Hot Tuna Fragments

v3 of MvvmCross finally brings some Android Fragment action to MvvmCross

The integration is still a work in progress, but you can see some Fragment binding in https://github.com/slodge/FragmentSample/

This sample shows some basic principles:

- A fragment declared in AXML and it's DataContext (ViewModel) set in Code Behind

var listFragment = (MyListFragment) SupportFragmentManager.FindFragmentById(Resource.Id.list_fragment);
listFragment.ViewModel = ViewModel;
view raw f.cs hosted with ❤ by GitHub
<fragment class="FragmentSample.UI.Droid.Views.MyListFragment"
android:id="@+id/list_fragment"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
/>
view raw f.xml hosted with ❤ by GitHub

- Fragment switched in/out of a ViewGroup container programmatically using Code Behind

_firstFragment = new MyFirstFragment()
{
ViewModel = ViewModel
};
ShowFormFragment(_firstFragment);
private void ShowFormFragment(MvxFragment myFragment)
{
var t = SupportFragmentManager.BeginTransaction();
t.Replace(Resource.Id.titles_fragment_holder, myFragment);
t.Commit();
}
view raw f.cs hosted with ❤ by GitHub
<FrameLayout
android:id="@+id/titles_fragment_holder"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
view raw f.xml hosted with ❤ by GitHub

- Fragments loaded into Tabs

[Activity]
public class TabsFragmentActivity : MvxTabsFragmentActivity
{
public new TabViewModel ViewModel
{
get { return (TabViewModel)base.ViewModel; }
set { base.ViewModel = value; }
}
public TabsFragmentActivity()
: base(Resource.Layout.Page_TabsView, Resource.Id.actualtabcontent)
{
}
protected override void AddTabs(Bundle args)
{
AddTab<Tab1Fragment>("Tab1", "Tab1", "Tab 1", args, ViewModel.Vm1);
AddTab<Tab2Fragment>("Tab2", "Tab2", "Tab 2", args, ViewModel.Vm2);
AddTab<Tab3Fragment>("Tab3", "Tab3", "Tab 3", args, ViewModel.Vm3);
AddTab<Tab3Fragment>("Tab4", "Tab4", "Tab 4", args, ViewModel.Vm3);
}
}

- Fragments used in Dialogs

public class FirstDialogFragment : MvxDialogFragment
{
private readonly Context _context;
public FirstDialogFragment(Context context)
{
_context = context;
}
public override Dialog OnCreateDialog(Bundle savedState)
{
base.EnsureBindingContextSet(savedState);
var view = this.BindingInflate(Resource.Layout.Dialog_FooBar, null);
var dialog = new AlertDialog.Builder(_context);
dialog.SetTitle("First Dialog");
dialog.SetView(view);
dialog.SetNegativeButton("Cancel", (s, a) => { });
dialog.SetPositiveButton("OK", (s, a) => { });
return dialog.Create();
}
}

----

There's still plenty more to learn and explore in these Fragments - the lifecycle of fragments really is a bit odd... so this code isn't really fully production ready yet...

There's also quite a few other things to try - like maps, view pagers and bound fragment collections...

But at least fragments can now be used and can be easily data-bound :)

No comments:

Post a Comment