DEV Community

Cover image for Ability Communication, Subcomponents, Click Dropdown, Component Refresh, XML Processing
kouwei qing
kouwei qing

Posted on

Ability Communication, Subcomponents, Click Dropdown, Component Refresh, XML Processing

[Daily HarmonyOS Next Knowledge] Ability Communication, Subcomponents, Click Dropdown, Component Refresh, XML Processing

1. How does communication work between HarmonyOS UIExtensionAbility and UIAbility?

After storing the windowStage object in AppStorage within UIAbility, when navigating from a UIAbility-loaded page to a page in extensionAbility, the value retrieved from AppStorage is undefined.

For communication, refer to the document:

https://developer.huawei.com/consumer/cn/doc/harmonyos-references-V5/js-apis-inner-application-uiextensioncontext-V5#uiextensioncontextstartability

2. Does HarmonyOS List allow using @builder as its subcomponent?

3. Does HarmonyOS ArkTS have an event triggered by clicking a dropdown?

The select event only triggers after an option is chosen. Since select options need to be dynamically queried via an interface, is there a way to implement this?

// xxx.ets
@Entry
@Component
struct SelectExample {
  @State text: string = "TTTTT"
  @State index: number = 2
  @State space: number = 8
  @State arrowPosition: ArrowPosition = ArrowPosition.END
  @State options: Array<SelectOption> = [
    { value: 'aaa', icon: $r("app.media.app_icon") },
    { value: 'bbb', icon: $r("app.media.app_icon") },
    { value: 'ccc', icon: $r("app.media.app_icon") },
    { value: 'ddd', icon: $r("app.media.app_icon") }]
  @State options2: Array<SelectOption> = []
  @State selected: string = ''
  @State @Watch('onSelectedIndexUpData') selectedIndex: number = -1

  onSelectedIndexUpData() {
    console.info('Data changed')
    if (this.selectedIndex < 0) {
      return
    }
    this.options2.push(this.options[this.selectedIndex])
  }

  build() {
    Row() {
      TextInput({ placeholder: 'input ...', text: this.selected })
        .onChange((value: string) => {
          this.selected = value
          let index = this.options.findIndex(item => item.value === value)
          this.selectedIndex = index >= 0 ? index : -1
          console.info(index.toString())
        })
        .width('60%')
      Select(this.options2)//.selected(this.index)
        .value(this.text)
        .font({ size: 16, weight: 500 })
        .onSelect((index: number, text?: string | undefined) => {
          console.info('Select:' + index)
          this.index = index;
          if (text) {
            this.text = text;
          }
          this.options2.pop()
          this.selectedIndex = -1
        })
    }.width('100%')
  }
}
Enter fullscreen mode Exit fullscreen mode

4. How to refresh the content of HarmonyOS @builder?

/**
 Online status area content for the title bar
 */
@ObservedV2
export class AIOTitleOnlineStatusItem {
  builder: WrappedBuilder<[AIOTitleOnlineStatusItem]> | undefined = undefined;
  @Trace title: string = '';
  @Trace subTitle: string = '';
}
/**
 Data entity for title bar updates
 */
@ObservedV2
export class AIOTitleModel {
  @Trace title: string = '';

  @Trace unreadCnt: number = 0;

  @Trace memberCnt: number = 0;

  @Trace onlineStatusItem: AIOTitleOnlineStatusItem | undefined = undefined;

}

const TAG = 'TroopAIOTitleComponent';

@Extend(Text) function navigationTextStyle() {
  .lineHeight(24)
  .fontColor(Color.Black)
  .fontSize(17)
  .textAlign(TextAlign.Start)
  .fontWeight(500)
  .textOverflow({ overflow: TextOverflow.Ellipsis })
  .maxLines(1)
}

@Builder
export function getOnlineStatusBuilder(statusItem: AIOTitleOnlineStatusItem) {
  Row() {
    Text(statusItem.title).lineHeight(16)
      .fontSize(12)
    Text(statusItem.subTitle).lineHeight(16)
      .fontSize(12)
  }.width('100%')
  .align(Alignment.Start)
    .height(20)
}

const model: AIOTitleModel = new AIOTitleModel();

@Entry
@Component
export struct Test {
  aboutToAppear(): void {
    model.title = 'Test Title';
    model.unreadCnt = 25;
  }
  build() {
    Column() {
      TitleComponent()
      Button('Click to change title content').onClick(() => {
        if (model.onlineStatusItem != undefined) {
          model.onlineStatusItem.title += '11';
          model.onlineStatusItem.builder = wrapBuilder(getOnlineStatusBuilder)
          // model.onlineStatusItem.builder = wrapBuilder(getOnlineStatusBuilder({ paramsItem: this.onlineStatusItem }))
        } else {
          model.onlineStatusItem = {
            builder: wrapBuilder(getOnlineStatusBuilder),
            // builder: wrapBuilder(getOnlineStatusBuilder({ paramsItem: this.onlineStatusItem })),
            title: 'Currently Online',
            subTitle: '-test'
          };
        }
      }).margin({
        top: 20
      })
    }.alignItems(HorizontalAlign.Center)
  }
}

@Component
export struct TitleComponent {

  build() {
    // Content area
    Flex({ wrap: FlexWrap.Wrap, justifyContent: FlexAlign.Start, alignContent: FlexAlign.SpaceEvenly }) {
      // Nickname
      Text() {
        // Left ear
        Span("TitleComponent")
        // Title
        Span(model.title)
        // Right ear
        // Group member count
        Span((${model.memberCnt}))

      }.navigationTextStyle()
      .alignSelf(ItemAlign.Start)
      .width('60%')
      .backgroundColor(Color.Pink)
      // Online status
      if (model.onlineStatusItem != undefined) {
        model.onlineStatusItem.builder?.builder(model.onlineStatusItem)
      }
    }.height(44)
    .alignSelf(ItemAlign.Center)
    .backgroundColor(Color.Yellow)
  }
}
Enter fullscreen mode Exit fullscreen mode

@ObservedV2 must be initialized with new and cannot be directly assigned.

5. How to save a written ohos.xml as a file in HarmonyOS?

// 1. Construct an XmlSerializer object based on ArrayBuffer
let arrayBuffer: ArrayBuffer = new ArrayBuffer(2048); // Create a 2048-byte buffer
let thatSer: xml.XmlSerializer = new xml.XmlSerializer(arrayBuffer); // Construct XmlSerializer based on ArrayBuffer

thatSer.setDeclaration(); // Write the XML declaration
thatSer.startElement('bookstore'); // Write the start tag of the element
thatSer.startElement('book'); // Write the start tag of the nested element
thatSer.setAttributes('category', 'COOKING'); // Write attributes and values
thatSer.startElement('title');
thatSer.setAttributes('lang', 'en');
thatSer.setText('Everyday'); // Write the tag value
thatSer.endElement(); // Write the end tag
thatSer.startElement('author');
thatSer.setText('Giada');
thatSer.endElement();
thatSer.startElement('year');
thatSer.setText('2005');
thatSer.endElement();
thatSer.endElement();
thatSer.endElement();
Enter fullscreen mode Exit fullscreen mode

Reference: https://developer.huawei.com/consumer/cn/doc/harmonyos-guides-V5/xml-generation-V5

Top comments (0)