目录

How do I make API version compatibility check for UI component properties?

Question

After using UI properties that are only supported in later API versions, the application may run into errors or crash when running on the system of an earlier API version.

Solution

You need to perform API adaptation or compatibility check for earlier versions. For example, if component property A was added in API 15, but the minimum supported device API version is API 12. In this case, you can use AttributeModifier to perform version checks for adaptation.

Assume that the backToTop property of the List component is used and you need to perform compatibility check. The sample code is as follows:

import { deviceInfo } from '@kit.BasicServicesKit';

@Entry
@Component
struct ComponentAttributeCompatibilityJudgment {
  modifier: MyListModifier = new MyListModifier();

  build() {
    List() {
      // List content
    }
    .height('100%')
    .width('100%')
    .attributeModifier(this.modifier)
  }
}

class MyListModifier implements AttributeModifier<ListAttribute> {
  applyNormalAttribute(instance: ListAttribute): void {
    // Determine based on the API version information of deviceInfo
    if (deviceInfo.sdkApiVersion > 14) {
      // The property to be adapted is the backToTop attribute of the List component
      // The instance is an attribute object of the List, and its properties can be modified through the instance
      instance.backToTop(true);
    }
  }
}

Reference

AttributeModifier