Showing posts with label mvvmcross. Show all posts
Showing posts with label mvvmcross. Show all posts

Tuesday, September 02, 2014

Duplicate folders issue with MvvmCross by NuGet

 

EDIT: Issue is fixed in MVVMCROSS v3.2.1 !

With the current NuGet version of MvvmCross, when adding it to the project you get duplicate folders (‘Layout’ and ‘layout’, ‘Values’ and ‘values’)

To fix this, right click on the project and choose ‘Tools \ Edit File’ in Xamarin Studio. In Visual Studio, there’s a similar way.

In the .csproj, you just need to replace the first upper case letter with lower case letter, so replace ‘Layout’ with ‘layout’ and ’Values’ with ‘values’ and save the file.

image

Monday, April 07, 2014

A busy MvxViewController for MvvmCross + iOS

In my MVVMCross apps, in the shared PCL core library, I usually have a MvxViewModel derived class called ViewModelBase with a IsBusy property:


public class ViewModelBase : MvxViewModel
{
bool isBusy;
public bool IsBusy
{
get { return this.isBusy; }
set { if (this.isBusy != value) { this.isBusy = value; this.RaisePropertyChanged("IsBusy"); } }
}

// other base stuff in ViewModelBase
}
The property is to update a progress indicator control in the view.
For iOS the control can be UIActivityIndicatorView.

But instead of placing a UIActivityIndicatorView on each view, we can dynamically create it at run-time when IsBusy property changes to true.
We can have this implemented in a ViewController base class like this:

using System;
using System.ComponentModel;
using MonoTouch.ObjCRuntime;
using MonoTouch.UIKit;
using Cirrious.MvvmCross.Touch.Views;
using Cirrious.CrossCore.WeakSubscription;
using YourApp.Core.ViewModels;

namespace YourApp.Touch
{
public abstract class MvxViewControllerBase : MvxViewController
{
// weak subscription to NotifyProperty event
IDisposable npSubscription;

public override void ViewDidLoad()
{
base.ViewDidLoad();

// subscribe to view-model's PropertyChanged
this.npSubscription = ((INotifyPropertyChanged)this.ViewModel).WeakSubscribe<bool>("IsBusy", (s, e) => { this.UpdateActivityIndicatorView(); });

// at this point view-model exists, so update the indicator view
this.UpdateActivityIndicatorView();

// add other common UIViewController stuff
}

protected override void Dispose(bool disposing)
{
if (disposing && this.npSubscription != null)
{
this.npSubscription.Dispose();
this.npSubscription = null;
}
base.Dispose(disposing);
}

void UpdateActivityIndicatorView()
{
// get the activity indicator
var activityIndicatorView = (UIActivityIndicatorView)this.View.ViewWithTag(1000);

var vm
= (ViewModelBase)this.ViewModel;
if (vm.IsBusy)
{
// show busy indicator. create it first if it doesn't already exists
if (activityIndicatorView == null)
{
activityIndicatorView
= new UIActivityIndicatorView(this.View.Frame)
{
ActivityIndicatorViewStyle
= UIActivityIndicatorViewStyle.Gray,
Tag
= 1000
};

this.Add(activityIndicatorView);
this.View.BringSubviewToFront(activityIndicatorView);
activityIndicatorView.StartAnimating();
}

// show the activity indicator
activityIndicatorView.Hidden = false;
}
else
{
// hide the activity indicator
if (activityIndicatorView != null)
{
activityIndicatorView.Hidden
= true;
}
}
}
}
}
Instead of having a base class we can delegate the implementation to an extension class which has the same implementation.

Please let me know if you see any possible issues.

I am thinking to do a similar implementation for other platforms as well.
Maybe MVVMCross could support out of the box a similar implementation. A built in implementation in MVVMCross would probably require to be able to override the style for the indicator.

Saturday, January 25, 2014

Type-safe ViewModel to ViewModel navigation in MvvmCross


In MvvmCross you can navigate between view-model's as described in the Wiki:
https://github.com/MvvmCross/MvvmCross/wiki/ViewModel--to-ViewModel-navigation

It's good however to use a simple type-safety mechanism.
Suppose we have a ProductViewModel which expects two arguments for initialization:

public class ProductViewModel : MvxViewModel
{
     public void Init(int productId, int clientId)
     {
          ....
     }
}

With a type-safe mechanism, instead of writing:

ShowViewModel<ProductViewModel>(new { productId = pid, clientId = cid });

we can write:

NavigationHelper.ShowProduct(pid, cid);

where NavigationHelper is a simple utility class:

using Cirrious.CrossCore;
using Cirrious.MvvmCross.ViewModels;
using Cirrious.MvvmCross.Views;
using MyApp.Core.ViewModels;
using Cirrious.MvvmCross.Platform;

namespace MyApp.Core.Common
{
    public static class NavigationHelper
    {
        public static void ShowProduct(int productId, int clientId)
        {
            ShowViewModel<ProductViewModel>(new { productId = productId, clientId = clientId });
        }

        static void ShowViewModel<T>(object parameter) where T : IMvxViewModel
        {
            var viewDispatcher = Mvx.Resolve<IMvxViewDispatcher>();
            var request = MvxViewModelRequest.GetDefaultRequest(typeof(T));
            request.ParameterValues = ((object)parameter).ToSimplePropertyDictionary();
            viewDispatcher.ShowViewModel(request);
        }
    }
}

using Cirrious.MvvmCross.Platform; namespace statement is important because it contains the ToSimplePropertyDictionary() extension method implemented by MvvmCross.

Furthermore, instead of using the NavigationHelper class, we can move the ShowViewModel method to a ViewModelBase class:

public class ViewModelBase : MvxViewModel
{
       protected static void ShowViewModel<T>(dynamic parameter) where T : IMvxViewModel        
       {            
           var viewDispatcher = Mvx.Resolve<IMvxViewDispatcher>();            
           var request = MvxViewModelRequest.GetDefaultRequest(typeof(T));            
           request.ParameterValues = ((object)parameter).ToSimplePropertyDictionary();            
           viewDispatcher.ShowViewModel(request);        
       }
}

public class ProductViewModel : ViewModelBase
{
    public static Show(int productId, int clientId)
    {
        ShowViewModel<ProductViewModel>(new { productId = productId, clientId = clientId });
    }

    public void Init(int productId, int clientId)
    {
        ...
    }
}

and we can now write:

ProductViewModel.Show(pid, cid);

Having the Show method near the Init method in the ViewModel class, makes it a bit more easier to maintain the parameters.

Sunday, December 29, 2013

Windows Store app development - important things to remember


1. Pages are by default destroyed when navigating from them. This is in contrast to Windows Phone where pages are cached.
2. When your app moves out of the foreground, Windows waits for a few seconds to allow quick switching back to the app, then tries to suspend the app.
This is very nicely described here:
http://blogs.msdn.com/b/windowsappdev/archive/2012/04/10/managing-app-lifecycle-so-your-apps-feel-quot-always-alive-quot.aspx
If your app doesn’t return from its suspending event handler within 5 seconds of receiving the suspending event, Windows will terminate it. It’s important not to do any heavy operations in your suspending event handler. Save your app data and return quickly.
3. When running app with debugger, the application is not suspended by the OS when it’s moving out of foreground. You need to use Suspend \ Resume menu in Visual Studio
More info:
http://msdn.microsoft.com/en-us/library/windows/apps/hh974425.aspx
http://blogs.msdn.com/b/windowsappdev/archive/2012/04/10/managing-app-lifecycle-so-your-apps-feel-quot-always-alive-quot.aspx
4. MVVMCross doesn’t play nicely with the generated SuspensionManager
In App.xaml.cs, I removed SuspensionManager:
private void OnSuspending(object sender, SuspendingEventArgs e)
{
           var deferral = e.SuspendingOperation.GetDeferral();
            //await SuspensionManager.SaveAsync();
            deferral.Complete();
}


5. Windows App Certification Kit fails on Suspend
Following error can be thrown while no real suspend problem is present in the code:

Performance suspendError Found: The performance suspend test collected the following results:
Application Error: Application Suspend was not detected for application App. This could be because your application failed to suspend correctly. Please consider re-running the test avoid interacting with the application while tests are running. 
Make sure you have Visual Studio running under admin privileges.
More info: http://endurasoftware.wordpress.com/2013/09/12/windows-app-certification-kit-fails-on-suspend/

6. Use Simulator to create screenshots for certification and check app in different resolutions.

7. How to create package and send it to customer and let him upload to his Windows Store account
The package needs to be created using the certificate generated with the customer’s Windows Store account.
For this, customer needs to first create a dummy app on his machine using Visual Studio. Suppose the customer reserves the ‘My App’ app name in the Windows Store:
1. Make a Windows Store app in Visual Studio (Blank App is fine), called MyApp
2 Once created, right click on the project and from context menu, choose Store \ Create App Packages ...
3. Choose Yes, click Next and sign in with the Windows Store account
4. In the list with reserved names, select select "My App" name
5. Click Create
6. Close dialog 'Package Creation Completed'
The customer needs to archive and send the whole project folder.








On my machine, in Visual Studio, double click on ‘Package.appxmanifest’ and in ‘Packaging’ tab click on Choose Certificate button and select the .pfx sent by the customer.
Make sure the ‘Package name’ and ‘Publisher display name’ corresponds to those from the app project generated by the customer.

Wednesday, November 13, 2013

ActionBarSherlock + Xamarin + MVVMCross

 

Short history of ActionBar in Android and Xamarin

1. ActionBar was first added in Android 3.0 (API Level 11).

2. ActionBarSherlock is a third-party library created by Jake Wharton, which brought ActionBar support for Android 2.x: “The library will automatically use the native action bar when appropriate or will automatically wrap a custom implementation around your layouts. This allows you to easily develop an application with an action bar for every version of Android from 2.x and up.”

ActionBarSherlock it’s not just about ActionBar support on Android 2.x, it also has some nice features not available in the Android’s ActionBar implementation.

3. In July 2013, Android Support Library revision 18 introduced a new v7 appcompat library which has ActionBar support for Android 2.1+.

4. Xamarin created a free component for their store as a binding for the ActionBarSherlock, called ‘ActionBarSherlock for Xamarin’.

5. Xamarin created a free component for the Android support Library v7 (rev 18) http://components.xamarin.com/view/xamandroidsupportv7appcompat

I haven’t yet tried how the ActionBar works using the this support library.

 

Using ActionBar in Xamarin application with ActionBarSherlock Xamarin component

The steps are:

1. Create an Android application and add MvvmCross by NuGet. (MvvmCross creates and adds a FirstView activity to the project).

2. Add ActionBarSherlock for Xamarin component from Xamarin Components store

3. Make sure the Android project has ‘Compile using Android version’ and ‘Target Android version’ set to the latest Android version.

4. Add reference to Mono.Android.Support.v4

5. Add a MvvmCross implementation for SherlockFragmentActivity (MvxSherlockFragmentActivity).

   I create a folder ‘MvxSherlockActionBar’ in the Droid project and add to it these two files: MvxEventSourceSherlockFragmentActivity.cs MvxSherlockFragmentActivity.cs These add support for MvvmCross to SherlockActionBar.

6. Change the FirstView’s class parent from MvxActivity to MvxSherlockFragmentActivity and set the ActionBar’s theme

