Last active
June 10, 2018 19:35
Android: Catch Back Button on EditText
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 System; | |
using Android.Content; | |
using Android.Graphics; | |
using Android.Util; | |
using Android.Widget; | |
namespace MyProject.Droid.Controls | |
{ | |
public class CustomEditText : EditText | |
{ | |
public event EventHandler BackPressed; | |
public CustomEditText(Context context) | |
: this(context, null) | |
{ | |
} | |
public CustomEditText(Context context, IAttributeSet attributes) | |
: this(context, attributes, Resource.Attribute.titleTextStyle) | |
{ | |
} | |
public CustomEditText(Context context, IAttributeSet attributes, int defStyle) | |
: base(context, attributes, defStyle) | |
{ | |
var a = context.ObtainStyledAttributes(attributes, Resource.Styleable.Fonts); | |
var font = a.GetString(Resource.Styleable.Fonts_customFont); | |
this.SetBackgroundColorFilter(context); | |
this.SetCustomFont(font); | |
a.Recycle(); | |
} | |
private void SetBackgroundColorFilter(Context context) | |
{ | |
//this.Background.SetColorFilter(context.Resources.GetColor(Resource.Color.appBorderColor), PorterDuff.Mode.SrcAtop); | |
} | |
public void SetCustomFont(string asset) | |
{ | |
Typeface typeface = null; | |
try | |
{ | |
typeface = Typeface.CreateFromAsset(Context.Assets, asset); | |
if (typeface == null) | |
{ | |
Console.WriteLine("No typeface found for asset: " + asset); | |
return; | |
} | |
} | |
catch | |
{ | |
Console.WriteLine("Could not load typeface from asset: " + asset); | |
return; | |
} | |
var style = typeface?.Style ?? TypefaceStyle.Normal; | |
this.SetTypeface(typeface, style); | |
} | |
public override bool OnKeyPreIme([GeneratedEnum] Keycode keyCode, KeyEvent e) | |
{ | |
if (e.KeyCode == Keycode.Back && e.Action == KeyEventActions.Up) | |
{ | |
BackPressed?.Invoke(this, new EventArgs()); | |
} | |
return base.OnKeyPreIme(keyCode, e); | |
} | |
} | |
} |
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
/* ... in the view ... */ | |
public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) | |
{ | |
// ... | |
editText = FindViewById<CustomEditText>(Resource.Id.MyEditText); | |
editText.BackPressed += (s, e) => | |
{ | |
// <insert code here> | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uses the same CustomEditText that I created for having custom fonts in the EditText.