五笔打字通主页
先创建一个 chanku.ets文件,装封闭好的文件写入,内容如下:
//首选项库封闭模块,调用此模块,就可以用一句代码来读取或写入数据
import { preferences } from '@kit.ArkData'
export class ChanKuClass {
//默认的仓库名称
static mo_store: string = 'mo_store'
static mo_key: string = 'mo_key'
static mo_value: string = 'mo_value'
//创建仓库:没有就新建,有了就获取,源码来自 wb98.com
static getStore(context: Context, storeName: string) {
const store = preferences.getPreferencesSync(context, {
name: storeName || ChanKuClass.mo_store
})
return store
}
//仓库中添加数据
static async setToken(context: Context, storeName: string, key: string, value: string) {
//获取创建的仓库
const store = ChanKuClass.getStore(context, storeName)
//添加数据:键,值
// await store.put(key || ChanKuClass.mo_key, value || ChanKuClass.mo_value)
await store.putSync(key || ChanKuClass.mo_key, value)
//将数据写入磁盘
await store.flush()
}
//获得仓库中的数据
static getToken(context: Context, storeName: string, key: string) {
const store = ChanKuClass.getStore(context, storeName)
const tokey = store.getSync(key, '')
return tokey
}
}下面是调用上述文件,来读取和写入设置值的代码:
import { ChanKuClass } from './chanku';
//此模块是首选项演示--源码来自 wb98.com
@Entry
@Component
struct Page12 {
@State txt1: string = '30'
build() {
Column({ space: 20 }) {
Text('在下面输入要设置的值')
.fontSize(20)
.fontWeight(700)
TextInput({ placeholder: '请输入数字', text: '30' })
.type(InputType.Number)
.backgroundColor(Color.Pink)
.width(200)
.onChange((value) => {
this.txt1 = value
})
Button('写入')
.onClick(() => {
ChanKuClass.setToken(getContext(), 'set1', 'fontdx', this.txt1)// 仓库名,键名,值
})
Button('读出')
.onClick(() => {
const xx = ChanKuClass.getToken(getContext(), 'set1', 'fontdx')//仓库名,键名
AlertDialog.show({
message: '读出结果:' + xx
})
})
}
.height('100%')
.width('100%')
}
}不要忘记,测试时,要用真机或模拟器来测试。
来源:济亨网
本文链接:https://www.wb98.com/post/372.html