首页 > 解决方案 > How to define Entry User name/Password/FirstName/LastName in Xamarin From so android will auto fill it?

问题描述

I know Android from certain version can detect the field is a field to enter User Name/ Password / Last Name / First Name?

But what I need to do in Xamarin Form for that to be happen?

标签: androidxamarinxamarin.formsxamarin.android

解决方案


In API-27+ (Oreo+) it is preferable to use an AutoCompleteTextView with the Autofill Framework but not absolutely needed.

Note: Xamarin.Forms currently (up to 3.0.x) does not implement the Android native AutoCompleteTextView in any of the built-in Forms' controls but you can use just an Entry control (implemented as a TextView on Android).

On either your Android-based TextView or AutoCompleteTextView you should programmically call:

* SetAutofillHints
* ImportantForAutofill

Example:

usernameView.SetAutofillHints(new string[2] {"emailAddress", "userName"});
usernameView.ImportantForAutofill = ImportantForAutofill.Yes;

Note: In native Xamarin.Android you can just set these attributes in the AXML layout.

re: https://codelabs.developers.google.com/codelabs/optimize-autofill/#0

Note: Review the Android docs for the basics on what the AutofillHints strings should be set to...

In Xamarin.Forms you can do this via a custom renderer or an effect:

Xamarin.Forms Auto-fill Android Effect Example:

[assembly: ResolutionGroupName("EffectsAutoFill")]
[assembly: ExportEffect(typeof(AutoFillUserNameEffect), "AutoFillUserNameEffect")]

namespace Effects
{
    public class AutoFillUserNameEffect : PlatformEffect
    {
        protected override void OnAttached()
        {
            var textView = (TextView)Control;
            if (Build.VERSION.SdkInt >= BuildVersionCodes.O)
            {
                textView.SetAutofillHints(new string[2] { "emailAddress", "userName" });
                textView.ImportantForAutofill = ImportantForAutofill.Yes;
            }

        protected override void OnDetached()
        {
        }
    }
}

Usage:

emailEntry.Effects.Add(Effect.Resolve("EffectsAutoFill.AutoFillUserNameEffect"));

Your Forms' app will now trigger whatevery auto-fill service the user have enabled on their device: Google, LastPass, etc.... (of course it is up to the user to enabled one or not...)

Output:

enter image description here


推荐阅读