1
头图

我们基于HarmonyOS Next来实现一个简单的阅读器demo,在实战开发中详细了解一下 HarmonyOS Next的开发过程

  1. 创建一个新的 HarmonyOS Next 项目
    使用 DevEco Studio 创建一个新的 HarmonyOS Next 项目。
  2. 创建页面
    创建一个页面用于展示书籍列表和阅读内容。
    2.1 书籍列表页面
// pages/BookList.ets
import { Book } from '../models/Book';

@Entry
@Component
struct BookList {
  @State books: Book[] = [
    { id: '1', title: 'The Great Gatsby', author: 'F. Scott Fitzgerald' },
    { id: '2', title: 'To Kill a Mockingbird', author: 'Harper Lee' },
    { id: '3', title: '1984', author: 'George Orwell' },
  ];

  build() {
    Column({ space: 10 }) {
      Text('Book List')
        .fontSize(30)
        .fontWeight(FontWeight.Bold)
        .padding({ top: 20, bottom: 20 });

      List(this.books) {
        (book) => (
          Row() {
            Text(book.title)
              .fontSize(20)
              .fontColor(Color.Black)
              .layoutWeight(1);
            Text(book.author)
              .fontSize(16)
              .fontColor(Color.Gray);
          }
          .padding({ left: 10, right: 10 })
          .onClick(() => {
            AppStorage.SetOrCreate('currentBookId', book.id);
            router.pushUrl({ url: 'pages/Reader' });
          })
        )
      }
      .width('100%')
      .height('100%')
    }
  }
}

2.2 阅读页面

// pages/Reader.ets
import { Book } from '../models/Book';

@Component
struct Reader {
  @StorageLink('currentBookId') currentBookId: string = '';
  @State book: Book | null = null;
  @State currentPage: number = 0;
  @StorageLink('lastReadPage') lastReadPage: number = 0;

  @Link('bookList') bookList: BookList;

  build() {
    if (!this.currentBookId) {
      return Column() {
        Text('Loading...')
          .fontSize(20)
          .fontWeight(FontWeight.Bold);
      };
    }

    // 模拟从本地存储加载书籍内容
    if (!this.book) {
      this.loadBookContent();
    }

    return Column({ space: 10 }) {
      Text(`${this.book?.title} - Page ${this.currentPage + 1}`)
        .fontSize(24)
        .fontWeight(FontWeight.Bold)
        .padding({ top: 20, bottom: 20 });

      Text(this.book?.content?.[this.currentPage] || 'Content loading...')
        .fontSize(18)
        .padding({ left: 20, right: 20 });

      Row({ space: 10 }) {
        Button('Previous')
          .onClick(() => {
            if (this.currentPage > 0) {
              this.currentPage--;
              this.saveReadingProgress();
            }
          })
          .width('40%');

        Button('Next')
          .onClick(() => {
            if (this.currentPage < (this.book?.content?.length || 0) - 1) {
              this.currentPage++;
              this.saveReadingProgress();
            }
          })
          .width('40%');
      }
      .padding({ bottom: 20 });
    };
  }

  loadBookContent() {
    // 模拟从本地存储或 API 加载书籍内容
    const bookData: { [key: string]: Book } = {
      '1': {
        id: '1',
        title: 'The Great Gatsby',
        author: 'F. Scott Fitzgerald',
        content: [
          'Chapter 1: In my younger and more vulnerable years...',
          'Chapter 2: The next day...',
          'Chapter 3: The party at Gatsby\'s...',
        ]
      },
      '2': {
        id: '2',
        title: 'To Kill a Mockingbird',
        author: 'Harper Lee',
        content: [
          'Chapter 1: When he was nearly thirteen...',
          'Chapter 2: The school year...',
          'Chapter 3: The Radley Place...',
        ]
      },
      '3': {
        id: '3',
        title: '1984',
        author: 'George Orwell',
        content: [
          'Chapter 1: It was a bright cold day...',
          'Chapter 2: Winston kept his back...',
          'Chapter 3: The telescreen received...',
        ]
      }
    };

    this.book = bookData[this.currentBookId];
    if (this.book) {
      this.currentPage = this.lastReadPage || 0;
    }
  }

  saveReadingProgress() {
    AppStorage.SetOrCreate('lastReadPage', this.currentPage);
  }
}
  1. 数据存储
    使用 AppStorage 和 PersistentStorage 实现数据的持久化存储。
    3.1 使用 AppStorage 保存和读取数据
// 在应用启动时初始化
AppStorage.SetOrCreate('fontSizePreference', 16);
AppStorage.SetOrCreate('lastReadPage', 0);

// 在组件中使用
@StorageLink('fontSizePreference') fontSize: number = 16;
@StorageLink('lastReadPage') lastPage: number = 0;

3.2 使用 PersistentStorage 实现持久化存储

// 初始化持久化存储
PersistentStorage.persistProp('lastReadPage', 0);

// 在组件中使用
@StorageLink('lastReadPage') lastPage: number = 0;

demo功能

  1. 在书籍列表页面,用户可以看到所有可用的书籍。
  2. 点击一本书籍后,页面会跳转到阅读页面,并加载书籍的内容。
  3. 用户可以点击“Previous”和“Next”按钮在章节间切换。
  4. 阅读进度会被自动保存,下次打开书籍时会从上次阅读的位置继续。

画楼西畔
6.4k 声望964 粉丝