HarmonyOS 鸿蒙Next登录输入框智能提示历史登录账号

HarmonyOS 鸿蒙Next登录输入框智能提示历史登录账号

你好,我想实现登录输入框只能提示历史登录账号的功能,不知道采用什么控件去实现,InputText控件有个属性InputTypeUSER_NAME,看起来可以使用,不过要求在已启用密码保险箱的情况下,才支持用户名、密码的自动保存和自动填充。

我的问题是:

  1. 能否用InputText控件有个属性InputType的属性去实现该功能,是否有示例demo?不能的话有没有更好的实现方法?
  2. 本人尝试使用menu来模拟效果,然而menu没有生效,示例代码:
@Builder
MyMenu() {
    Menu() {
        MenuItem({
            startIcon: $r("app.media.icon"),
            content: "菜单选项"
        });
        MenuItem({
            startIcon: $r("app.media.icon"),
            content: "菜单选项"
        });
        // ForEach(this.loginHistoryAccounts, (item: string) => { 
        //     MenuItem({
        //         content: item.toString(),
        //     });
        // }, (item: string) => item);
    }.width('90%');
}

build() {
    Row() {}.bindMenu(this.MyMenu);
}

更多关于HarmonyOS 鸿蒙Next登录输入框智能提示历史登录账号的实战教程也可以访问 https://www.itying.com/category-93-b0.html

2 回复

您看一下首选项数据持久化。能否满足您的述求 参考链接:https://developer.huawei.com/consumer/cn/doc/harmonyos-references-V5/js-apis-data-preferences-V5#导入模块

import dataPreferences from '@ohos.data.preferences';
import { BusinessError } from '@ohos.base';
import { DEFAULT } from '@ohos/hypium';
import router from '@ohos.router';

const usernameV: string = "admin";
const passwordV: string = "123456";

//加载等待
async function sleepFunction(): Promise<void> {
    try {
        const result: string = await new Promise((resolve) => {
            setTimeout(() => {
                router.pushUrl({ url: 'pages/Page' });
            }, 1000);
        });
    } catch (e) {
        console.error(`Get exception: ${e}`);
    }
}

@Entry
@Component
struct Index {
    @State message: string = 'Hello World';
    @State username: string = "";
    @State password: string = "";

    private inputAccountValue: string = "";
    private inputPassword: string = "";

    @State flag1: boolean = false;
    @State flag2: boolean = false;

    @StorageLink("preferences") preferences: dataPreferences.Preferences = {} as dataPreferences.Preferences;

    @State loginHistoryAccounts: Array<string> = []

    aboutToAppear() {
        //获取首选项的用户数据
        for (let index = 0; index < this.loginHistoryAccounts.length; index++) {
            let usernameVal: Object = this.preferences.getSync(`username+${index}`, 'default');

            if (this.username == "default") {
                this.username = "";
            } else {
                this.loginHistoryAccounts.map((str) => {
                    if (str !== usernameVal as string) {
                        this.loginHistoryAccounts.push(usernameVal as string)
                    }
                })
            }
        }

        try {
            let passwordVal: Object = this.preferences.getSync('password', 'default');
            this.password = passwordVal as string;

            if (this.password == "default") {
                this.password = "";
            }

            let savePasswordVal: Object = this.preferences.getSync('savePassword', 'default');
            if (savePasswordVal != DEFAULT) {
                this.flag1 = savePasswordVal as boolean;
            }

            let autoLoginVal: Object = this.preferences.getSync('autoLogin', 'default');
            if (autoLoginVal != DEFAULT) {
                this.flag2 = autoLoginVal as boolean;
            }
        } catch (err) {
            let code: number = (err as BusinessError).code;
            let message: string = (err as BusinessError).message;
            console.error(`Failed to get value of 'info'. Code:${code}, message:${message}`);
        }
    }

    onPageShow() {
        //每次显示这个页面时,如果勾选了自动登录,则自动登录
        if (this.flag2 == true && this.username == usernameV && this.password == passwordV) {
            sleepFunction()
        }
    }

    @Builder
    MyMenu() {
        Menu() {
            ForEach(this.loginHistoryAccounts, (item: string) => {
                MenuItem({
                    content: item.toString(),
                }).onClick(() => {
                    this.username = item
                })
            }, (item: string) => item)
        }.width('90%')
    }

    build() {
        Row() {
            Column() {
                Text(this.message)
                    .fontSize(50)
                    .fontWeight(FontWeight.Bold)
                Row() {
                    Text("账号:")
                        .margin({ top: 20 })
                        .fontSize(20)
                    TextInput({ placeholder: '请输入账号', text: this.username })
                        .onChange(value => {
                            this.inputAccountValue = value;
                        })
                        .width(250)
                        .margin({ top: 20 })
                        .type(InputType.USER_NAME)
                    Text('下拉')
                        .width(30).height(30).backgroundColor('#ffdd0a0a').bindMenu(this.MyMenu)
                }
                Row() {
                    Text("密码:")
                        .margin({ top: 20 })
                        .fontSize(20)
                    TextInput({ placeholder: '请输入密码', text: this.password })
                        .onChange(value => {
                            this.inputPassword = value;
                        })
                        .width(250)
                        .margin({ top: 20 })
                        .type(InputType.Password)
                }
                Row() {
                    Row() {
                        Toggle({ type: ToggleType.Checkbox, isOn: this.flag1 })
                            .margin({ top: 13 })
                            .width(20)
                            .onClick(() => {
                                this.flag1 = !this.flag1;
                            })
                        Text("记住密码")
                            .margin({ top: 10 })
                            .fontSize(15)
                    }
                    .margin({ right: 50 })
                    Row() {
                        Toggle({ type: ToggleType.Checkbox, isOn: this.flag2 })
                            .margin({ top: 13 })
                            .width(20)
                            .onClick(() => {
                                if (this.flag2 == false) {
                                    this.flag1 = true;
                                }
                                this.flag2 = !this.flag2;
                            })
                        Text("自动登录")
                            .margin({ top: 10 })
                            .fontSize(15)
                    }
                    .margin({ left: 50 })
                }
                Button('登录')
                    .width(150)
                    .margin({ top: 20 })
                    .onClick(() => {
                        try {
                            //添加数据,写入账号
                            if (this.preferences.hasSync(`username+${this.loginHistoryAccounts.length}`)) {
                                //如果存在就更改账号
                                this.preferences.put(`username+${this.loginHistoryAccounts.length}`, this.inputAccountValue,
                                    (err: BusinessError) => {
                                        if (err) {
                                            console.error(`Failed to put the value of 'username'. Code:${err.code},message:${err.message}`);
                                            return;
                                        }
                                    })
                            } else {
                                // 此处以此键值对不存在时写入数据为例
                                this.preferences.putSync(`username+${this.loginHistoryAccounts.length}`, this.inputAccountValue);
                                this.loginHistoryAccounts.push(this.inputAccountValue)
                            }
                            //点击记住密码,持久化账号密码
                            if (this.flag1 == true) {
                                //写入密码
                                if (this.preferences.hasSync('password')) {
                                    //如果存在就更改密码
                                    this.preferences.put('password', this.inputPassword, (err: BusinessError) => {
                                        if (err) {
                                            console.error(`Failed to put the value of 'password'. Code:${err.code},message:${err.message}`);
                                            return;
                                        }
                                    })
                                } else {
                                    // 键值对不存在时写入数据
                                    this.preferences.putSync('password', this.inputPassword);
                                }
                                //写入记住密码状态
                                if (this.preferences.hasSync('savePassword')) {
                                } else {
                                    // 键值对不存在时写入数据
                                    this.preferences.putSync('savePassword', this.flag1);
                                }
                                //写入自动登录状态
                                if (this.flag2 == true) {
                                    if (this.preferences.hasSync('autoLogin')) {
                                    } else {
                                        // 此处以此键值对不存在时写入数据为例
                                        this.preferences.putSync('autoLogin', this.flag1);
                                    }
                                } else {
                                    this.preferences.deleteSync('autoLogin');
                                }
                            } else {
                                this.preferences.deleteSync('password');
                                this.preferences.deleteSync('savePassword');
                            }
                            //数据持久化
                            this.preferences.flush((err: BusinessError) => {
                                if (err) {
                                    console.error(`Failed to flush. Code:${err.code}, message:${err.message}`);
                                    return;
                                }
                                console.info('Succeeded in flushing.');
                            })
                        } catch (err) {
                            let code = (err as BusinessError).code;
                            let message = (err as BusinessError).message;
                            console.error(`Failed to check the key 'save'. Code:${code}, message:${message}`);
                        }
                        router.pushUrl({ url: 'pages/Page' });
                    }
                }
            }
        }
    }
}

更多关于HarmonyOS 鸿蒙Next登录输入框智能提示历史登录账号的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


在HarmonyOS(鸿蒙)系统中,关于Next登录输入框智能提示历史登录账号的功能,这通常涉及到系统的用户数据管理以及应用层面的输入框组件配置。以下是对该功能的简要说明:

鸿蒙系统在设计时考虑到了用户体验,因此在某些原生应用或遵循鸿蒙设计指南的应用中,登录输入框可能会具备智能提示历史登录账号的功能。这一功能旨在通过缓存用户之前输入的账号信息,提高用户再次登录时的便捷性。

实现该功能的关键在于应用层面的开发。开发者需要在登录界面的输入框组件中启用相关的历史记录功能,并确保这些数据的安全存储与访问。这通常涉及到使用鸿蒙系统提供的数据存储API,以及遵循最佳实践来保护用户隐私。

然而,值得注意的是,并非所有应用都会默认启用此功能,它可能取决于应用的开发者是否选择了实现这一特性。此外,用户也可以在系统设置中管理或清除这些历史记录。

如果用户在特定应用中未看到此功能,可能是因为该应用未实现或禁用了此功能。用户可以尝试更新应用到最新版本,或在应用设置中查找相关选项。

如果问题依旧没法解决请联系官网客服,官网地址是:https://www.itying.com/category-93-b0.html

回到顶部