[Activity(Label = "View for FirstViewModel"] 
public class FirstView : MvxSherlockFragmentActivity
{
protected override void OnCreate(Bundle bundle)
{
SetTheme(Resource.Style.Theme_Sherlock);
base.OnCreate(bundle);
SetContentView(Resource.Layout.FirstView);
}
}


You should use SherlockFragmentActivity::SupportActionBar property to use the ActionBar.

A very basic walkthrough to the Xamarin component: http://components.xamarin.com/gettingstarted/XamarinActionBarSherlock 
Xamarin also created a sample application using Xamarin ActionBarSherlock component and made its source code available https://github.com/xamarin/monodroid-samples/tree/master/ActionBarSherlock It contains different examples of usage.

Sunday, September 22, 2013

Xamarin MVVMCross PCL Visual Studio issues

 

Introduction to MVVMCross setup

MVVMCross framework is suitable for Xamarin applications with the following structure:

- a platform-independent PCL Core (MyApp.Core) project containing your app logic like view models, services, models
- several platform specific applications projects (MyApp.Droid, MyApp.iOS, MyApp.Store)

Note that MVVMCross works with PCL targeting frameworks
’NET Framework 4.5’,
‘Silverlight 4 and higher’.
‘Windows Phone 7.5 and higher’,
‘.NET for Windows Store apps’

You don’t need to select all these, just the platforms you target but MVVMCross doesn’t work  with ‘.NET Framework 4.0’ or ‘Windows Phone 7’.

The problem

Because of the framework target profiles, Visual Studio by default won’t let you add a PCL project as reference to your Xamarin Android project in Visual Studio.
In the case of MVVMCross, you cannot add the Core PCL project to the application project.

Solutions

The solutions I’ve seen:


#1. (Most popular) Create profiles for ‘Mono for Android’ and ‘MonoTouch’ in
C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETPortable\v4.0\Profile\Profile104\SupportedFrameworks
This makes the two profiles available when creating the PCL and makes Visual Studio recognizing the PCL project compatible with the Xamarin app projects.
http://slodge.blogspot.ro/2012/12/cross-platform-winrt-monodroid.html
http://jpobst.blogspot.co.uk/2012/04/mono-for-android-portable-libraries-in.html
http://psvitz.com/xamarin-vs2012-pcl-mvvm-cross-v3-awesome1one1/

#2. Manually edit the Xamarin application projects to add reference to the PCL project. It will compile fine but with a warning generated about the possible framework incompatibility
http://blog.ostebaronen.dk/2013/07/working-with-pcls-in-lates.html

#3.  The solution I am using: create PCL project and app project in Visual Studio, then use Xamarin Studio just to add the PCL project as reference to the application project. Then switch back and continue work in Visual Studio.

      (If you’ve been using the two profiles from method #1, remove them in advance. For this solution, you shouldn’t see them when creating the PCL, because they create an issue selecting the ‘WP7.5 and higher’ without these two profiles selected, see more below)
 

I also saw another way which involves using a WPF class library (you read it right).
http://neueobjective.wordpress.com/2013/08/08/using-asyncawait-system-net-http-httpclient-and-mvvmcross-in-wp8-xamarin-android-and-xamarin-ios/

 

Problems with having the ‘Mono for Android’ and ‘MonoTouch’ custom profiles

When using #1 with custom profiles, if you try to use NuGet in Visual Studio, Visual Studio will complain about the larger majority of the available toolkits in NuGet:

image

The reason is because most toolkits do not know about the ‘Mono for Android’ and ‘MonoTouch’ framework targets.
As a workaround, even if the operation failed, you can still manually add as references the toolkit assemblies downloaded by NuGet in the ‘packages’ folder. But that makes NuGet a bit less useful.

Another side issue I've noticed is with having the two profiles (‘Mono for Android’ and ‘MonoTouch’):
When you create a PCL project you cannot select 'Windows Phone 7.5 and higher' without also having the two profiles selected.
Without these two profiles selected, Visual Studio will automatically select ‘Windows Phone 7 and higher’ profile.

(Off topic about Json.NET: Json.NET happens to have a Xamarin component available in the http://components.xamarin.com/view/json.net/ but Xamarin currently does not have the Component feature for PCLs).


I am eager to hear other opinions, experiences, solutions, thoughts.

Wednesday, September 18, 2013

A first implementation of alert dialog support in Xamarin + MVVMCross


Update: You can use this MvvmCross plugin: https://github.com/brianchance/MvvmCross-UserInteraction
              At this moment however, the plugin doesn't have an implementation for Windows Phone and Windows Store, it's only for Android and iOS.

The implementation steps:
#1. In the Core PCL project, have the dialog interface declared in IDialogService.cs.
namespace MyApp.Core.Services
{
    public interface IDialogService
    {
        Task<bool?> ShowAsync(string message, string title, string OKButtonContent, string CancelButtonContent);
    }
}

#2. In the platform specific project, implement the dialog support. Example for Android:

namespace MyApp.Droid.Services
{
    public class DialogService : IDialogService
    {
        public Task<bool?> ShowAsync(string message, string title, string OKButtonContent, string CancelButtonContent)
        {
            var tcs = new TaskCompletionSource<bool?>();

            var mvxTopActivity = Mvx.Resolve<IMvxAndroidCurrentTopActivity>();
            AlertDialog.Builder builder = new AlertDialog.Builder(mvxTopActivity.Activity);
            builder.SetTitle(title)
                   .SetMessage(message)
                   .SetCancelable(false)
                   .SetPositiveButton(OKButtonContent, (s, args) =>
                    {
                        tcs.SetResult(true);
                    })
                   .SetNegativeButton(CancelButtonContent, (s, args) =>
                   {
                       tcs.SetResult(false);
                   });

            builder.Create().Show();
            return tcs.Task;
        }
    }
}


#3.
Still in the platform specific project, register the service:

namespace MyApp.Droid
{
    public class Setup : MvxAndroidSetup
    {
        public Setup(Context applicationContext) : base(applicationContext)
        {
        }

        protected override void InitializeLastChance()
        {
            Mvx.RegisterSingleton<IDialogService>(new DialogService());
            base.InitializeLastChance();
        }
    }
}

#4. In the view models, here is how I can call the display of the dialog:


void async DeleteUser()
{
    var result = await Mvx.Resolve<IDialogService>().Show("Are you sure you want to delete selected user?", "Confirmation", "OK", "Cancel");
    if(result == true)
    {
        // delete user...
    }
}


This is a first implementation of showing dialogs. There’s a lot of possible parameterization / customization, but it needs to take into account the capabilities and behavior of all platforms.
In tests, the IDialogService implementation obviously does not call showing a dialog, it does nothing.

One interesting discussion I had with Greg Shackles is about using a different approach than what I showed here: have the view full responsibility of displaying the dialog and communicate with view model using commands \ methods, etc. I understand the idea but I don't have a very clear way of doing this so until I see all the issues I think I will use this solution.

Localization in Xamarin + MVVMCross



Here is how I implement localization in my Xamarin MVVMCross (what a great pair!) app:
#1. In the Core PCL project, create resource (project properties \ Resources) and use editor to enter all localizable strings in the app (or, you might use localization tools which produce the .resx file).
     Make sure to select Public visibility for the members of the generated Resources class.image
     For the resource name, I usually use the actual string + 'Text':
         'Username' –> UsernameText. 
         'Change password' –> ChangePasswordText.
     For long strings, I try to give it a short distinctive name  + usage + 'Text':
         'NewAppVersionAvailableMessageText'  -> 'A new version of the application is currently available. Would you like to download it?'
         'DeleteUserConfirmationText'  ->  'Are you sure you want to delete selected user?'
#2. I have a BaseViewModel class derived from MvxViewModel serving as a base for all my view models. It uses an indexer to get the translated string value based on an index resource value  
public class ViewModelBase : MvxViewModel
{
    public string this[string index]
    {
        get
        {
            return Resources.ResourceManager.GetString(index);
        }
    }

#3.
(for Android, but the idea is similar to other platforms too) In the layout, I am using MVVMCross binding to bind the controls to the view model’s indexer and pass the resource name:

<TextView local:MvxBind="Text [UsernameText]"
          android:layout_width="wrap_content"
          android:layout_height="wrap_content" />

At runtime, because of the MVVMCross binding between the TextView’s Text property and view model indexer, the Text property will call the view model’s indexer using the ‘UsernameText’ as index.
This in turn calls ResourceManager.GetString which returns the localized string.

This setup works great. I haven’t yet tried it on all the platforms but it makes sharing a single set of localized strings. Also, the resource strings can be referenced by the statically typed properties of the Resources class.

If the application needs to switch the language at runtime, it should be enough to tell the view model to notify its bound controls to refresh their values. I haven’t tried it yet, but viewModel.RaisePropertyChanged(string.Empty) should work.

There are different approaches to localization, here are few links:
N=21 - Internationalisation - i18n - N+1 Days of MvvmCros (using the MVMCross plugin) 
Using resx-files for localization in MvvmCross (mentioned in the video)
http://danielvaughan.org/post/Generating-Localized-Resources-in-Mono-for-Android-Using-T4.aspx (interesting ideas)

I am happy to hear your thoughts on this approach.

Monday, June 03, 2013

Issues when deploying a release version of a Xamarin app made with MVVMCross on a device (Android)

First, you can send to someone the .apk file representing the app and he can install it on the device.
There are few deployment options:
  • Via a Website – A Xamarin.Android application can be made available for download on a website, from which users may then install the application by clicking on a link.
  • By e-mail – It is possible for users to install a Xamarin.Android application from their e-mail. The application will be installed when the attachment is opened with an Android-powered device.
  • Through a Market – There are several application marketplaces that exist for distribution, such as Google Play or Amazon App Store for Android.
See more here http://docs.xamarin.com/guides/android/deployment,_testing,_and_metrics/publishing_an_application
I am trying to deploy the app on a device by sending the .apk file to someone to test it on his device.
First, I need to compile the app in Release mode and sign it. When compiling, Xamarin produces a signed version of the app.
In the \bin\Release folder, there is yourapp.apk and yourapp-Signed.apk files.

Second, I encountered different problems when running the app in Release mode on the device, there were a number of issues with MVVMCross.

The issues are related to the Xamarin linker. If you look to the build properties of the Xamarin app (In Xamarin Studio, that's project Options \ Build \ Android Build \ General tab), there are few linker options:

  1. Don't Link
  2. Link SDK Assemblies
  3. Link All Assemblies

Linking is described in Xamarin docs: http://docs.xamarin.com/guides/android/advanced_topics/linking
'Don't Link' option produces the largest app files, linker not being enabled. The app will definitely work without an issue.
Issues start appearing with the two options, becausue with these two options, the linker is enabled.
The issues appear at runtime, for example I was getting MvvMCross errors written in the application output, mentioning about bindings / events not working right.

When using the 'Don't link' linker option, the app size was 20 MB! When switching to 'Link SDK Assemblies', it was 7 MB!
The idea is to use 'Link SDK Assemblies' linker option and do the necessary to make linker do the right thing.

A solution is to force the linker include code from MVVMCross, using a dummy class.

class LinkerIncludePlease
{
private void IncludeVisibility(View widget)
{
widget.Visibility = widget.Visibility + 1;
}
private void IncludeClick(View widget)
{
widget.Click += (s,e) => {};
}
private void IncludeRelativeLayout(RelativeLayout relativeLayout)
{
relativeLayout.Click += (s, e) => { };
}
public void Include(INotifyCollectionChanged changed)
{
changed.CollectionChanged += (s,e) => { var test = string.Format("{0}{1}{2}{3}{4}", e.Action,e.NewItems, e.NewStartingIndex, e.OldItems, e.OldStartingIndex); } ;
}
}

 More info here:
http://stackoverflow.com/questions/16924178/issues-with-mvvmcross-and-linking-on-android/16924320?noredirect=1#comment24433662_16924320
http://stackoverflow.com/questions/11349864/mvvmcross-monotouch-fail-to-bind-properties-on-a-real-ipad-but-it-works-on-th (including the info and links from comments)
http://spouliot.wordpress.com/2011/08/11/when-to-link-monotouch-applications/

Note there are other options, in the same Build tab: Use shared Mono runtime and Fast assembly deployment. These are not meant to be used on Release (if you have over the options, the explanation is pretty good and you should get a good idea of how they work).



MvvmCross Android app with dynamic fragments

It’s not much different than implementing the app with Java, except using the MvvmCross MvxXXXX classes.
Let’s do a simple exercise: have an activity loading a fragment by code behind.
Here’s the code we need:

1. a MvxFragmentActivity derived class.  It is the corresponding to Android’s FragmentActivity class

[Activity(Label = "View for FirstViewModel")]
public class FirstView : MvxFragmentActivity
{
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
SetContentView(Resource.Layout.FirstView);
this.AddChildView ();
}
void AddChildView()
{
var childView = new ChildView () {
ViewModel = new ChildViewModel()
};
var fm = this.SupportFragmentManager;
var ft = fm.BeginTransaction ();
ft.Add (Resource.Id.childViewHost, childView, "childView");
ft.Commit ();
}


2. a corresponding Android layout for it: FirstView.axml
  it needs to have a host widget for the fragment, let’s say a FrameLayout called childViewHost
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:local="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<FrameLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="@+id/childViewHost" />
</FrameLayout >

 
  3. a MvxFragment derived class. Note the MvvmCross BindingInflate method which makes binding work in the fragment
public class ChildView : MvxFragment
{
public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
var ignored = base.OnCreateView(inflater, container, savedInstanceState);
return this.BindingInflate(Resource.Layout.ChildView, null);
}
}
4. a corresponding Android layout  for it: ChildView.axml. Let’s have a textbox bound to the ViewModel’s property
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:local="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">

<TextView
local:MvxBind="Text Hello"
android:textAppearance="?android:attr/textAppearanceSmall"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/textView2" />
</LinearLayout>



Wednesday, May 22, 2013

First app with Xamarin Android and MVVMCross – gotchas

1. After installing Xamarin, create a new ‘Visual C# / Android / Android Application’ using Visual Studio, say ‘DemoApp.Android’ but have the solution called ‘DemoApp’.

2. Add an ‘Visual C# / Windows / Portable Class Library’ called DemoApp.Core.
   First select ‘Windows Phone 7.5 and later’ and then ‘Mono Android’ and ‘MonoTouch’. Note that Xamarin frameworks become available only if you select ‘Windows Phone 7.5 and later’

3. Make sure you have the latest NuGet installed. For this, in Visual Studio, go to Help \ About Microsoft Visual Studio.
image

4. Using NuGet, search for ‘mvvmcross’ and add ‘MVVMCross Hot Tuna Starter Pack’ to BOTH the DemoApp.Android and DemoApp.Core
In the DemoApp.Android, it creates a SplashScreen activity and layout, and a layout and a view in FirstView.axml and FirstView.cs respectively.
In the DemoApp.Core, it creates a FirstViewModel view model.

6. In DemoApp.Android, delete the Activity1.cs and Resources/Layout/Main.axml.

7. Run. It should run OK at this point.