Last active
September 28, 2021 18:14
-
-
Save wcoder/42e1ef810b9e709337e8 to your computer and use it in GitHub Desktop.
Example of formatted input for EditText using Xamarin Android
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)); | |
} | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks.great example