Aiko West
Aiko West

Reputation: 791

How to pass EditText.TextChanged Event to Parent?

Usually I am using this code to handle the TextChanged from my EditText

EditText myEditText = new EditText(Context);
myEditText.TextChanged += (sender, e) => { /* do something */ };

Now, I defined my own LinearLayout, which holds an EditText. My question is, how can I pass the TextChanged event from the EditText to a method of the LinearLayout, so I can call

MyLinearLayout.TextChanged instead of MyLinearLayout.editText.TextChanged

public class MyLinearLayout : LinearLayout
{
    private EditText editText;

    public MyLinearLayout(Context context) : base(context)
    {
        LayoutParameters = new LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.WrapContent);

        editText = new EditText(context);
        AddView(_editText);
    }


    // some method like this
    public event EventHandler<Android.Text.TextChangedEventArgs> TextChanged
    {
        // just passes the _editText.TextChanged
    }
}

Upvotes: 0

Views: 107

Answers (1)

Lucas Zhang
Lucas Zhang

Reputation: 18861

You could define an EventHandler in custom LinearLayout , and invoke it when EditText's TextChanged evented been invoked

using System;
using Android.Content;
using Android.Runtime;
using Android.Text;
using Android.Util;
using Android.Views;
using Android.Widget;
using Android.Graphics;
namespace App11
{
    public class MyLinearLayout : LinearLayout
    {
        private EditText editText;               

        public MyLinearLayout(Context context, IAttributeSet attrs) : base(context, attrs)
        {
            LayoutParameters = new LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.WrapContent);

            editText = new EditText(context);

            editText.TextChanged += EditText_TextChanged;

            AddView(editText, LayoutParameters);
        }



        private void EditText_TextChanged(object sender, Android.Text.TextChangedEventArgs e)
        {
            TextChanged.Invoke(this, e);
        }


        public event EventHandler<TextChangedEventArgs> TextChanged;
    }
}
MyLinearLayout myLinearLayout = FindViewById<MyLinearLayout>(Resource.Id.myLinearLayout);
myLinearLayout.TextChanged += MyLinearLayout_TextChanged;

private void MyLinearLayout_TextChanged(object sender, TextChangedEventArgs e)
{
  Console.WriteLine(e.Text);
}

Upvotes: 1

Related Questions