Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

Copy link
Owner Author

@steveevers steveevers commented Jun 10, 2018

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