DEV Community

陈杨
陈杨

Posted on

Hong Mong 5 Development Treasure Case Sharing Click Response Delay Analysis

HarmonyOS Treasure Discovery! Official Hidden Practical Cases, Double Your Development Efficiency 🚀

Hello everyone! Recently, while exploring HarmonyOS development, I accidentally discovered Huawei's official case treasure library! It turns out that the HarmonyOS documentation hides nearly a hundred scenario-based cases, covering high-frequency needs such as layout adaptation, performance optimization, and animation implementation. These cases not only provide complete code but also offer pitfall-avoidance guides. Today, I’ll share a few super practical ones! (With code analysis)


🔥 Selected Case Analysis + Code Practice

1. Foldable Screen Hover State Development

Scenario: When a foldable device is unfolded, the app automatically displays a split view (e.g., menu on the left, details on the right)
Core Solution: Use [@ohos.display](https://geek.csdn.net/educolumn/display) to listen to screen status and dynamically switch layouts

// 监听屏幕折叠状态
import display from '@ohos.display';

// 获取默认屏幕对象
let displayClass: display.Display | null = null;
display.getDefaultDisplay((err, data) => {
  displayClass = data;
  // 监听折叠状态变化
  displayClass.on('foldStatusChange', (curStatus) => {
    if (curStatus === display.FoldStatus.FOLD_STATUS_EXPANDED) {
      // 展开状态:启用分栏布局
      this.enableTwoPaneMode();
    } else {
      // 折叠状态:单列布局
      this.enableSingleColumn();
    }
  });
});
Enter fullscreen mode Exit fullscreen mode

Key Tips:

  • Use Grid + Row/Column to achieve responsive layouts
  • Dynamically adjust split ratios with mediaQuery (7:3 for large screens, fullscreen for small screens)

2. Long List Performance Optimization

Pain Point: Scrolling through thousands of data items is laggy
Solution: LazyForEach lazy loading + component reuse

// 使用LazyForEach动态加载
LazyForEach(this.dataArray, (item: ItemData) => {
  ListItem() {
    // 关键!设置cachedCount复用屏幕外组件
    MyListItemComponent({ item: item })
  }
}, (item) => item.id.toString())

// 组件内声明复用标识
@Component
struct MyListItemComponent {
  @ObjectLink item: ItemData;

  // 声明组件可复用
  aboutToReuse(params: Record<string, Object>) {
    this.item = params.item as ItemData;
  }
}
Enter fullscreen mode Exit fullscreen mode

Optimization Effect:

  • Memory usage reduced by 40%
  • FPS increased from 30 to 55+

3. Service Card Real-Time Update

Scenario: Music card displays playback progress
Black Technology: FormExtensionAbility + postCardAction

// 卡片提供方
export default class MusicFormAbility extends FormExtensionAbility {
  onAddForm(want) {
    // 创建卡片时启动进度更新
    setInterval(() => {
      // 获取当前播放进度
      let progress = getMusicProgress();
      // 主动更新卡片UI
      postCardAction(this.context, {
        formId: want.parameters["ohos.extra.param.key.form_identity"],
        action: "updateProgress",
        params: { progress }
      });
    }, 1000);
  }
}

// 卡片布局内绑定动态数据
@Entry
@Component
struct MusicCard {
  @State progress: number = 0;

  build() {
    Stack() {
      // 进度条组件
      Progress({ value: this.progress, total: 100 })
    }
    .onCardAction((action) => {
      // 接收服务端更新
      if (action.action === "updateProgress") {
        this.progress = action.params.progress;
      }
    })
  }
}
Enter fullscreen mode Exit fullscreen mode

4. Cross-Device File Drag and Drop

Seamless Flow Core Code:

// 设置元素为可拖拽
Text("拖我传文件")
  .draggable(true)
  .onDragStart((event: DragEvent) => {
    // 添加要传递的文件数据
    event.setData({
      "file": { path: "internal://app/file.txt" }
    });
  })

// 目标设备放置区域
Column()
  .onDrop((event: DropEvent) => {
    // 获取传递的文件
    const file = event.getData()["file"];
    // 跨设备保存文件
    fs.copy(file.path, 'local://newFile.txt');
  })
Enter fullscreen mode Exit fullscreen mode

Technical Points:

  • Declare ohos.permission.INTERNET permission in module.json5
  • Devices must be logged in with the same Huawei account

💎 Treasure Entry Guide

  1. Search by Scenario:
    • Finance → Banking and wealth management cases
    • Video → Smooth short video switching
    • Games → High-performance rendering optimization

Final Words

These cases are like "official plugins," especially suitable for:

  • Developers new to HarmonyOS ➡️ Run through the cases directly and then modify as needed
  • Facing performance bottlenecks ➡️ Copy official optimization solutions
  • Need to support new devices (such as foldables) ➡️ Check vertical adaptation guides

It’s recommended to bookmark the Best Practice Documentation—it’s much more efficient than aimlessly Googling! Have you found any other treasure resources? See you in the comments 👇

Easter Egg: Search for "Development Practice" in the documentation to unlock more hidden cases~

Top comments (0)