【使用首選項實現用戶名密碼保存獲取】
打開src/main/ets/entryability路徑下的EntryAbility.ts文件
在
export default class EntryAbility extends UIAbility {onCreate(want, launchParam) {hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onCreate');
下邊添加內容:
// 獲取首選項實例對象,然后將實例對象全局處理,這樣其他文件可以直接使用 preferences.getPreferences(this.context,'account').then(preference=>{// globalThis設置全局變量preference,讓這個變量等于上邊那個preference// 注意:這兩個preference不是一個globalThis.preference=preferenceconsole.log("加載成功");})// 加載不成功catch.catch(reason=>{console.log(reason)})
打開pages文件夾下的index.ets文件:
import preferences from '@ohos.data.preferences' import router from '@ohos.router' @Entry @Component struct Index {@State username: string=''@State password: string=''pref: preferences.PreferencesonPageShow(){this.pref=globalThis.preference// 獲取用戶名跟密碼,如果獲取不到那么為空this.pref.get('username','').then(value=>{this.username=value.toString()})this.pref.get('password','').then(value=>{this.password=value.toString()})}
build() {Row() {Column() {TextInput({placeholder:'請輸入用戶名',text:this.username}).onChange(value=>{this.username=value})TextInput({placeholder:'請輸入密碼',text:this.password}).onChange(value=>{this.password=value})Button('登錄').onClick(()=>{this.pref.put('username',this.username)this.pref.put('password',this.password)this.pref.flush()router.pushUrl({url:'pages/Page2'})})
}.width('100%')}.height('100%')} }
實際效果圖: