Search code examples
c#xamarinxamarin.formsxamarin.iosxamarin.android

Entry show and hide password


I want an entry to have an icon before the placeholder, and a icon in the end of the entry, to show and hide the text in the entry, i had an entry with the show and hide icon using this tutorial: https://www.techierathore.com/2017/09/xamarin-forms-tip-implement-show-hide-password-using-effects/

But now I want to have icons before the entry too, I can do that with this tutorial: https://xamgirl.com/image-entry-in-xamarin-forms/

But if i add the effect of the first tutorial to the custom entry, only the and hide/show icon shows up.

Is possible to do what i want?


Solution

  • You could use editText.SetCompoundDrawablesRelativeWithIntrinsicBounds() to add both icon.

    SetCompoundDrawablesRelativeWithIntrinsicBounds takes four parameters for start, top, end, and bottom drawable. In the first tutorial, the hide/show icon is added to the end, you can change the first parameter from 0 to your drawable. There are three places need to modify.

    For example:

    public class ShowHidePassEffect : PlatformEffect
    {
        protected override void OnAttached()
        {
            ConfigureControl();
        }
    
        protected override void OnDetached()
        {
        }
    
        private void ConfigureControl()
        {
            EditText editText = ((EditText)Control);
            editText.SetCompoundDrawablesRelativeWithIntrinsicBounds(Resource.Drawable.Password, 0, Resource.Drawable.ShowPass, 0);
            editText.SetOnTouchListener(new OnDrawableTouchListener());
        }
    }
    
    public class OnDrawableTouchListener : Java.Lang.Object, Android.Views.View.IOnTouchListener
    {
        public bool OnTouch(Android.Views.View v, MotionEvent e)
        {
            if (v is EditText && e.Action == MotionEventActions.Up)
            {
                EditText editText = (EditText)v;
                if (e.RawX >= (editText.Right - editText.GetCompoundDrawables()[2].Bounds.Width()))
                {
                    if (editText.TransformationMethod == null)
                    {
                        editText.TransformationMethod = PasswordTransformationMethod.Instance;
                        editText.SetCompoundDrawablesRelativeWithIntrinsicBounds(Resource.Drawable.Password, 0, Resource.Drawable.ShowPass, 0);
                    }
                    else
                    {
                        editText.TransformationMethod = null;
                        editText.SetCompoundDrawablesRelativeWithIntrinsicBounds(Resource.Drawable.Password, 0, Resource.Drawable.HidePass, 0);
                    }
                    return true;
                }
            }
            return false;
        }
    }
    

    And the result is:
    enter image description here