diff --git a/ArkDataKit/entry/src/main/ets/pages/PredicateQuery.ets b/ArkDataKit/entry/src/main/ets/pages/PredicateQuery.ets index f6c45445faf1b7a6e505450b68090b151859de6c..5a10ef2c612739ac26fd1a88b72f5076f78d8a4f 100644 --- a/ArkDataKit/entry/src/main/ets/pages/PredicateQuery.ets +++ b/ArkDataKit/entry/src/main/ets/pages/PredicateQuery.ets @@ -29,25 +29,25 @@ export struct ReadingTheLocalDatabase { build() { Row() { Column({ space: 20 }) { - Button('创建数据库') + Button('Create database') .fontSize(20) .fontWeight(FontWeight.Bold) .onClick(async () => { try { - let name = new distributedKVStore.FieldNode('name'); // 创建FieldNode对象 - name.type = distributedKVStore.ValueType.STRING; // 指定节点类型对应的数据类型为string - name.nullable = false; // 节点数据不能为空 - name.default = 'cake'; // 默认值 + let name = new distributedKVStore.FieldNode('name'); // Create FieldNode + name.type = distributedKVStore.ValueType.STRING; // Set NodeType string + name.nullable = false; // NodeData is not null + name.default = 'cake'; // Default - let schema1 = new distributedKVStore.Schema(); // 创建Schema对象 - schema1.root.appendChild(name); // 添加子节点 - schema1.indexes = ['$.name']; // 定义索引字段 - // 创建KVManager对象 + let schema1 = new distributedKVStore.Schema(); // Create Schema + schema1.root.appendChild(name); // 添加子节点 add Child name + schema1.indexes = ['$.name']; + // Create KVManager let kvManager = distributedKVStore.createKVManager({ bundleName: 'TEST_CRASH_APP', context: this.getUIContext().getHostContext() }); - // 创建并获取分布式键值数据库 + // Create database await kvManager.getKVStore('storeIds', { createIfMissing: true, backup: false, @@ -75,7 +75,7 @@ export struct ReadingTheLocalDatabase { } entries.push(ent); } - // 批量插入键值对到数据库中 + // insert data kvStore.putBatch(entries) .then((data) => { console.info('Succeeded in putting Batch'); @@ -88,14 +88,14 @@ export struct ReadingTheLocalDatabase { } }) - Button('like查询') + Button('like select') .fontSize(20) .onClick(() => { try { if (kvStore === undefined) { return; } - // 使用谓词查询具有与指定字符串值相似的指定字段,并获取与指定Query对象匹配的键值对列表 + // Use predicates to query a specified field that has a value similar to the specified string, and obtain a list of key value pairs that match the specified Query object kvStore.getEntries(new distributedKVStore.Query().like('$.name', 'c%')) .then((value) => { for (let i = 0; i < value.length; i++) { diff --git a/ArkUI/entry/src/main/ets/entryability/EntryAbility.ets b/ArkUI/entry/src/main/ets/entryability/EntryAbility.ets index a42f8ab391a5d34fcebb6842b74c3206be33972c..68b92f2ffc8f4bdff6a87fe9769b43d1ffcce05d 100644 --- a/ArkUI/entry/src/main/ets/entryability/EntryAbility.ets +++ b/ArkUI/entry/src/main/ets/entryability/EntryAbility.ets @@ -17,7 +17,10 @@ export default class EntryAbility extends UIAbility { onWindowStageCreate(windowStage: window.WindowStage): void { // Main window is created, set main page for this ability hilog.info(DOMAIN, 'testTag', '%{public}s', 'Ability onWindowStageCreate'); + // [Start on_window_stage_create] + // Save windowStage for all to use AppStorage.setOrCreate('windowStage',windowStage); + // [End on_window_stage_create] windowStage.loadContent('pages/Index', (err) => { if (err.code) { hilog.error(DOMAIN, 'testTag', 'Failed to load the content. Cause: %{public}s', JSON.stringify(err)); diff --git a/ArkUI/entry/src/main/ets/entryability/EntryAbilityGetWindowStageInstance.ets b/ArkUI/entry/src/main/ets/entryability/EntryAbilityGetWindowStageInstance.ets index 0174fe1f4b89516f0ed7add96d752bda935087f2..e90b26fc16a39d2e32eba120d26e2017796f9aaf 100644 --- a/ArkUI/entry/src/main/ets/entryability/EntryAbilityGetWindowStageInstance.ets +++ b/ArkUI/entry/src/main/ets/entryability/EntryAbilityGetWindowStageInstance.ets @@ -35,7 +35,8 @@ export default class EntryAbility extends UIAbility { } hilog.info(0x0000, 'testTag', 'Succeeded in loading the content.'); }); - console.info('windowStage+++', JSON.stringify(windowStage)) + console.info('windowStage', JSON.stringify(windowStage)) + // Store windowStage instance globally for cross-page access AppStorage.setAndLink('windowStage', windowStage) } diff --git a/ArkUI/entry/src/main/ets/pages/AvoidAreaHeight.ets b/ArkUI/entry/src/main/ets/pages/AvoidAreaHeight.ets index 27048538810b424c1110804462ee25a1534cd11a..edebc0d458b67879bc4f43dc2b211300ca9aace5 100644 --- a/ArkUI/entry/src/main/ets/pages/AvoidAreaHeight.ets +++ b/ArkUI/entry/src/main/ets/pages/AvoidAreaHeight.ets @@ -30,27 +30,30 @@ struct GetAvoidAreaHeight { Column() { Button('GetAvoidAreaHeight') .onClick(() => { - let type1 = window.AvoidAreaType.TYPE_SYSTEM; - let type2 = window.AvoidAreaType.TYPE_NAVIGATION_INDICATOR; - window.getLastWindow(this.context.getHostContext()).then((data) => { - // Get the system default area, usually including the status bar and navigation bar - let avoidArea1 = data.getWindowAvoidArea(type1); - // Top status bar height - let statusBarHeight = avoidArea1.topRect.height; - // Bottom navigation bar height - let bottomNavHeight = avoidArea1.bottomRect.height; - // Get the navigation bar area - let avoidArea2 = data.getWindowAvoidArea(type2); - // Get the height of the navigation bar area - let indicatorHeight = avoidArea2.bottomRect.height; - console.info(`statusBarHeight is ${statusBarHeight}`); - console.info(`bottomNavHeight is ${bottomNavHeight}`); - console.info(`indicatorHeight is ${indicatorHeight}`); - }).catch((err: BusinessError) => { - console.error(`Failed to obtain the window. Cause: ${JSON.stringify(err)}`); - }); + let systemAvoidAreaType = window.AvoidAreaType.TYPE_SYSTEM; // system + let navigationIndicatorType = window.AvoidAreaType.TYPE_NAVIGATION_INDICATOR; // navigation + if (this.context) { + window.getLastWindow(this.context.getHostContext()).then((data) => { + // Get the system default area, usually including the status bar and navigation bar + let avoidArea1 = data.getWindowAvoidArea(systemAvoidAreaType); + // Top status bar height + let statusBarHeight = avoidArea1.topRect.height; + // Bottom navigation bar height + let bottomNavHeight = avoidArea1.bottomRect.height; + // Get the navigation bar area + let avoidArea2 = data.getWindowAvoidArea(navigationIndicatorType); + // Get the height of the navigation bar area + let indicatorHeight = avoidArea2.bottomRect.height; + console.info(`statusBarHeight is ${statusBarHeight}`); + console.info(`bottomNavHeight is ${bottomNavHeight}`); + console.info(`indicatorHeight is ${indicatorHeight}`); + }).catch((err: BusinessError) => { + console.error(`Failed to obtain the window. Cause: ${JSON.stringify(err)}`); + }); + } }) } } } + // [End get_avoid_area_height] \ No newline at end of file diff --git a/ArkUI/entry/src/main/ets/pages/ClickButtonSoftwareKeyboardToClose.ets b/ArkUI/entry/src/main/ets/pages/ClickButtonSoftwareKeyboardToClose.ets index 186031ad5d1cd641c6ae687a1cd27465692e926f..ce46757c8745494477e84df35beeabe729c160cb 100644 --- a/ArkUI/entry/src/main/ets/pages/ClickButtonSoftwareKeyboardToClose.ets +++ b/ArkUI/entry/src/main/ets/pages/ClickButtonSoftwareKeyboardToClose.ets @@ -32,7 +32,13 @@ struct ClickBlankHideKeyboard { Button('log on').width('100%') .onClick(() => { // Exit text editing mode - inputMethod.getController().stopInputSession(); + try { + this.inputRef.blur(); + // Close the current input session and hide the soft keyboard. + inputMethod.getController().stopInputSession(); + } catch (err) { + console.error('Failed to hide keyboard: ' + err); + } }) } } diff --git a/ArkUI/entry/src/main/ets/pages/CommonText.ets b/ArkUI/entry/src/main/ets/pages/CommonText.ets index fc5bc1a414e3a51ff0a1724b0d129f589580ebbc..afa1d6ae65e8866ee468af801466ad41a28fc92a 100644 --- a/ArkUI/entry/src/main/ets/pages/CommonText.ets +++ b/ArkUI/entry/src/main/ets/pages/CommonText.ets @@ -18,6 +18,7 @@ */ // [Start implement_cross_file_component_reuse_one] +// Set Image width & height export class ImageModifier implements AttributeModifier { width: number = 60; height: number = 60; @@ -36,6 +37,7 @@ export class ImageModifier implements AttributeModifier { /* Custom class implementation of the AttributeModifier interface for text, used for initialization */ +// Set Text textSize export class TextModifier implements AttributeModifier { textSize: number = 12; @@ -59,6 +61,9 @@ export class CheckboxModifier implements AttributeModifier { size: number = 15; constructor(size: number) { + if (size < 0) { + size = 15; + } this.size = size; } @@ -73,10 +78,10 @@ export class CheckboxModifier implements AttributeModifier { */ @Component export struct ImageText { - @State textOneContent: string | Resource = 'default'; + @State textContent: string | Resource = 'default'; @State imageSrc: PixelMap | ResourceStr | DrawableDescriptor = $r('app.media.icon'); //Accept externally passed AttributeModifier class instances, which can customize only some components and selectively pass parameters. - @State textOne: AttributeModifier = new TextModifier(12); + @State textModifier: AttributeModifier = new TextModifier(12); @State imageModifier: AttributeModifier = new ImageModifier(60, 60); @State checkboxModifier: AttributeModifier = new CheckboxModifier(15); @@ -89,8 +94,8 @@ export struct ImageText { .attributeModifier(this.imageModifier) .margin({ right: 10 }) - Text(this.textOneContent) - .attributeModifier(this.textOne) + Text(this.textContent) + .attributeModifier(this.textModifier) .fontColor(Color.Orange) } .padding({ top: 5 }) @@ -99,4 +104,5 @@ export struct ImageText { .height(100) } } + // [End implement_cross_file_component_reuse_one] \ No newline at end of file diff --git a/ArkUI/entry/src/main/ets/pages/CopyContentDirectlyClipboard.ets b/ArkUI/entry/src/main/ets/pages/CopyContentDirectlyClipboard.ets index 5db2636982919165e1ddbbceb051c48a23205dab..ffcfd17777082b93406de93d75dbd7fa51ab0cc3 100644 --- a/ArkUI/entry/src/main/ets/pages/CopyContentDirectlyClipboard.ets +++ b/ArkUI/entry/src/main/ets/pages/CopyContentDirectlyClipboard.ets @@ -25,6 +25,10 @@ import { pasteboard } from '@kit.BasicServicesKit'; struct CopyText { private textContent: string = 'Copy me'; + aboutToAppear(): void { + AppStorage.setOrCreate('context', this.getUIContext()); + } + build() { Column() { Text(this.textContent) @@ -47,7 +51,11 @@ struct CopyText { } } -// Define method +/* + * Copy the text to the system clipboard + * @param text - text + * @returns void + */ function copyText(text: string) { const uiContext: UIContext | undefined = AppStorage.get('context'); // Create clipboard content object diff --git a/ArkUI/entry/src/main/ets/pages/CorrectWayToUseForEach.ets b/ArkUI/entry/src/main/ets/pages/CorrectWayToUseForEach.ets index 8b9f50d731e2fdb9efb6641b98306cd658696ef0..298a9f35277c2f52893abc13751b2d1e71ce2929 100644 --- a/ArkUI/entry/src/main/ets/pages/CorrectWayToUseForEach.ets +++ b/ArkUI/entry/src/main/ets/pages/CorrectWayToUseForEach.ets @@ -23,7 +23,9 @@ export struct BindSheetAndForEach { @State isShow: boolean = false; @State arr: number[] = [1, 2, 3, 4]; - @State isHoverText: Array = new Array(this.arr.length).fill(false); + @State isSheetVisible: Array = new Array(this.arr.length).fill(false); + + @Builder myBuilder() { @@ -35,6 +37,7 @@ export struct BindSheetAndForEach { .width('100%') } + // Each array item corresponds to an independent pop-up window displaying the status, which is index bound build() { Column() { ForEach(this.arr, (item: number, idx: number) => { @@ -42,16 +45,16 @@ export struct BindSheetAndForEach { Text('item') Button('Bullet Frame') .onClick(() => { - this.isHoverText[idx] = true; + this.isSheetVisible[idx] = true; }) .fontSize(15) .margin(10) - .bindSheet(this.isHoverText[idx], this.myBuilder(), { + .bindSheet(this.isSheetVisible[idx], this.myBuilder(), { backgroundColor: Color.Gray, height: SheetSize.MEDIUM, showClose: true, onWillDisappear: () => { - this.isHoverText[idx] = false; + this.isSheetVisible[idx] = false; } }) Checkbox() diff --git a/ArkUI/entry/src/main/ets/pages/DrawRoundedRectanglesUsingCanvas.ets b/ArkUI/entry/src/main/ets/pages/DrawRoundedRectanglesUsingCanvas.ets index 32be373fb4592ffd065b370e8b198b496e993728..7e4ae7af6bc34f26f0454ac0f4d55da1b455995d 100644 --- a/ArkUI/entry/src/main/ets/pages/DrawRoundedRectanglesUsingCanvas.ets +++ b/ArkUI/entry/src/main/ets/pages/DrawRoundedRectanglesUsingCanvas.ets @@ -24,9 +24,11 @@ struct CanvasDrawRoundedRectangle { private readonly settings: RenderingContextSettings = new RenderingContextSettings(true); private readonly ctx: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings); - drawRoundRect(x: number, y: number, width: number, height: number, radius: number, strokeColor?: string, - fillColor?: string, lineDash?: []) { + fillColor?: string, lineDash?: Array) { + if (width < 2 * radius || height < 2 * radius) { + radius = Math.min(width, height) / 2; + } strokeColor = strokeColor || '#333'; lineDash = lineDash || []; this.ctx.beginPath(); @@ -39,7 +41,7 @@ struct CanvasDrawRoundedRectangle { this.ctx.arc(width - radius + x, radius + y, radius, Math.PI * 3 / 2, Math.PI * 2); // Draw the second straight path this.ctx.lineTo(width + x, height + y - radius); - // Draw the third arc path + // Draw the third arc path this.ctx.arc(width - radius + x, height - radius + y, radius, 0, Math.PI / 2); // Draw the third straight path this.ctx.lineTo(radius + x, height + y); @@ -58,7 +60,6 @@ struct CanvasDrawRoundedRectangle { this.ctx.closePath(); } - build() { Row() { Column() { @@ -74,4 +75,5 @@ struct CanvasDrawRoundedRectangle { .height('100%') } } + // [End draw_rounded_rectangles_using_canvas] \ No newline at end of file diff --git a/ArkUI/entry/src/main/ets/pages/ExcavationScreenAdaptation.ets b/ArkUI/entry/src/main/ets/pages/ExcavationScreenAdaptation.ets index e402c32d8462f29aedd7b385cd21d459f030eaaf..3a5702d9d5cc9b12ef0100cf1c6995d250e58280 100644 --- a/ArkUI/entry/src/main/ets/pages/ExcavationScreenAdaptation.ets +++ b/ArkUI/entry/src/main/ets/pages/ExcavationScreenAdaptation.ets @@ -70,6 +70,10 @@ struct Index { } } + /** + * Calculate the left and right margins of the unusable areas of the punch hole screen + * @returns {TextMargin} Objects that include left/right offsets + */ getBoundingRectPosition(): TextMargin { if (this.boundingRect !== null && this.displayClass !== null && this.boundingRect[0] !== undefined) { // Distance from the right of the unavailable area to the right edge of the screen: screen width minus left width and unavailable area width diff --git a/ArkUI/entry/src/main/ets/pages/FullNavigationSubcomponent.ets b/ArkUI/entry/src/main/ets/pages/FullNavigationSubcomponent.ets index d17e1ed99a437b8ee84a859f2ebf5cf3bfdd2ffa..7c72847d0e413c025f2b9eeb07b222563604c63e 100644 --- a/ArkUI/entry/src/main/ets/pages/FullNavigationSubcomponent.ets +++ b/ArkUI/entry/src/main/ets/pages/FullNavigationSubcomponent.ets @@ -19,15 +19,23 @@ // [Start full_navigation_subcomponent] import { window } from '@kit.ArkUI'; +import { hilog } from '@kit.PerformanceAnalysisKit'; + +const DOMAIN = 0x0000; +const TAG = 'FullNavigationSubComponent'; @Entry @Component -struct FullNavigationSubcomponent { +struct FullNavigationSubComponent { context = this.getUIContext(); onPageShow(): void { window.getLastWindow(this.context.getHostContext(), (err, win) => { - win.setWindowLayoutFullScreen(true); + if (err != null) { + hilog.error(DOMAIN, TAG, `getLastWindow failed code:${err.code};message:${err.message}`); + } else { + win.setWindowLayoutFullScreen(true); + } }) } diff --git a/ArkUI/entry/src/main/ets/pages/GetComponentRenderingTime.ets b/ArkUI/entry/src/main/ets/pages/GetComponentRenderingTime.ets index 236996994d6884fdf6ccf33eebf5db8e585fe436..d40fabfb5b4f949636d96aff95b0fa8a1c7b3c12 100644 --- a/ArkUI/entry/src/main/ets/pages/GetComponentRenderingTime.ets +++ b/ArkUI/entry/src/main/ets/pages/GetComponentRenderingTime.ets @@ -25,7 +25,8 @@ import { inspector } from '@kit.ArkUI'; struct GetComponentRenderTime { @State startTime: number = 0; private listener: inspector.ComponentObserver = this.getUIContext().getUIInspector().createComponentObserver('IMAGE_ID'); - private onDrawComplete = () => { + // Calculate rendering duration: currentTime - this.startTime + private onDrawCompleteCallback = () => { // 2. Time when the image component finishes drawing console.info('onDrawComplete', new Date().getTime()); }; @@ -37,12 +38,12 @@ struct GetComponentRenderTime { // layout: Component layout completed // draw: Component drawing completed - this.listener.on('draw', this.onDrawComplete); + this.listener.on('draw', this.onDrawCompleteCallback); } aboutToDisappear() { // Unregister callback before destruction - this.listener.off('draw', this.onDrawComplete); + this.listener.off('draw', this.onDrawCompleteCallback); } build() { diff --git a/ArkUI/entry/src/main/ets/pages/IgnoreSingleClickGestures.ets b/ArkUI/entry/src/main/ets/pages/IgnoreSingleClickGestures.ets index cdfcd68f5b4cd8bf45f7ef4f5ad92608c8eb0e7a..7637c47246092dc7b6a269bebd6a94c07359dfe1 100644 --- a/ArkUI/entry/src/main/ets/pages/IgnoreSingleClickGestures.ets +++ b/ArkUI/entry/src/main/ets/pages/IgnoreSingleClickGestures.ets @@ -34,8 +34,7 @@ struct TapGestureExample { .onAction(() => { console.info('TapGesture 1'); }) - ) - ) + )) } .width('100%') .height('100%') diff --git a/ArkUI/entry/src/main/ets/pages/ImplementLazyLoadingOfTwoDimensionalArrays.ets b/ArkUI/entry/src/main/ets/pages/ImplementLazyLoadingOfTwoDimensionalArrays.ets index b9c645535a04b8be54ea7e682647748a62e277cd..92606e33a1b3b06c0251a5f2947d470665649a7c 100644 --- a/ArkUI/entry/src/main/ets/pages/ImplementLazyLoadingOfTwoDimensionalArrays.ets +++ b/ArkUI/entry/src/main/ets/pages/ImplementLazyLoadingOfTwoDimensionalArrays.ets @@ -29,6 +29,9 @@ class BasicDataSource implements IDataSource { } public getData(index: number): TimeTable | string { + if (index < 0 || index >= this.originDataArray.length) { + return ''; + } return this.originDataArray[index]; } @@ -115,6 +118,9 @@ class MyDataSource extends BasicDataSource { } } +/* + * The course schedule data structure, title represents the day of the week, and projects represents the list of courses for that day + */ interface TimeTable { title: string; projects: string[]; @@ -141,7 +147,7 @@ export struct TwoNestingArrayLazy { } ]; private data1: MyDataSource = new MyDataSource(this.timeTable); - private hashMap: HashMap = new HashMap(); + private hashMap: HashMap = new HashMap(); aboutToAppear(): void { for (let index = 0; index < this.timeTable.length; index++) { @@ -159,8 +165,8 @@ export struct TwoNestingArrayLazy { } @Builder - itemFoot(num: number) { - Text('common' + num + 'period') + itemFoot(itemCount: number) { + Text('common' + itemCount + 'period') .fontSize(16) .backgroundColor(0xAABBCC) .width("100%") diff --git a/ArkUI/entry/src/main/ets/pages/ImplementUnifiedPageGrayingFunction.ets b/ArkUI/entry/src/main/ets/pages/ImplementUnifiedPageGrayingFunction.ets index f3ccfb948a3cdc860ce5f61762fd8d4e4cec4460..9f6374bc05648fad93380f297a9121ffb3154fc5 100644 --- a/ArkUI/entry/src/main/ets/pages/ImplementUnifiedPageGrayingFunction.ets +++ b/ArkUI/entry/src/main/ets/pages/ImplementUnifiedPageGrayingFunction.ets @@ -25,7 +25,6 @@ struct Index { build() { Column({ space: 20 }) { - Flex() Image($r("app.media.app_icon")) .height(100) Row({ space: 20 }) { diff --git a/ArkUI/entry/src/main/ets/pages/ListDropdownLoadRollbackCurrentLocation.ets b/ArkUI/entry/src/main/ets/pages/ListDropdownLoadRollbackCurrentLocation.ets index 9a0132bcaeae8116a6f18255778e1e83d61ee2d7..3b669d946160dfb4b50cc2a8f2a99ac3b082b5e4 100644 --- a/ArkUI/entry/src/main/ets/pages/ListDropdownLoadRollbackCurrentLocation.ets +++ b/ArkUI/entry/src/main/ets/pages/ListDropdownLoadRollbackCurrentLocation.ets @@ -23,6 +23,7 @@ struct RefreshDemo { @State isRefreshing: boolean = false; @State arr: String[] = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10']; + // Used to control the scrolling position of the list and maintain consistency of the view after refreshing private listScroller: Scroller = new Scroller(); build() { @@ -49,11 +50,13 @@ struct RefreshDemo { setTimeout(() => { this.isRefreshing = false; }, 2000) + let originalCount = this.arr.length; this.arr.unshift('11'); this.arr.unshift('12'); - this.listScroller.scrollToIndex(2); + this.listScroller.scrollToIndex(this.listScroller.scrollToIndex(this.arr.length - originalCount)); }) } } } + // [End list_dropdown_load_rollback_current_location] \ No newline at end of file diff --git a/ArkUI/entry/src/main/ets/pages/ListExchangeSubcomponentPositions.ets b/ArkUI/entry/src/main/ets/pages/ListExchangeSubcomponentPositions.ets index 825f2c6df413cdd8a9bfa3e8c504cddc6a637490..d7bdab20bb4844c5260540846072750e03d2c99b 100644 --- a/ArkUI/entry/src/main/ets/pages/ListExchangeSubcomponentPositions.ets +++ b/ArkUI/entry/src/main/ets/pages/ListExchangeSubcomponentPositions.ets @@ -1,30 +1,10 @@ -/* -* Copyright (c) 2024 Huawei Device Co., Ltd. -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ - -/* -* FAQ:如何实现List内拖拽交换子组件位置 -*/ - -// [Start list_exchange_subcomponent_positions] @Entry @Component struct Index { @State listArr: string[] = []; @Builder - pixelMapBuilder(text: string) { + textItemBuilder(text: string) { Column() { Text(text) .fontSize(16) @@ -67,10 +47,10 @@ struct Index { .lanes({ minLength: 80, maxLength: 80 }) .alignListItem(ListItemAlign.Center) .onItemDragStart((event: ItemDragInfo, index: number) => { - return this.pixelMapBuilder(this.listArr[index]); + return this.textItemBuilder(this.listArr[index]); }) .onItemDrop((event: ItemDragInfo, itemIndex: number, insertIndex: number, isSuccess: boolean) => { - if (!isSuccess || insertIndex >= this.listArr.length) { + if (!isSuccess || insertIndex < 0 || insertIndex >= this.listArr.length) { return; } this.changeListItemIndex(itemIndex, insertIndex); @@ -80,5 +60,4 @@ struct Index { .height('100%') .backgroundColor(0xDCDCDC) } -} -// [End list_exchange_subcomponent_positions] \ No newline at end of file +} \ No newline at end of file diff --git a/ArkUI/entry/src/main/ets/pages/ListSideRebound.ets b/ArkUI/entry/src/main/ets/pages/ListSideRebound.ets index eda4fc7860767482e2cb1fcdeb9e49166c7c8fa1..ebe0e06ab1d6eb1cd03f5e156fbe6e5b4970c9f9 100644 --- a/ArkUI/entry/src/main/ets/pages/ListSideRebound.ets +++ b/ArkUI/entry/src/main/ets/pages/ListSideRebound.ets @@ -43,9 +43,9 @@ struct ListSideRebound { .listDirection(Axis.Vertical) // Arrangement direction .scrollBar(BarState.Off) .friction(0.6) - .edgeEffect(this.isTop ? EdgeEffect.Spring : EdgeEffect.None) + .edgeEffect(this.isTop ? EdgeEffect.Spring : EdgeEffect.None) // Enable the flex effect only on the top boundary .onScrollIndex((firstIndex: number) => { - if (firstIndex === 0) { + if (this.arr.length === 0 || firstIndex === 0) { this.isTop = true; } else { this.isTop = false; @@ -59,4 +59,5 @@ struct ListSideRebound { .padding({ top: 5 }) } } + // [End list_side_rebound] \ No newline at end of file diff --git a/ArkUI/entry/src/main/ets/pages/MergeTwoListsAndSupportLazyLoading.ets b/ArkUI/entry/src/main/ets/pages/MergeTwoListsAndSupportLazyLoading.ets index cb0e53a8727631040776f0e9086481d2cf7154b5..66dccbbf24001cc03a0872181665f9b4a5d2d573 100644 --- a/ArkUI/entry/src/main/ets/pages/MergeTwoListsAndSupportLazyLoading.ets +++ b/ArkUI/entry/src/main/ets/pages/MergeTwoListsAndSupportLazyLoading.ets @@ -20,13 +20,11 @@ // [Start merge_two_lists_and_support_lazy_loading_one] import { MyDataSource } from './DataUtil'; - @Entry @Component struct DoubleLazyForEach { private scrollerForScroll: Scroller = new Scroller(); - build() { Flex() { Scroll(this.scrollerForScroll) { @@ -51,24 +49,21 @@ struct DoubleLazyForEach { } } - @Component struct ListA { private scrollerForListA: Scroller = new Scroller(); private dataOne: MyDataSource = new MyDataSource(); - aboutToAppear() { for (let i = 0; i <= 20; i++) { this.dataOne.pushData(`Hello One ${i}`); } } - build() { Column() { List({ space: 20, scroller: this.scrollerForListA }) { - LazyForEach(this.dataOne, (item: number) => { + LazyForEach(this.dataOne, (item: string) => { ListItem() { Text('ListItem' + item) .width('100%') @@ -96,26 +91,23 @@ struct ListA { } } - @Component struct ListB { private dataTwo: MyDataSource = new MyDataSource(); private scrollerForListB: Scroller = new Scroller(); - aboutToAppear() { for (let i = 0; i <= 20; i++) { this.dataTwo.pushData(`Hello Two ${i}`); } } - build() { Column() { List({ space: 20, scroller: this.scrollerForListB }) { - LazyForEach(this.dataTwo, (item: number) => { + LazyForEach(this.dataTwo, (item: string) => { ListItem() { - MyText({ state_value: item.toString() }) + MyText({ state_value: item }) } .width('100%') .height(100) @@ -133,12 +125,10 @@ struct ListB { } } - @Component struct MyText { @State private state_value: string = 'Hello'; - build() { Text('ListItem' + this.state_value) .width('100%') @@ -149,4 +139,5 @@ struct MyText { .backgroundColor(Color.Pink) } } + // [End merge_two_lists_and_support_lazy_loading_one] \ No newline at end of file diff --git a/ArkUI/entry/src/main/ets/pages/RealizePageLevelTransparencyEffect.ets b/ArkUI/entry/src/main/ets/pages/RealizePageLevelTransparencyEffect.ets index 30c0ad6de7cfff7fdcc46bca79fd042e274fd5b8..0977b5ef2caf19787a7b768728699532c4b0a5fd 100644 --- a/ArkUI/entry/src/main/ets/pages/RealizePageLevelTransparencyEffect.ets +++ b/ArkUI/entry/src/main/ets/pages/RealizePageLevelTransparencyEffect.ets @@ -23,7 +23,7 @@ export struct TransparentPage { @Provide('NavPathStack') pageStack: NavPathStack = new NavPathStack(); @Builder - PagesMap(name: string) { + pageMapBuilder(name: string) { if (name === 'DialogPage') { DialogPage() } @@ -40,7 +40,7 @@ export struct TransparentPage { } .mode(NavigationMode.Stack) .title('Main') - .navDestination(this.PagesMap) + .navDestination(this.pageMapBuilder) } } @@ -57,7 +57,7 @@ export struct DialogPage { .margin({ bottom: 100 }) Button("Close") .onClick(() => { - this.pageStack.pop(); + this.pageStack?.pop() ?? console.warn("Navigation stack is empty"); }) .width('30%') } @@ -69,8 +69,6 @@ export struct DialogPage { .height("100%") .width('100%') } - // Set background color - //.backgroundColor(Color.Red) .hideTitleBar(true) .mode(NavDestinationMode.DIALOG) } diff --git a/ArkUI/entry/src/main/ets/pages/ReplaceDefaultTimeSet.ets b/ArkUI/entry/src/main/ets/pages/ReplaceDefaultTimeSet.ets index c9e58e63d6bf685a2568479be84b1af8decd7dfa..ba6a9ae55cedefd034d33dc692b56412520dc4bf 100644 --- a/ArkUI/entry/src/main/ets/pages/ReplaceDefaultTimeSet.ets +++ b/ArkUI/entry/src/main/ets/pages/ReplaceDefaultTimeSet.ets @@ -35,6 +35,7 @@ struct ReplaceDefaultTimeSetPage { @State offsetY: number = 0; // Set grid column count private str: string = ''; + // Records the offset of the drag starting position private dragRefOffsetx: number = 0; private dragRefOffsety: number = 0; private FIX_VP_X: number = 108; @@ -162,7 +163,7 @@ struct ReplaceDefaultTimeSetPage { // Control whether the element can be moved and sorted by its index isDraggable(index: number): boolean { - return index > -1; // Always成立,所有元素均可移动排序 + return index >= 0 && index < this.numbers.length; } build() { diff --git a/ArkUI/entry/src/main/ets/pages/SideSlipEventInterception.ets b/ArkUI/entry/src/main/ets/pages/SideSlipEventInterception.ets index cd8af58988d832e4e95cdc8f899de76c9f58d226..af3b918ed7608f91120ebe20963d9bd6996b03b1 100644 --- a/ArkUI/entry/src/main/ets/pages/SideSlipEventInterception.ets +++ b/ArkUI/entry/src/main/ets/pages/SideSlipEventInterception.ets @@ -1,23 +1,3 @@ -/* -* Copyright (c) 2024 Huawei Device Co., Ltd. -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ - -/* -* FAQ:如何在Navigation页面中实现侧滑事件拦截 -*/ - -// [Start sideslip_intercept] import { ShowDialogSuccessResponse } from '@kit.ArkUI'; @Entry @@ -25,14 +5,14 @@ import { ShowDialogSuccessResponse } from '@kit.ArkUI'; struct SideslipIntercept { controller: TextAreaController = new TextAreaController(); @State text: string = ''; - @Provide pageStackForComponentSharedPages: NavPathStack = new NavPathStack(); + @Provide pageStack: NavPathStack = new NavPathStack(); build() { // Main page uses NavDestination as carrier to display Navigation content area - Navigation(this.pageStackForComponentSharedPages) { + Navigation(this.pageStack) { } .onAppear(() => { - this.pageStackForComponentSharedPages.pushPathByName('MainPage', null, false); + this.pageStack.pushPathByName('MainPage', null, false); }) // Create NavDestination component, use its onBackPressed callback to intercept back event .navDestination(this.textArea) @@ -84,5 +64,4 @@ struct SideslipIntercept { return true ; }) } -} -// [End sideslip_intercept] \ No newline at end of file +} \ No newline at end of file diff --git a/ArkUI/entry/src/main/ets/pages/SwitchingBetweenCustomAndSystemKeyboard.ets b/ArkUI/entry/src/main/ets/pages/SwitchingBetweenCustomAndSystemKeyboard.ets index 778966fc75b266590647535d144c78332d6e5fbc..9dbe91c2fe4c41d04ff28b76f97f0feb518988a1 100644 --- a/ArkUI/entry/src/main/ets/pages/SwitchingBetweenCustomAndSystemKeyboard.ets +++ b/ArkUI/entry/src/main/ets/pages/SwitchingBetweenCustomAndSystemKeyboard.ets @@ -26,7 +26,7 @@ export struct CustomSystemKeyboardToggle { // Customize keyboard components @Builder - CustomKeyboardBuilder() { + customKeyboardBuilder() { Column() { Button('x') .onClick(() => { @@ -56,7 +56,7 @@ export struct CustomSystemKeyboardToggle { build() { Column() { TextInput({ controller: this.controller, text: this.inputValue })// Bind custom keyboard - .customKeyboard(this.show ? this.CustomKeyboardBuilder() : undefined) + .customKeyboard(this.show ? this.customKeyboardBuilder() : undefined) .margin(10) .height(48) Button('switch') diff --git a/ArkUI/entry/src/main/ets/pages/TextExpansionAndCollapseFunctions.ets b/ArkUI/entry/src/main/ets/pages/TextExpansionAndCollapseFunctions.ets index 7d320718123648e536e0e39899755735689e8d37..21dc6f27c2494ad63e5fa7fc9fb6bd03ac5dcfde 100644 --- a/ArkUI/entry/src/main/ets/pages/TextExpansionAndCollapseFunctions.ets +++ b/ArkUI/entry/src/main/ets/pages/TextExpansionAndCollapseFunctions.ets @@ -27,18 +27,19 @@ const EXPAND_STR: string = 'Expand'; const COLLAPSE_STR: string = 'Collapse'; const FULL_TEXT: string = 'HarmonyOS provides a UI development framework called the ArkUI Framework. The ArkUI Framework provides developers with ' + - 'essential capabilities for application UI development, such as multiple components, layout calculations, animation capabilities, UI interaction, drawing, etc.\n' + - 'The ArkUI Framework offers two development paradigms for developers with different purposes and technical backgrounds: ' + - 'the Declarative Development Paradigm based on ArkTS (referred to as the "Declarative Development Paradigm") ' + - 'and the JS-compatible Web Development Paradigm (referred to as the "Web Development Paradigm"). Here is a simple comparison of these two development paradigms.' + 'essential capabilities for application UI development, such as multiple components, layout calculations, animation capabilities, UI interaction, drawing, etc.\n' + + 'The ArkUI Framework offers two development paradigms for developers with different purposes and technical backgrounds: ' + + 'the Declarative Development Paradigm based on ArkTS (referred to as the "Declarative Development Paradigm") ' + + 'and the JS-compatible Web Development Paradigm (referred to as the "Web Development Paradigm"). Here is a simple comparison of these two development paradigms.' @Entry @Component struct TextCollapseTest { @State title: string = FULL_TEXT; @State suffixStr: string = ''; - private expanded: Boolean = true; - private needProcess: boolean = true + private expanded: boolean = true; + private needProcess: boolean = true; + aboutToAppear(): void { this.process(); } @@ -63,6 +64,7 @@ struct TextCollapseTest { // Collapse text collapseText(): void { if (!this.needProcess) { + this.suffixStr = ''; return; } // Size of expanded text @@ -81,18 +83,19 @@ struct TextCollapseTest { }); // No processing needed when collapsed and expanded text heights are equal - if ((expandSize.height as number) == (collapseSize.height as number)) { + if (!expandSize || !collapseSize || (expandSize.height as number) == (collapseSize.height as number)) { this.needProcess = false; return; } - let clipTitle: string = FULL_TEXT + let clipTitle: string = FULL_TEXT; this.suffixStr = EXPAND_STR; // Use binary search to find string length that fits exactly two lines let leftCursor: number = 0; let rightCursor: number = this.title.length; let cursor: number = Math.floor(rightCursor / 2); let tempTitle: string = ''; + // Binary search to find the maximum text length fitting exactly two lines while (true) { tempTitle = this.title.substring(0, cursor) + ELLIPSIS + EXPAND_STR; const currentLinesTextSize: SizeOptions = this.getUIContext().getMeasureUtils().measureTextSize({ @@ -143,4 +146,5 @@ struct TextCollapseTest { .height('100%') } } + // [End text_collapse_test] \ No newline at end of file diff --git a/ArkUI/entry/src/main/ets/pages/TheOuterScrollScrollsTheEntireLayout.ets b/ArkUI/entry/src/main/ets/pages/TheOuterScrollScrollsTheEntireLayout.ets index 3db07704810eedddef3036e88286150b425dd45d..2fca26430757adba54c68e6c58ef2d612d6cadc8 100644 --- a/ArkUI/entry/src/main/ets/pages/TheOuterScrollScrollsTheEntireLayout.ets +++ b/ArkUI/entry/src/main/ets/pages/TheOuterScrollScrollsTheEntireLayout.ets @@ -36,8 +36,8 @@ export struct ScrollNestingList { }, (item: string) => item) } .nestedScroll({ - scrollForward: NestedScrollMode.PARENT_FIRST, - scrollBackward: NestedScrollMode.SELF_FIRST + scrollForward: NestedScrollMode.PARENT_FIRST, // Triggering the parent scroll first when scrolling down + scrollBackward: NestedScrollMode.SELF_FIRST // When scrolling up, the current List is triggered first }) .divider({ strokeWidth: 1, diff --git a/ArkUI/entry/src/main/ets/pages/ToggleComponentBlocksClickGestures.ets b/ArkUI/entry/src/main/ets/pages/ToggleComponentBlocksClickGestures.ets index a60952ff8a34e01b46ca6ff0311928a08621177f..287be8b765e7ecebf59efa0ad3307689f4aad75d 100644 --- a/ArkUI/entry/src/main/ets/pages/ToggleComponentBlocksClickGestures.ets +++ b/ArkUI/entry/src/main/ets/pages/ToggleComponentBlocksClickGestures.ets @@ -29,6 +29,7 @@ struct ToggleDrag { @State positionX: number = 0; @State positionY: number = 0; @State toggleIsOn: boolean = true; + // Marks whether the current drag state is used to block click events private isDragging: boolean = false; @@ -40,7 +41,7 @@ struct ToggleDrag { .selectedColor(Color.Pink) // Onchange callback precedes onActionEnd .onChange((isOn: boolean) => { - hilog.info(0x0000, 'testTag', 'xxx %{public}s', `onClick Toggle, isOn: ${isOn}`); + hilog.info(0x0000, 'TOGGLE_DRAG', 'xxx %{public}s', `onClick Toggle, isOn: ${isOn}`); console.info('isDragging======' + this.isDragging); if (isOn === this.toggleIsOn) { return; diff --git a/ArkUI/entry/src/main/ets/pages/TriggeringApplicationBackendRunningInCode.ets b/ArkUI/entry/src/main/ets/pages/TriggeringApplicationBackendRunningInCode.ets index aa5057be90847bee055ee2a39f924f9d588e41a1..3bd44ea652b03bfe4d7c4f80e0c7278640f3c69d 100644 --- a/ArkUI/entry/src/main/ets/pages/TriggeringApplicationBackendRunningInCode.ets +++ b/ArkUI/entry/src/main/ets/pages/TriggeringApplicationBackendRunningInCode.ets @@ -30,7 +30,10 @@ export struct BackgroundExecution { .width('40%') .onClick(() => { let windowStage = AppStorage.get('context') as window.WindowStage; - windowStage.getMainWindowSync().minimize(); + if (windowStage) { + // It can be minimized when it is the main window and hidden when it is a sub-window. + windowStage.getMainWindowSync().minimize(); + } }) } .height('100%') diff --git a/ArkUI/entry/src/main/ets/pages/ViewRangeOfTouchHotspots.ets b/ArkUI/entry/src/main/ets/pages/ViewRangeOfTouchHotspots.ets index af56edad8fb79e7e467813f2e61bd8b55c57f336..5ea269be222c233a1a4705dbf4dd546d98b4c2ac 100644 --- a/ArkUI/entry/src/main/ets/pages/ViewRangeOfTouchHotspots.ets +++ b/ArkUI/entry/src/main/ets/pages/ViewRangeOfTouchHotspots.ets @@ -24,9 +24,8 @@ struct TouchTargetExample { @State text: string = ''; @State x: number = 0; @State y: number = 0; - @State reg_width: string = '50%'; - @State reg_height: string = '100%'; - + @State regWidth: string = '50%'; + @State regHeight: string = '100%'; build() { Column({ space: 20 }) { @@ -36,15 +35,14 @@ struct TouchTargetExample { .responseRegion({ x: this.x, y: this.y, - width: this.reg_width, - height: this.reg_height + width: this.regWidth, + height: this.regHeight }) .onClick(() => { this.text = 'button1 clicked'; - console.info('button1 clicked: ' + this.x + ' ' + this.y + ' ' + this.reg_width + ' ' + this.reg_height); + console.info('button1 clicked: ' + this.x + ' ' + this.y + ' ' + this.regWidth + ' ' + this.regHeight); }) - Text(this.text) .margin({ top: 10 }) } @@ -52,4 +50,5 @@ struct TouchTargetExample { .margin({ top: 100 }) } } + // [End view_range_of_touch_hotspots] \ No newline at end of file diff --git a/ArkUI/entry/src/main/ets/pages/attributeModifier.ets b/ArkUI/entry/src/main/ets/pages/attributeModifier.ets index 89bc6b4d1aa19c95d76076bb53c2fcfb43c5879d..7a9e66e7d94e3eb2bcace11d01d3fd54a67b0881 100644 --- a/ArkUI/entry/src/main/ets/pages/attributeModifier.ets +++ b/ArkUI/entry/src/main/ets/pages/attributeModifier.ets @@ -31,6 +31,10 @@ export class CommodityText implements AttributeModifier { } applyNormalAttribute(instance: TextAttribute): void { + if (typeof this.textSize !== 'number' || this.textSize <= 0) { + throw new Error('Invalid textSize') + } + if (this.textType === TextType.TYPE_ONE) { instance.fontSize(this.textSize); instance.fontColor(Color.Orange); @@ -52,6 +56,8 @@ export class CommodityText implements AttributeModifier { instance.textAlign(TextAlign.Center); instance.border({ width: 1, color: Color.Orange, style: BorderStyle.Solid }); instance.margin({ right: 10 }); + } else { + console.log(`TYPE is ${this.textType}`); } } }