当前位置: 首页 > article >正文

【每日学点鸿蒙知识】自定义弹窗实现分享、Badge切换闪动等

1、使用自定义弹窗实现分享弹窗?

希望实现分享弹窗效果:

  1. 底部弹出分享框,两行,可左右滑动
  2. 底部弹窗基础控件,内部内容可任意定制

参考代码:

import { BusinessError } from '@ohos.base';
import { ComponentContent } from "@ohos.arkui.node";
import { PromptAction } from '@kit.ArkUI';

class Params {
  ApplicationSharings: string[] = [];
  Sharings: string[] = [];
  promptAction: PromptAction;
  numss: number = 0

  constructor(ApplicationSharings: string[], Sharings: string[] = [], promptAction: PromptAction, numss: number) {
    this.ApplicationSharings = ApplicationSharings;
    this.Sharings = Sharings;
    this.promptAction = promptAction;
    this.numss = numss;
  }
}

@Builder
function buildText($$: Params) {
  Column() {
    Text('网页由mp.xxx.xxx.com提供')
      .fontSize(10)
    // .fontWeight(FontWeight.Bold)
    // .margin({bottom: 36})
    Grid() {
      ForEach($$.ApplicationSharings, (item: string, index) => {
        GridItem() {
          Column() {
            Image($r('app.media.app_icon'))
              .height(50).width(50)
            Text(item)
              .fontSize(10)
          }
        }
      })
    }
    .height(100)
    .rowsGap(20)
    .columnsGap(20)
    .scrollBar(BarState.Off)
    .rowsTemplate('1fr')

    Grid() {
      ForEach($$.Sharings, (item: string, index) => {
        GridItem() {
          Column() {
            Image($r('app.media.app_icon'))
              .height(50).width(50)
            Text(item)
              .fontSize(10)
          }
        }
      })
    }
    .height(100)
    .rowsGap(20)
    .columnsGap(20)
    .scrollBar(BarState.Off)
    .rowsTemplate('1fr')


    Button('取消')
      .width('100%')
      .fontColor(Color.Black)
      .backgroundColor(Color.White)
      .onClick(() => {
        /*let sasasa1 = LocalStorage.getShared()?.get('uiContext') as UIContext
        let sasasa = LocalStorage.getShared()?.get('PropAA') as ComponentContent<Params>
        try {
        $$.promptAction.closeCustomDialog(sasasa);
        } catch (error) {
        let message = (error as BusinessError).message;
        let code = (error as BusinessError).code;
        console.error(`:::OpenCustomDialog args error code is ${code}, message is ${message}`);
        };*/
        let link1: SubscribedAbstractProperty<number> = storage.link('PropA');
        let numsss = link1.get()
        console.log(':::numsss', link1.get())
        link1.set(++numsss)
        // $$.numss++
        // console.log(':::$$.numss',$$.numss)
      })

  }
  .backgroundColor('#FFF0F0F0')
  .width('90%')
  .height('30%')
  .borderRadius(10)
}


let para: Record<string, number> = { 'PropA': 1 };
let storage: LocalStorage = new LocalStorage(para); // 创建新实例并使用给定对象初始化


// let globalBuilder: WrappedBuilder<[Params]> = wrapBuilder(buildText);

@Entry(storage)
@Component
struct CustomDialogDemo {
  @State message: string = "hello"
  @State ApplicationSharings: string[] =
    ['转发', '群发给客户', '群发到客户群', '分享到同事吧', '收藏', '群发到客户群', '分享到同事吧', '收藏', '刷新',
      '翻译', '复制链接', '调整字体', '刷新', '翻译']
  @State Sharings: string[] = ['最小化', '复制链接', '调整字体', '刷新', '翻译', '复制链接', '调整字体', '刷新', '翻译']
  @LocalStorageLink('PropA') @Watch('onchang') nums: number = 0;
  // @State @Watch('onchang') nums :number = 0;


  @LocalStorageLink('uiContext') aaa: UIContext = this.getUIContext();
  @LocalStorageLink('PropAA') shjsh: ComponentContent<Params> | null =
    null //new ComponentContent(this.aaa,wrapBuilder(ssss));

  // @LocalStorageLink('PropAA') shjsh:ComponentContent<Params> = new ComponentContent(this.aaa, globalBuilder);

  aboutToAppear(): void {
    // setInterval(()=>{
    // console.log(":::nums",this.nums)
    // },1000)
  }

  onchang() {
    console.log('::: onchang')
    try {
      this.aaa.getPromptAction().closeCustomDialog(this.shjsh);
    } catch (error) {
      let message = (error as BusinessError).message;
      let code = (error as BusinessError).code;
      console.error(`OpenCustomDialog args error code is ${code}, message is ${message}`);
    }
    ;
  }

  build() {
    Row() {
      Column() {
        TextInput()
          .id('aaa')
          .visibility(Visibility.None)
        Button("click me")
          .onClick(() => {
            let uiContext = this.getUIContext();
            let promptAction = uiContext.getPromptAction();
            let contentNode = new ComponentContent(uiContext, wrapBuilder(buildText),
              new Params(this.ApplicationSharings, this.Sharings, promptAction, this.nums));
            this.shjsh = contentNode
            try {
              promptAction.openCustomDialog(contentNode);
            } catch (error) {
              let message = (error as BusinessError).message;
              let code = (error as BusinessError).code;
              console.error(`OpenCustomDialog args error code is ${code}, message is ${message}`);
            }
            ;
          })
      }
      .width('100%')
      .height('100%')
    }
    .height('100%')
  }
}

2、Badge有数量与无数量切换时会发生闪动?

下面两种场景会导致闪动:

  • Badge有数量与无数量切换
  • 有Badge与无Badge切换

可使用onComplete时间,图片数据加载成功和解码成功时均触发该回调 https://developer.huawei.com/consumer/cn/doc/harmonyos-references-V5/development-intro-api-V5?catalogVersion=V5

参考代码:

@Entry
@Component
struct BadgeDemo {
  @State message: string = 'Hello World';
  @State sizes: string = '0'
  @State isDnd: boolean = false;

  build() {
    Row() {
      Text(this.message)
        .fontSize(50)
        .fontWeight(FontWeight.Bold)
        .onClick(() => {
          this.isDnd = !this.isDnd;
        })
      Stack() {
        Badge({
          value: '',
          position: { x: 40, y: 0 },
          style: { badgeSize: 15, badgeColor: Color.Red }
        }) {
          Image($r('app.media.icon'))
            .width(50)
            .height(50)
            .onComplete(() => {
              this.isDnd = !this.isDnd;
            })
        }
        .visibility(this.isDnd ? Visibility.Visible : Visibility.None)

        Badge({
          count: 98,
          maxCount: 99,
          position: { x: 30, y: 0 },
          style: { fontSize: 15, badgeSize: 15, badgeColor: Color.Red }
        }) {
          Image($r('app.media.icon'))
            .width(50)
            .height(50)
        }
        .visibility(this.isDnd ? Visibility.None : Visibility.Visible)
      }
    }
    .height('100%')
  }
}

3、如何延迟改变toggle状态且延时回调?(目前toggle组件响应点击之后会立刻渲染且立刻回调)

现有的toggle点击之后会立马发生改变且立刻回调,比如下面场景:
toggle处于关闭的状态,用户打开toggle,在打开过程中遇见某些问题,要重置开关为关闭,但这时候会触发toggle的状态变化回调方法,但实际上只是想重置,而不是走开关关闭的逻辑。

可以用hitTestBehavior和settimeout来解决:

@Entry
@Component
struct Index {
  @State isDarkMode: boolean = false
  build() {
    Column() {
      Column() {
        Toggle({ type: ToggleType.Switch, isOn: $$this.isDarkMode })

          .onChange((isOn: boolean) => {
            console.info('Toggle.onChange:isOn' + isOn)
            this.isDarkMode = isOn
            getContext(this).getApplicationContext().setColorMode(this.isDarkMode ? 0 : 1)
          })
      }
      .hitTestBehavior(HitTestMode.Block)
      .onClick(() => {
        setTimeout(() => {
          this.isDarkMode = !this.isDarkMode
        }, 10000)
      })
    }.width('100%').height('100%').padding(32)
  }
}

4、跟随系统,系统深色模式下getColorSync(resource)返回了浅色模式下的颜色值而不是深色的

有两种方案可参考:

  1. 通过传资源id
 getContext(component).resourceManager.getColorSync($r("app.color.xxx").id)
  1. 在深浅色配置的包中(配置了dark限定词目录的包)中的module.json5中添加配置
"metadata": [
  {
    "name": "ContextResourceConfigLoadFromParentTemp",
    "value": "true"
  }
]

5、汉字转拼音如何去掉音标?

可以先转拼音,再去音调。参考代码如下:

let transliterator = i18n.Transliterator.getInstance('Any-Latn');
let res = transliterator.transform('中国');

let transliterator2 = i18n.Transliterator.getInstance('Latin-ASCII');
let res2 = transliterator2.transform(res);

http://www.kler.cn/a/472484.html

相关文章:

  • Visio 画阀门 符号 : 电动阀的画法
  • Bash语言的数据库编程
  • 用豆包MarsCode IDE打造精美数据大屏:从零开始的指南
  • LangChain速成课程_构建基于OpenAI_LLM的应用
  • Springboot SAP Docker 镜像打包问题
  • SQL从入门到实战
  • sqlalchemy CreateIndex
  • 第一次使用Git上传本地项目到github上
  • 探索Rancher服务发现机制:容器世界的“导航仪”
  • Spring AI ectorStore
  • 刚体变换矩阵的逆
  • Godot最佳实践个人转述
  • Django中自定义模板字符串
  • Qt QDockWidget详解以及例程
  • 随机梯度下降(SGD)算法的深度剖析与应用探索
  • STM32L051芯片 超低功耗特性概览
  • 高级数据库系统 复习提纲
  • 空间不足导致Oracle集群内存使用率暴增
  • ctfshow 每日练习 web 区 php特性 1-10
  • Java将String类型的html文本中的img路径替换前缀
  • css预处理器sass
  • 设计基于检索增强生成的个性化语言模型(RAG-based LLM)
  • 深入了解 StarRocks 表类型:解锁高效数据分析的密码
  • 基于Spring Boot的电子文档交易系统
  • BERT:深度双向Transformer的预训练用于语言理解
  • 【Nginx】设置https和http同时使用同一个端口访问