Last active
February 7, 2018 15:42
-
-
Save jzeferino/b687405b88e719868e7f68a48b39fe39 to your computer and use it in GitHub Desktop.
Edit text with suffix
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.Content; | |
using Android.Util; | |
using Android.Widget; | |
using Android.Runtime; | |
using System; | |
using Android.Text; | |
namespace Utils | |
{ | |
public class SuffixEditText : EditText | |
{ | |
private string _suffix; | |
private bool _addTextProgrammaticlly; | |
public SuffixEditText(IntPtr a, JniHandleOwnership b) | |
: base(a, b) | |
{ | |
Initialize(); | |
} | |
public SuffixEditText(Context context) | |
: base(context) | |
{ | |
Initialize(); | |
} | |
public SuffixEditText(Context context, IAttributeSet attrs) | |
: base(context, attrs) | |
{ | |
Initialize(); | |
} | |
public SuffixEditText(Context context, IAttributeSet attrs, int defStyle) | |
: base(context, attrs, defStyle) | |
{ | |
Initialize(); | |
} | |
private void Initialize() | |
{ | |
TextChanged += OnTextChanged; | |
} | |
private void AddSuffixIfCan() | |
{ | |
if (!_addTextProgrammaticlly && !string.IsNullOrEmpty(_suffix)) | |
{ | |
if (!Text.EndsWith(_suffix)) | |
{ | |
_addTextProgrammaticlly = true; | |
Text = $"{Text}{_suffix}"; | |
} | |
} | |
else { | |
_addTextProgrammaticlly = false; | |
} | |
} | |
private void OnTextChanged(object sender, TextChangedEventArgs e) | |
{ | |
AddSuffixIfCan(); | |
} | |
public void SetSuffix(string suffix) | |
{ | |
_suffix = suffix; | |
Text = _suffix; | |
} | |
protected override void OnSelectionChanged(int selStart, int selEnd) | |
{ | |
base.OnSelectionChanged(selStart, selEnd); | |
if (_suffix != null) | |
{ | |
if (selStart > Length() - _suffix.Length) | |
{ | |
SetSelection(Length() - _suffix.Length, Length() - _suffix.Length); | |
} | |
else if (selEnd > Length() - _suffix.Length) | |
{ | |
SetSelection(selStart, Length() - _suffix.Length); | |
} | |
} | |
} | |
public string TextWithoutSuffix | |
{ | |
get { return Text.Replace(_suffix, ""); } | |
} | |
public void Reset() | |
{ | |
Text = _suffix; | |
} | |
protected override void Dispose(bool disposing) | |
{ | |
base.Dispose(disposing); | |
if (disposing) | |
{ | |
TextChanged -= OnTextChanged; | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment