[Introduction]
This case will implement a random password generator. Users can customize the length of the password and the type of characters it contains (uppercase letters, lowercase letters, numbers, special characters), and finally generate the password by clicking a button with one-click copying functionality.
[Environmental Preparation]
-Operating system: Windows 10
-Development Tools: DevEco Studio NEXT Beta1 Build Version: 5.0.3.806
-Target device: Huawei Mate60 Pro
-Development language: ArkTS
-Framework: ArkUI
-API version: API 12
[Project structure]
This project consists mainly of an entry componentPasswordGeneratorPage
and an observable classPasswordOption
Ingredients.PasswordOption
class is used to define the password options, including the name of the option, the character set, whether it is checked, and the status of whether it is enabled.
1. PasswordOption class
@ObservedV2 class PasswordOption { name: string; // Option name characters: string; // The character set for this option @Trace selected: boolean = true; // Whether or not it is selected, default is true. @Trace enabled: boolean = true; // Enable or not, default is true constructor(name: string, characters: string) { = name; = characters; } }
2. PasswordGeneratorPage component
This component contains password options, password length settings, the ability to generate passwords and copy passwords.
@Entry @Component struct PasswordGeneratorPage { @State options: PasswordOption[] = [ new PasswordOption("Capital letters.", "ABCDEFGHIJKLMNOPQRSTUVWXYZ"), new PasswordOption("Lowercase letters.", "abcdefghijklmnopqrstuvwxyz"), new PasswordOption("Numbers.", "0123456789"), new PasswordOption("Special characters", "!@#$%^&*()_+-=[]{}|;:,.<>?"), ]; @State passwordLength: number = 10; // Default password length @State generatedPassword: string = ''; // Generated password // Methods for generating passwords generatePassword() { let characterSet = ''; for (let option of ) { if () { characterSet += ; } } let password = ''; for (let i = 0; i < ; i++) { const randomIndex = (() * ); password += characterSet[randomIndex]; } = password; } // Copying to the Clipboard copyToClipboard(text: string) { const pasteboardData = (pasteboard.MIMETYPE_TEXT_PLAIN, text); const systemPasteboard = (); (pasteboardData); ({ message: 'Copied' }); } // Methods for building page layouts build() { // Page layout code... } }
Functional realization
1. Generation of passwords
Users can select different character sets (uppercase letters, lowercase letters, numbers, special characters) and set the password length. After clicking the "Generate Password" button, the system will generate a random password based on the selected options.
2. Copying passwords
The generated password can be copied to the clipboard by clicking the "Copy" button and the user will receive a "Copied" message.
user
The user interface has a clean design and contains a header, password length setting, option selection, generate password button and copy button. By dynamically generating the option UI elements, users can easily select the desired character set.
summarize
This article describes how to use Hongmeng NEXT framework to develop a random password generator . Through a simple code implementation, we can quickly build a practical function. Hope this case can provide inspiration and help for your development.
[complete code]
// Import Clipboard Service import { pasteboard } from '@'; // Importing a pop-up alert service import { promptAction } from '@'; // Use a decorator to define an observable class for the password option @ObservedV2 class PasswordOption { name: string; // Option name characters: string; // The character set for this option // Defines whether the checkbox is selected, defaults to true. @Trace selected: boolean = true; // Define whether to enable it, defaults to true @Trace enabled: boolean = true; // Constructor to initialize name and characters. constructor(name: string, characters: string) { = name; = characters; } } // Define an entry component using a decorator @Entry @Component struct PasswordGeneratorPage { // Define an array of password options @State options: PasswordOption[] = [ new PasswordOption("Capital letters.", "ABCDEFGHIJKLMNOPQRSTUVWXYZ"), new PasswordOption("Lowercase letters.", "abcdefghijklmnopqrstuvwxyz"), new PasswordOption("Numbers.", "0123456789"), new PasswordOption("Special characters", "!@#$%^&*()_+-=[]{}|;:,.<>?"), ]; // Define the password length status, defaults to 10. @State passwordLength: number = 10; // Base spacing @State baseSpacing: number = 30; // Generated password @State generatedPassword: string = ''; // Whether to enable the copy button @State isCopyButtonEnabled: boolean = false; // Theme colors @State primaryColor: string = '#71dec7'; // Font color @State fontColor: string = "#2e2e2e"; // Methods for generating passwords generatePassword() { let characterSet = ''; // Initialize the character set // Iterate over all options and add to the character set if the option is selected for (let option of ) { if () { characterSet += } } let password = ''; // Initialize the password string // Generate random passwords based on password length for (let i = 0; i < ; i++) { const randomIndex = (() * ); password += characterSet[randomIndex]; } = password; // Update the generated password } // Copying to the Clipboard copyToClipboard(text: string) { const pasteboardData = (pasteboard.MIMETYPE_TEXT_PLAIN, text); // Create clipboard data const systemPasteboard = (); // Get the system clipboard (pasteboardData); // Put the data on the clipboard ({ message: 'Copied' }); // Display a prompt that the copy was successful } // Ways to check the status of an option selection checkOptionsSelection() { let selectedCount = 0; // Record the number of options that have been checked let lastSelectedIndex = 0; // Record the index of the last selected option // Iterate over all options for (let i = 0; i < ; i++) { [i].enabled = true; // Enable all options by default if ([i].selected) { lastSelectedIndex = i; // Update the index of the last selected option selectedCount++; // Increase the check mark count } } // If only one option is checked, disable the option to prevent it from being unchecked if (selectedCount === 1) { [lastSelectedIndex].enabled = false; } } // Methods for building page layouts build() { Column() { // Title bar Text("Random password generation") .width('100%')// Set the width to 100% .height(54)// Set the height to 54 .fontSize(18)// Setting the font size .fontWeight(600)// Set the font thickness .backgroundColor()// Set the background color .textAlign()// Set the text to be center-aligned .fontColor(); // Set the font color // Password length setting section Column() { Row() { Text(`Password length:`)// Password length labels .fontWeight(600) .fontSize(18) .fontColor(); Text(`${}`)// Display the current password length .fontWeight(600) .fontSize(18) .fontColor(); } .margin({ top: `${}lpx`, left: `${}lpx` }); // Slider to set password length Row() { Text('4').fontColor().width(20); Slider({ value: , // Current value min: 4, // Minimum value max: 32, // Maximum value style: // Slider Style }) .layoutWeight(1)// Layout weights .blockColor()// Slider color .trackColor('#EBEBEB')// track color .trackThickness(30)// Track thickness .blockSize({ width: 55, height: 55 })// Slider size .selectedColor()// Selected colors .onChange((value: number, mode: SliderChangeMode) => { = value; // Update password length ('value:' + value + 'mode' + ); // Print the log }); Text('32').fontColor().width(20); }.margin({ left: `${}lpx`, right: `${}lpx`, top: `${}lpx`, }); // Option Settings section Text('Options') .fontWeight(600) .fontSize(18) .fontColor() .margin({ left: `${}lpx`, top: `${}lpx`, bottom: `${}lpx` }); // Dynamically generate UI elements for each option ForEach(, (option: PasswordOption, index: number) => { Row() { Text()// Option name .fontWeight(400) .fontSize(16) .fontColor() .layoutWeight(1); Toggle({ type: , isOn: })// Toggle button .width('100lpx') .height('50lpx') .enabled()// Whether to enable switching .selectedColor() .onChange((isOn: boolean) => { = isOn; // Update option status (); // Check option selection status }); } .width('100%') .padding({ left: `${}lpx`, right: `${}lpx`, top: `${ / 3}lpx`, bottom: `${ / 3}lpx` }) .hitTestBehavior() .onClick(() => { if () { = !; // Toggle option status } }); }); // Generate password button Text('Generate Password') .fontColor() .backgroundColor() .height(54) .textAlign() .borderRadius(10) .fontSize(18) .width(`${650 - * 2}lpx`) .margin({ top: `${}lpx`, left: `${}lpx`, right: `${}lpx`, bottom: `${}lpx` }) .clickEffect({ level: , scale: 0.8 })// Click effect .onClick(() => { (); // Generate a password }); } .width('650lpx') .margin({ top: 20 }) .backgroundColor() .borderRadius(10) .alignItems(); // Display the generated password Column() { Text(`Password results:`) .fontWeight(600) .fontSize(18) .fontColor() .margin({ top: `${}lpx`, left: `${}lpx`, }); Text(`${}`)// Display the generated password .width('650lpx') .fontColor() .fontSize(18) .textAlign() .padding({ left: 5, right: 5 }) .margin({ top: `${ / 3}lpx` }); // Copy button Text('Copy') .enabled( ? true : false)// Enable the copy button only if a password has been generated .fontColor() .backgroundColor() .height(54) .textAlign() .borderRadius(10) .fontSize(18) .width(`${650 - * 2}lpx`) .margin({ top: `${}lpx`, left: `${}lpx`, right: `${}lpx`, bottom: `${}lpx` }) .clickEffect({ level: , scale: 0.8 }) .onClick(() => { (); // Copy the password }); } .width('650lpx') .backgroundColor() .borderRadius(10) .margin({ top: `${}lpx` }) .alignItems(); } .height('100%') .width('100%') .backgroundColor("#f2f3f5"); // Page background color } }