
回复
@Entry
@Component
struct HelloWorld {
build() {
Text('Hello, HarmonyOS Next!')
.fontSize(24)
.fontWeight(FontWeight.Bold)
.fontColor('#007AFF')
}
}
@ohos.data.preferences
进行数据存储。getPreferences
方法初始化Preferences。put
和get
方法存储和读取数据。import storage from '@ohos.data.preferences';
async function initPreferences() {
try {
const preferences = await storage.getPreferences(getContext(this), 'appSettings');
await preferences.put('theme', 'dark');
const savedTheme = await preferences.get('theme', 'light');
console.log('Saved theme:', savedTheme);
} catch (error) {
console.error('Error initializing preferences:', error);
}
}
@ohos.mediaquery
实现响应式布局。matchMediaSync
检测屏幕特性。import mediaQuery from '@ohos.mediaquery';
@Entry
@Component
struct ResponsiveLayout {
@State isTablet: boolean = false;
@State isLandscape: boolean = false;
aboutToAppear() {
const tabletListener = mediaQuery.matchMediaSync('(min-width: 600vp)');
const landscapeListener = mediaQuery.matchMediaSync('(orientation: landscape)');
tabletListener.on('change', (_) => {
this.isTablet = tabletListener.matches;
});
landscapeListener.on('change', (_) => {
this.isLandscape = landscapeListener.matches;
});
}
build() {
Column() {
Text('设备类型: ' + (this.isTablet ? '平板' : '手机'))
Text('屏幕方向: ' + (this.isLandscape ? '横屏' : '竖屏'))
}
}
}
@ohos.window
设置状态栏颜色。import window from '@ohos.window';
@Entry
@Component
struct ThemeSwitcher {
@State isDarkMode: boolean = false;
updateTheme() {
this.isDarkMode = !this.isDarkMode;
this.updateStatusBarColor();
}
updateStatusBarColor() {
const windowClass = window.getLastWindow(getContext(this));
windowClass.setWindowBackgroundColor(this.isDarkMode ? '#1C1C1E' : '#F2F2F7');
}
build() {
Column() {
Text('当前主题: ' + (this.isDarkMode ? '深色' : '浅色'))
Button('切换主题')
.onClick(() => this.updateTheme())
}
}
}
class TodoItem {
id: number;
text: string;
isCompleted: boolean;
createdAt: Date;
constructor(text: string) {
this.id = Date.now();
this.text = text;
this.isCompleted = false;
this.createdAt = new Date();
}
}
@Entry
@Component
struct TaskManager {
@State todoList: TodoItem[] = [];
@State newTodoText: string = '';
addTodo() {
if (this.newTodoText.trim() !== '') {
this.todoList.push(new TodoItem(this.newTodoText.trim()));
this.newTodoText = '';
}
}
toggleTodoComplete(index: number) {
this.todoList[index].isCompleted = !this.todoList[index].isCompleted;
}
deleteTodo(index: number) {
this.todoList.splice(index, 1);
}
build() {
Column() {
TextInput({ placeholder: '添加新任务...', text: this.newTodoText })
.onChange((value: string) => { this.newTodoText = value; })
.width('100%')
.margin({ bottom: 16 })
Button('添加')
.onClick(() => this.addTodo())
List() {
ForEach(this.todoList, (item: TodoItem, index: number) => {
ListItem() {
Row() {
Checkbox(item.isCompleted)
.onChange((value: boolean) => this.toggleTodoComplete(index))
Text(item.text)
}
}
})
}
}
}
}
通过以上章节的学习,用户将逐步掌握HarmonyOS Next的开发技能,从基础的环境搭建到复杂的任务管理应用实现。每个章节都包含清晰的代码示例和详细解释,帮助用户快速上手并深入理解HarmonyOS Next的开发。