Skip to content

Instantly share code, notes, and snippets.

@steveevers
Last active June 10, 2018 19:35
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save steveevers/385bea5d86db9f744a7396cd4e19b9b7 to your computer and use it in GitHub Desktop.
Android: Catch Back Button on EditText
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);
}
}
}
/* ... 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>
};
}
@steveevers
Copy link
Author

Uses the same CustomEditText that I created for having custom fonts in the EditText.

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