目录

Can the isAttached API of FrameNode be used to determine whether a FrameNode is displayed on the screen?

The isAttached API of FrameNode is designed to check whether a node is mounted to the main node tree, regardless of whether the node is displayed on the screen. Nodes that are not displayed on the screen may have been mounted to the main tree (for example, in the List scenario constructed using ForEach). You are advised not to use this API for judgment.

If you want to check whether a node is mounted to the main node tree, you can use the following alternative solution:

import { FrameNode, NodeController, UIContext } from '@kit.ArkUI';

class MyNodeController extends NodeController {
  rootNode: FrameNode | null = null;
  node1: FrameNode | null = null;
  node2: FrameNode | null = null;

  makeNode(uiContext: UIContext): FrameNode | null {
    this.rootNode = new FrameNode(uiContext);
    this.node1 = new FrameNode(uiContext);
    this.node1.commonAttribute.id('node1'); // Set id
    this.node2 = new FrameNode(uiContext);
    this.node2.commonAttribute.id('node2'); // Set id
    this.rootNode.appendChild(this.node1); // Node1 on the main tree, node2 not on the main tree.
    return this.rootNode;
  }
}

@Entry
@Component
struct Index {
  myNodeController: MyNodeController = new MyNodeController();

  build() {
    Column() {
      NodeContainer(this.myNodeController)
      Button('Click')
        .onClick(() => {
          // If the node cannot be obtained through getAttachedFrameNodeById, it indicates that the node has not been mounted to the main tree.
          console.info(`node1 is attached to main tree: ${(this.getUIContext().getAttachedFrameNodeById('node1') !==
            null)}`);
          console.info(`node2 is attached to main tree: ${(this.getUIContext().getAttachedFrameNodeById('node2') !==
            null)}`);
        })
    }
  }
}