Skip to content

Instantly share code, notes, and snippets.

@geirsagberg
Last active August 29, 2015 14:14
Show Gist options
  • Save geirsagberg/8c1a2f6d4596f054dfcb to your computer and use it in GitHub Desktop.
Save geirsagberg/8c1a2f6d4596f054dfcb to your computer and use it in GitHub Desktop.
FocusTextBinding for Android
// From http://stackoverflow.com/a/19221385/500976
// In Setup.cs:
// protected override void FillTargetFactories(IMvxTargetBindingFactoryRegistry registry)
// {
// base.FillTargetFactories(registry);
// registry.RegisterCustomBindingFactory("FocusText", (EditText view) => new FocusTextBinding(view));
// }
using System;
using Android.Views;
using Android.Widget;
using Cirrious.MvvmCross.Binding;
using Cirrious.MvvmCross.Binding.Droid.Target;
public class FocusTextBinding : MvxAndroidTargetBinding
{
private bool _subscribed;
protected EditText TextField
{
get { return Target as EditText; }
}
public override Type TargetType
{
get { return typeof (string); }
}
public override MvxBindingMode DefaultMode
{
get { return MvxBindingMode.TwoWay; }
}
public FocusTextBinding(object target)
: base(target)
{
}
protected override void SetValueImpl(object target, object value)
{
if (TextField == null) return;
value = value ?? string.Empty;
TextField.Text = value.ToString();
}
public override void SubscribeToEvents()
{
if (TextField == null) return;
TextField.FocusChange += HandleLostFocus;
_subscribed = true;
}
private void HandleLostFocus(object sender, View.FocusChangeEventArgs e)
{
if (TextField == null) return;
if (!e.HasFocus)
FireValueChanged(TextField.Text);
}
protected override void Dispose(bool isDisposing)
{
base.Dispose(isDisposing);
if (!isDisposing) return;
if (TextField != null && _subscribed) {
TextField.FocusChange -= HandleLostFocus;
_subscribed = false;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment