Wednesday, October 17, 2012

Creating custom views is easy to do...

This answer came from a question about creating custom view behaviour inside a list in MvvmCross for MonoDroid - http://stackoverflow.com/questions/12934654/how-to-create-views-actions-listener-for-mvxitemtemplate


---

Creating custom views is easy to do...

namespace Angevelle.App1.UI.Droid.Controls
{
    public class MyText : EditText
    {
        public MyText(Context context, IAttributeSet attrs)
            : base(context, attrs)
        {
            this.EditorAction += OnEditorAction;
        }

        private void OnEditorAction(object sender, EditorActionEventArgs editorActionEventArgs)
        {
            if (editorActionEventArgs.ActionId == ImeAction.Done)
            {
                // this code not tested - but something like this should work
                var imm = (InputMethodManager)Context.GetSystemService(Context.InputMethodService);
                imm.HideSoftInputFromWindow(WindowToken, 0);
            }
        }
    }
}

Then you can use that View in your AXML just as you do Android or Mvx views:

<angevelle.app1.ui.droid.controls.MyText
         android:layout_height=....
     />

If you are finding angevelle.app1.ui.droid.controls too verbose, then you could shorten this using an abbreviation in setup.cs:

    protected override IDictionary ViewNamespaceAbbreviations
    {
        get
        {
            var abbreviations = base.ViewNamespaceAbbreviations;
            abbreviations["Abv"] = "angevelle.app1.ui.droid.controls";
            return abbreviations;
        }
    }
then you can just use:

<Abv.MyText
android:layout_height=.... />

No comments:

Post a Comment