Skip to content

Instantly share code, notes, and snippets.

@wcoder
Last active September 28, 2021 18:14
Show Gist options
  • Save wcoder/42e1ef810b9e709337e8 to your computer and use it in GitHub Desktop.
Save wcoder/42e1ef810b9e709337e8 to your computer and use it in GitHub Desktop.
Example of formatted input for EditText using Xamarin Android
using Android.App;
using Android.Widget;
using Android.OS;
using Android.Views;
using Android.Text;
using Android.Runtime;
using Java.Text;
using System.Text.RegularExpressions;
namespace EditTextExample
{
[Activity (Label = "EditTextExample", MainLauncher = true, Icon = "@mipmap/icon")]
public class MainActivity : Activity
{
private EditText _editText;
protected override void OnCreate (Bundle savedInstanceState)
{
base.OnCreate (savedInstanceState);
// Set our view from the "main" layout resource
SetContentView (Resource.Layout.Main);
_editText = FindViewById<EditText> (Resource.Id.myEditField);
_editText.AfterTextChanged += EditText_AfterTextChanged;
}
private void EditText_AfterTextChanged(object sender, AfterTextChangedEventArgs e)
{
var text = e.Editable.ToString();
_editText.AfterTextChanged -= EditText_AfterTextChanged;
var formatedText = PhoneNumberValueConverter(text);
_editText.Text = formatedText;
_editText.SetSelection(formatedText.Length);
_editText.AfterTextChanged += EditText_AfterTextChanged;
}
private static string PhoneNumberValueConverter(string text)
{
var numbers = Regex.Replace(text, @"\D", "");
if (numbers.Length <= 3)
return numbers;
if (numbers.Length <= 7)
return string.Format("{0}-{1}", numbers.Substring(0, 3), numbers.Substring(3));
return string.Format("({0}) {1}-{2}", numbers.Substring(0, 3), numbers.Substring(3, 3), numbers.Substring(6));
}
}
}
@kkarakk
Copy link

kkarakk commented Nov 21, 2018

Thanks.great example

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment