ArKTS: staic message simple UI

 项目结构:

1754151545344

 

一种:

/**
 # encoding: utf-8
 # 版权所有 2024 ©涂聚文有限公司
 # 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
 # 描述: https://developer.huawei.com/consumer/cn/doc/harmonyos-references/ohos-arkui-advanced-dialog
 # Author    : geovindu,Geovin Du 涂聚文. https://yesicon.app/
 # IDE       : DevEco Studio 5.1.1 HarmonyOS ArKTS
 # OS        : windows 10  ohpm install @coremail/mail_base     https://gitee.com/openharmony-tpc/ohos_mail_base
 # database  : mysql 9.0 sql server 2019, postgreSQL 17.0  Oracle 21c Neo4j
 # Datetime  : 2024/10/31 20:33
 # User      : geovindu
 # Product   : MyApplicatin
 # Project   : MyApplicatin
 # File      : WxList.ets
 * */
import { UserInfoBase } from '../../constant/UserInfoBase'
import { router } from '@kit.ArkUI';
import { TodoTitleNameUtils } from '../../pages/utils/TodoTitleNameUtils'
import { trustedAppService } from '@kit.DeviceSecurityKit';
import { CommonConstantWX } from '../../constant/CommonConstantWX'
import { UserMessageBase } from '../../constant/UserMessageBase';

// 2. 定义传递的参数类型(包含user属性)
interface UserParams {
  user: UserInfoBase;
}

@Entry
@Component
struct WxList {
  @State message: string = '聊天';
  @State users: UserInfoBase=new UserInfoBase() ;
  @State messagelist: Array<UserMessageBase> = CommonConstantWX.mUserMessage
  // 3. 获取参数并断言为UserParams类型
  //const params = router.getParams() as UserParams | undefined;

  aboutToAppear() {
    // 获取传递的参数
    const params =router.getParams() as UserParams | undefined;// router.getParams();
    if (params?.user) {
      this.users = params.user as UserInfoBase; // 类型转换,确保与传递的item结构一致

    }
  }
  build() {
    Column() {

      Row() {
        TodoTitleNameUtils({ isTitle: true, titleName: this.users.name === undefined ? "" : this.users.name })
      }
      .width('100%')
      .height('15pv')

      List() {
        ForEach(this.messagelist, (item: UserMessageBase) => {
          ListItem() {
            Column() {
              // 外层Row设置主轴靠右对齐,确保内部元素整体靠右
              Row() {
                if(item.category===0) {
                  Image(item.img)
                    .width(40)
                    .height(50)
                    .margin({right: 8})
                    .borderRadius(5)
                    .objectFit(ImageFit.Contain)
                  // 移除不必要的align,由外层Row统一控制对齐
                }
                Text(item.content)
                  .fontSize($r('app.float.pagemessagesize'))
                  .fontWeight(FontWeight.Bold)
                  .backgroundColor(item.category===0?'#ffffff': '#ff81cd0a') // 白色背景
                  .borderRadius(10) // 圆角效果,数值可调整
                  .padding({ left: 12, right: 12, top: 8, bottom: 8 }) // 文本与背景的内边距
                  .margin({ right: 8 }) // 图片与文本之间的间距
                  .onClick(() => {
                    router.pushUrl({
                      url: 'pages/weixin/WXHome',
                    })
                  })
                if(item.category===1) {
                  Image(item.img)
                    .width(40)
                    .height(50)
                  .margin({left: 8})
                    .borderRadius(5)
                    .objectFit(ImageFit.Contain)
                  // 移除不必要的align,由外层Row统一控制对齐
                }
              }
              .width('100%')
              .justifyContent(item.category===0?FlexAlign.Start:FlexAlign.End) // 关键:Row内元素靠右排列 FlexAlign.End
              .align(item.category===0?Alignment.Start:Alignment.End) // Alignment.End
              .margin({ right: 1})
            }
            .alignItems(item.category===0?HorizontalAlign.Start:HorizontalAlign.End) // 确保Column的子元素(Row)靠右对齐 HorizontalAlign.End
            .align(item.category===0?Alignment.Start:Alignment.End) //Alignment.End
            // 可根据需要添加整体外边距
            .margin({ right: 12, top: 8, bottom: 8 })



          }.align(item.category===0?Alignment.Start:Alignment.End) // Alignment.End
        })
      }.height('80%')
      .width('100%')
      .backgroundColor('#ccc')
      .scrollSnapAlign(ScrollSnapAlign.START)

      Row({ space: 8 }) {
        // 语音按钮
        Image($r('app.media.SoundHighSolid'))
          .width(30)
          .height(30)
          .objectFit(ImageFit.Contain)
          .onClick(() => {
            router.pushUrl({
              url: 'pages/weixin/WXHome',
            })
          })

        // 输入框
        TextInput({ placeholder: '请输入消息...'})
          .id('WxListHelloWorld')
          .fontSize($r('app.float.page_text_font_size'))
          .fontWeight(FontWeight.Normal)
          .backgroundColor('#ffffff')
          .borderRadius(20)  // 圆角输入框
          .padding({ left: 16, right: 16 })  // 文本内边距
          .onClick(() => {
            this.message = this.users?.name || "";
          })
          .flexGrow(1)  // 自动填充剩余空间
          .width('75%')
        // 发送按钮
        Button('+')
          .fontSize(18)
          .width(40)
          .height(40)
          .borderRadius(20)  // 圆形按钮
          .backgroundColor('#07C160')  // 微信绿
          //.textStyle({ color: '#ffffff' })
          .onClick(() => {
            router.back()
          })
      }
      .margin({ top: 8, left: 12, right: 12, bottom: 8 })  // 整体外边距
      .height(50)  // 合适的高度
      .backgroundColor('#f5f5f5')  // 浅灰背景
      .alignItems(VerticalAlign.Center)  // 垂直居中对齐
      .width('100%')
    }
  }
}

  

二种:

/**
 # encoding: utf-8
 # 版权所有  2025 ©涂聚文有限公司™ ®
 # 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
 # 描述:
 # Author    : geovindu,Geovin Du 涂聚文.
 # IDE       : DevEco Studio 5.1.1  HarmonyOS ArKTS
 # os        : windows 10
 # database  : mysql 9.0 sql server 2019, postgreSQL 17.0  Oracle 21c Neo4j
 # Datetime  : 2025/8/2 23:56
 # User      :  geovindu
 # Product   : DevEco Studio
 # Project   : SQLiteApp
 # File      : WxControl.ets
 **/
import { UserMessageBase } from '../constant/UserMessageBase';
import { router } from '@kit.ArkUI';
 
@Component//表示组件
export default struct WxControl {
 
  @Prop useritem:UserMessageBase=new UserMessageBase
 
  build() {
 
    // 外层Row设置主轴靠右对齐,确保内部元素整体靠右
    Row() {
      if(this.useritem.category===0) {
        Image(this.useritem.img)
          .width(40)
          .height(50)
          .margin({right: 8})
          .borderRadius(5)
          .objectFit(ImageFit.Contain)
        // 移除不必要的align,由外层Row统一控制对齐
      }
      Text(this.useritem.content)
        .fontSize($r('app.float.pagemessagesize'))
        .fontWeight(FontWeight.Bold)
        .backgroundColor(this.useritem.category===0?'#ffffff': '#ff81cd0a') // 白色背景
        .borderRadius(10) // 圆角效果,数值可调整
        .padding({ left: 12, right: 12, top: 8, bottom: 8 }) // 文本与背景的内边距
        .margin({ right: 8 }) // 图片与文本之间的间距
        .onClick(() => {
          router.pushUrl({
            url: 'pages/weixin/WXHome',
          })
        })
      if(this.useritem.category===1) {
        Image(this.useritem.img)
          .width(40)
          .height(50)
          .margin({left: 8})
          .borderRadius(5)
          .objectFit(ImageFit.Contain)
        // 移除不必要的align,由外层Row统一控制对齐
      }
    }
    .width('100%')
    .justifyContent(this.useritem.category===0?FlexAlign.Start:FlexAlign.End) // 关键:Row内元素靠右排列 FlexAlign.End
    .align(this.useritem.category===0?Alignment.Start:Alignment.End) // Alignment.End
    .margin({ right: 1})
 
  }
 
}
 
 
/**
 # encoding: utf-8
 # 版权所有 2024 ©涂聚文有限公司
 # 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
 # 描述: https://developer.huawei.com/consumer/cn/doc/harmonyos-references/ohos-arkui-advanced-dialog
 # Author    : geovindu,Geovin Du 涂聚文. https://yesicon.app/
 # IDE       : DevEco Studio 5.1.1 HarmonyOS ArKTS
 # OS        : windows 10  ohpm install @coremail/mail_base     https://gitee.com/openharmony-tpc/ohos_mail_base
 # database  : mysql 9.0 sql server 2019, postgreSQL 17.0  Oracle 21c Neo4j
 # Datetime  : 2024/10/31 20:33
 # User      : geovindu
 # Product   : MyApplicatin
 # Project   : MyApplicatin
 # File      : WxList.ets
 * */
import { UserInfoBase } from '../../constant/UserInfoBase'
import { router } from '@kit.ArkUI';
import { TodoTitleNameUtils } from '../../pages/utils/TodoTitleNameUtils'
import { trustedAppService } from '@kit.DeviceSecurityKit';
import { CommonConstantWX } from '../../constant/CommonConstantWX'
import { UserMessageBase } from '../../constant/UserMessageBase';
import WxControl, {  } from '../../Control/WxControl'
import { it } from '@ohos/hypium';
 
// 2. 定义传递的参数类型(包含user属性)
interface UserParams {
  user: UserInfoBase;
}
 
@Entry
@Component
struct WxList {
  @State message: string = '聊天';
  @State users: UserInfoBase=new UserInfoBase() ;
  @State messagelist: Array<UserMessageBase> = CommonConstantWX.mUserMessage
  // 3. 获取参数并断言为UserParams类型
  //const params = router.getParams() as UserParams | undefined;
 
  aboutToAppear() {
    // 获取传递的参数
    const params =router.getParams() as UserParams | undefined;// router.getParams();
    if (params?.user) {
      this.users = params.user as UserInfoBase; // 类型转换,确保与传递的item结构一致
 
    }
  }
  build() {
    Column() {
 
      Row() {
        TodoTitleNameUtils({ isTitle: true, titleName: this.users.name === undefined ? "" : this.users.name })
      }
      .width('100%')
      .height('15pv')
 
      List() {
        ForEach(this.messagelist, (item: UserMessageBase) => {
          ListItem() {
            Column() {
              // 外层Row设置主轴靠右对齐,确保内部元素整体靠右
              WxControl({ useritem: item }) //引用用户控件
            }
            .alignItems(item.category===0?HorizontalAlign.Start:HorizontalAlign.End) // 确保Column的子元素(Row)靠右对齐 HorizontalAlign.End
            .align(item.category===0?Alignment.Start:Alignment.End) //Alignment.End
            // 可根据需要添加整体外边距
            .margin({ right: 12, top: 8, bottom: 8 })
 
 
 
          }.align(item.category===0?Alignment.Start:Alignment.End) // Alignment.End
        })
      }.height('80%')
      .width('100%')
      .backgroundColor('#ccc')
      .scrollSnapAlign(ScrollSnapAlign.START)
 
      Row({ space: 8 }) {
        // 语音按钮
        Image($r('app.media.SoundHighSolid'))
          .width(30)
          .height(30)
          .objectFit(ImageFit.Contain)
          .onClick(() => {
            router.pushUrl({
              url: 'pages/weixin/WXHome',
            })
          })
 
        // 输入框
        TextInput({ placeholder: '请输入消息...'})
          .id('WxListHelloWorld')
          .fontSize($r('app.float.page_text_font_size'))
          .fontWeight(FontWeight.Normal)
          .backgroundColor('#ffffff')
          .borderRadius(20)  // 圆角输入框
          .padding({ left: 16, right: 16 })  // 文本内边距
          .onClick(() => {
            this.message = this.users?.name || "";
          })
          .flexGrow(1)  // 自动填充剩余空间
          .width('75%')
        // 发送按钮
        Button('+')
          .fontSize(18)
          .width(40)
          .height(40)
          .borderRadius(20)  // 圆形按钮
          .backgroundColor('#07C160')  // 微信绿
          //.textStyle({ color: '#ffffff' })
          .onClick(() => {
            router.back()
          })
      }
      .margin({ top: 8, left: 12, right: 12, bottom: 8 })  // 整体外边距
      .height(50)  // 合适的高度
      .backgroundColor('#f5f5f5')  // 浅灰背景
      .alignItems(VerticalAlign.Center)  // 垂直居中对齐
      .width('100%')
    }
  }
}

  

 

import { UserInfoBase } from '../../constant/UserInfoBase'
import { CommonConstantWX } from '../../constant/CommonConstantWX'
import { router } from '@kit.ArkUI';
import promptAction from '@ohos.promptAction'
import { BusinessError } from '@ohos.base';

@Entry
@Component
struct WXHome {
  @State homeList: Array<UserInfoBase> = CommonConstantWX.contactsList
  build() {
    Column(){
      Search({placeholder: '搜索'})
        .width('90%')
        .backgroundColor(Color.White)
        .borderRadius(10)
      /*//搜索框按钮
        .searchButton('搜索')
      //提示词的设置文本颜色,大小,
        .placeholderColor(Color.Red)
        .placeholderFont({size: 20,weight: 700})
      //提交逻辑,点击放大镜和搜索按钮都会触发
        .onSubmit(() => {
          console.log('点击了提交');
        })
      //文本改变的逻辑,在输入框输入或者删除都会触发
        .onChange((value: string) => {
          console.log('文本改变' +  value);
        })*/
      List(){
        ForEach(this.homeList,(item: UserInfoBase) => {
           ListItem(){
             Column({space: 8}) {
               Row({ space: 20 }) {
                 Image(item.img)
                   .width(40)
                   .height(50)
                   .objectFit(ImageFit.Contain)
                   .borderRadius(5)
                 .onClick(() => {
                   router.pushUrl({
                     url: 'pages/Index',
                   })
                 })
                 Text(item.name)
                   .onClick(() => {
                     // 页面跳转并传递参数
                     router.pushUrl({
                       url: 'pages/weixin/WxList', // 目标页面路径
                       params: {
                         user: item // 需要传递的参数
                       }
                     }, router.RouterMode.Single) // 可选参数,指定路由模式
                       .then(() => {
                         console.log('页面跳转成功');
                       }).catch(() => {
                       console.log('页面跳转失败:');
                       promptAction.showToast({
                         message: '页面跳转失败',
                         duration: 2000
                       })
                     })

                   })

               }
               .justifyContent(FlexAlign.Start)
               Row(){
                 Divider()
                   .height(0.5)
                   .backgroundColor(Color.Gray)
               }
             }.alignItems(HorizontalAlign.Start)
           }

        })
      }

    }
    .width('100%')
    .height('100%')
    .backgroundColor('#ffd7d6d6')
  }
}

  

 

/**
 # encoding: utf-8
 # 版权所有  2025 ©涂聚文有限公司™ ®
 # 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
 # 描述:
 # Author    : geovindu,Geovin Du 涂聚文.
 # IDE       : DevEco Studio 5.1.1  HarmonyOS ArKTS
 # os        : windows 10
 # database  : mysql 9.0 sql server 2019, postgreSQL 17.0  Oracle 21c Neo4j
 # Datetime  : 2025/8/2 23:56
 # User      :  geovindu
 # Product   : DevEco Studio
 # Project   : SQLiteApp
 # File      : WXHome.ets
 **/
import { UserInfoBase } from '../../constant/UserInfoBase'
import { CommonConstantWX } from '../../constant/CommonConstantWX'
import { router } from '@kit.ArkUI';
import promptAction from '@ohos.promptAction'
import { BusinessError } from '@ohos.base';


@Entry
@Component
struct WXHome {
  @State homeList: Array<UserInfoBase> = []
  @State searchText: string = ''

  aboutToAppear() {
    this.initData();
  }

  private initData() {
    try {
      // 强制使用默认测试数据,排除数据源问题
      this.homeList =  CommonConstantWX.contactsList
      console.log('初始化默认数据成功,长度:', this.homeList.length);
    } catch (err) {
      console.error('初始化数据异常:', JSON.stringify(err));
      this.homeList = [];
    }
  }

  // 强化版过滤逻辑
  get filteredList(): Array<UserInfoBase> {
    try {
      // 1. 校验数据源基础格式
      if (!Array.isArray(this.homeList)) {
        console.error('homeList不是数组,类型:', typeof this.homeList);
        return [];
      }
      if (this.homeList.length === 0) {
        console.log('homeList为空数组,返回空结果');
        return [];
      }

      // 2. 处理搜索文本
      const searchText = (this.searchText || '').trim();
      if (!searchText) {
        console.log('搜索文本为空,返回全部数据');
        return [...this.homeList]; // 返回副本避免引用问题
      }

      // 3. 执行过滤(严格类型检查)
      const lowerSearchText = searchText.toLowerCase();
      const result: UserInfoBase[] = [];

      for (const item of this.homeList) {
        // 逐个检查item合法性
        if (!item || typeof item !== 'object') {
          console.warn('跳过非法item:', item);
          continue;
        }
        // 安全处理name属性
        const itemName = typeof item.name === 'string' ? item.name.toLowerCase() : '';
        if (itemName.includes(lowerSearchText)) {
          result.push(item);
        }
      }

      console.log(`搜索完成,关键词:${searchText},结果数:${result.length}`);
      return result;
    } catch (err) {
      // 打印完整错误堆栈
      console.error('过滤逻辑异常:', JSON.stringify(err), (err as Error).stack);
      return [];
    }
  }

  build() {
    Column(){
      Search({ placeholder: '搜索联系人' })
        .width('90%')
        .backgroundColor(Color.White)
        .borderRadius(10)
        .searchButton('搜索')
        .placeholderColor('#999')
        .placeholderFont({ size: 16, weight: FontWeight.Normal })
        .onSubmit((value: string) => {
          try {
            console.log('开始处理搜索提交,value:', value);
            this.searchText = value;

            // 直接使用同步计算的结果(避免setTimeout的异步问题)
            const resultCount = this.filteredList.length;
            console.log('搜索结果数量:', resultCount);

            // 严格按照文档要求调用showToast(参数必须正确)
            promptAction.showToast({
              message: resultCount > 0
                ? `找到${resultCount}个联系人`
                : '未找到匹配的联系人',
              duration: 1500, // 必须是1500或3000
              bottom: 100 // 可选:设置显示位置,避免被键盘遮挡
            })

          } catch (err) {
            console.error('搜索提交异常:', JSON.stringify(err), (err as Error).stack);
            // 简化错误提示的调用参数,确保不抛错
            promptAction.showToast({
              message: '搜索失败',
              duration: 1500
            });
          }
        })
        .onChange((value: string) => {
          this.searchText = value;
        })
        .margin({ top: 10 })
      //this.filteredList
      List() {
        ForEach(this.homeList,(item: UserInfoBase) => {
          ListItem(){
            Column({space: 8}) {
              Row({ space: 20 }) {
                Image(item.img)
                  .width(40)
                  .height(50)
                  .objectFit(ImageFit.Contain)
                  .borderRadius(5)
                  .onClick(() => {
                    router.pushUrl({
                      url: 'pages/Index',
                    })
                  })
                Text(item.name)
                  .onClick(() => {
                    // 页面跳转并传递参数
                    router.pushUrl({
                      url: 'pages/weixin/WxList', // 目标页面路径
                      params: {
                        user: item // 需要传递的参数
                      }
                    }, router.RouterMode.Single) // 可选参数,指定路由模式
                      .then(() => {
                        console.log('页面跳转成功');
                      }).catch(() => {
                      console.log('页面跳转失败:');
                      promptAction.showToast({
                        message: '页面跳转失败',
                        duration: 2000
                      })
                    })

                  })

              }
              .justifyContent(FlexAlign.Start)
              Row(){
                Divider()
                  .height(0.5)
                  .backgroundColor(Color.Gray)
              }
            }.alignItems(HorizontalAlign.Start)
          }
        }
          //(item) => item.id?.toString() || `key-${Math.random()}`
        )
      }
      .flexGrow(1)
      .width('100%')
      .margin({ top: 10 })
    }
    .width('100%')
    .height('100%')
    .backgroundColor('#ffd7d6d6')
  }
}

  

第三种:

import { it } from '@ohos/hypium'
import { UserInfoBase } from '../constant/UserInfoBase'
import { CommonConstantWX } from '../constant/CommonConstantWX'
import { router } from '@kit.ArkUI'
import promptAction from '@ohos.promptAction'

@Entry
@Component
struct WXHome {
  @State homeList: Array<UserInfoBase> = CommonConstantWX.contactsList
  @State searchList:Array<UserInfoBase>=[]
  //变量承载输入框的内容
  @State mContent: string = ''
  //创建控制器,控制信息展示最新信息
  private listScroller: Scroller = new Scroller()
  //创建变量,控制信息为对方还是自己发的信息
  @State mCategory: number = 0

  build() {
    Column(){
      Search({placeholder: '搜索'})
        .width('90%')
        .backgroundColor(Color.White)
        .borderRadius(10)
        .onChange((value: string) => {
          //清除之前搜索到数据
          this.searchList = []
          //处理到底找到了几条符合数据
          let searchCount = 0
          //进行便利查找
          for(let index = 0;index < this.homeList.length; index ++ ){
            const element = this.homeList[index]
            //进行判断
            if (element.name?.indexOf(value) != -1) {
              searchCount ++
              //相同数据填充到新数组里
              this.searchList.push(element)
            }
          }
          //没有找到相应数据
          if (searchCount === 0) {
            this.searchList.push({
              id: 999,
              name:"没有找到相应用户",
              img: $r('app.media.avatar_icon')
            })
          }
        })

      /*//搜索框按钮
        .searchButton('搜索')
      //提示词的设置文本颜色,大小,
        .placeholderColor(Color.Red)
        .placeholderFont({size: 20,weight: 700})
      //提交逻辑,点击放大镜和搜索按钮都会触发
        .onSubmit(() => {
          console.log('点击了提交');
        })
      //文本改变的逻辑,在输入框输入或者删除都会触发
        .onChange((value: string) => {
          console.log('文本改变' +  value);
        })*/
      List({space: 10,scroller: this.listScroller}){
        ForEach(this.searchList.length === 0 ?this.homeList : this.searchList,(item: UserInfoBase) => {
          ListItem(){
            Column({space: 8}) {
              Row({ space: 20 }) {
                Image(item.img)
                  .width(40)
                  .height(50)
                  .objectFit(ImageFit.Contain)
                  .borderRadius(5)
                  .onClick(() => {
                    router.pushUrl({
                      url: 'pages/Index',
                    })
                  })
                Text(item.name)
                  .onClick(() => {
                    // 页面跳转并传递参数
                    router.pushUrl({
                      url: 'pages/weixin/WxList', // 目标页面路径
                      params: {
                        user: item // 需要传递的参数
                      }
                    }, router.RouterMode.Single) // 可选参数,指定路由模式
                      .then(() => {
                        console.log('页面跳转成功');
                      }).catch(() => {
                      console.log('页面跳转失败:');
                      promptAction.showToast({
                        message: '页面跳转失败',
                        duration: 2000
                      })
                    })

                  })

              }
              //.padding({top:10,bottom:10})
              .margin({left:10})
              .justifyContent(FlexAlign.Start)
              Row(){
                Divider()
                  .height(0.5)
                  .backgroundColor(Color.Gray)
              }
            }.alignItems(HorizontalAlign.Start)
          }.margin({bottom:10})

        })
      }
      .padding({bottom:50})

    }
    .width('100%')
    .height('100%')
    .backgroundColor('#ffd7d6d6')
  }
}

 

/**
 # encoding: utf-8
 # 版权所有 2024 ©涂聚文有限公司
 # 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
 # 描述: https://developer.huawei.com/consumer/cn/doc/harmonyos-references/ohos-arkui-advanced-dialog
 # Author    : geovindu,Geovin Du 涂聚文. https://yesicon.app/
 # IDE       : DevEco Studio 5.1.1 HarmonyOS ArKTS
 # OS        : windows 10  ohpm install @coremail/mail_base     https://gitee.com/openharmony-tpc/ohos_mail_base
 # database  : mysql 9.0 sql server 2019, postgreSQL 17.0  Oracle 21c Neo4j
 # Datetime  : 2024/10/31 20:33
 # User      : geovindu
 # Product   : MyApplicatin
 # Project   : MyApplicatin
 # File      : WxList.ets
 * */
import { UserInfoBase } from '../../pages/constant/UserInfoBase'
import { router } from '@kit.ArkUI';
import { TodoTitleNameUtils } from '../../pages/utils/TodoTitleNameUtils'
import { trustedAppService } from '@kit.DeviceSecurityKit';
import { CommonConstantWX } from '../../pages/constant/CommonConstantWX'
import { UserMessageBase } from '../../pages/constant/UserMessageBase';
import WxControl, {  } from '../../Control/WxControl'
import { it } from '@ohos/hypium';

// 2. 定义传递的参数类型(包含user属性)
interface UserParams {
  user: UserInfoBase;
}

@Entry
@Component
struct WxList {
  @State message: string = '聊天';
  @State users: UserInfoBase=new UserInfoBase() ;
  @State messagelist: Array<UserMessageBase> = CommonConstantWX.mUserMessage
  // 3. 获取参数并断言为UserParams类型
  //const params = router.getParams() as UserParams | undefined;
  //变量承载输入框的内容
  @State mContent: string = ''
  //创建控制器,控制信息展示最新信息
  private listScroller: Scroller = new Scroller()
  //创建变量,控制信息为对方还是自己发的信息
  @State mCategory: number = 0


  aboutToAppear() {
    // 获取传递的参数
    const params =router.getParams() as UserParams | undefined;// router.getParams();
    if (params?.user) {
      this.users = params.user as UserInfoBase; // 类型转换,确保与传递的item结构一致

    }
  }
  build() {
    Column() {

      Row() {
        TodoTitleNameUtils({ isTitle: true, titleName: this.users.name === undefined ? "" : this.users.name })
      }
      .width('100%')
      .height('15pv')

      List({space: 10,scroller: this.listScroller}) {
        ForEach(this.messagelist, (item: UserMessageBase) => {
          ListItem() {
            Column() {
              // 外层Row设置主轴靠右对齐,确保内部元素整体靠右
              WxControl({ useritem: item }) //引用用户控件
            }
            .alignItems(item.category===0?HorizontalAlign.Start:HorizontalAlign.End) // 确保Column的子元素(Row)靠右对齐 HorizontalAlign.End
            .align(item.category===0?Alignment.Start:Alignment.End) //Alignment.End
            // 可根据需要添加整体外边距
            .margin({ right: 12, top: 8, bottom: 8 })



          }.align(item.category===0?Alignment.Start:Alignment.End) // Alignment.End
        })
      }.height('80%')
      .width('100%')
      .backgroundColor('#ccc')
      .scrollSnapAlign(ScrollSnapAlign.START)

      Row({ space: 8 }) {
        // 语音按钮
        Image($r('app.media.SoundHighSolid'))
          .width(30)
          .height(30)
          .padding({left:5})
          .objectFit(ImageFit.Contain)
          .onClick(() => {
            router.pushUrl({
              url: 'pages/weixin/WXHome',
            })
          })

        // 输入框
        TextInput({ placeholder: '请输入消息...',text:this.mContent})
          .id('WxListHelloWorld')
          .fontSize($r('app.float.page_text_font_size'))
          .fontWeight(FontWeight.Normal)
          .backgroundColor('#ffffff')
          .borderRadius(20)  // 圆角输入框
          .padding({ left: 16, right: 16 })  // 文本内边距
          .onChange((value:string)=>{
            this.mContent = value
          })
          .flexGrow(1)  // 自动填充剩余空间
          .width('75%')

        // 发送按钮
        //如果输入框里面有内容,隐藏图片,显示发送按钮
        //.trim()去掉空格  length判断文本长度
        if (!this.mContent || this.mContent.trim().length === 0){
          Button('+')
            .fontSize(18)
            .width(40)
            .height(40)
            .borderRadius(20)  // 圆形按钮
            .padding({right:15})
            .margin({right:5})
            .backgroundColor('#07C160')  // 微信绿
            //.textStyle({ color: '#ffffff' })
            .onClick(() => {
              //router.back()
              this.message = this.users?.name || "";
              //点击发送按钮,发送信息
              this.messagelist.push({
                id: 7,
                img: this.mCategory % 2 === 0 ? this.users.img : $r("app.media.avatar_icon1"),
                content: this.mContent,
                category: this.mCategory % 2 === 0 ? 0 : 1

              })
            })
        } else {
          Button() {
            Text('发送')
              .fontSize(12)
              .fontColor(Color.White)
              .onClick(()=>{
                //router.back()
                this.message = this.users?.name || "";
                //点击发送按钮,发送信息
                this.messagelist.push({
                  id: 7,
                  img: this.mCategory % 2 === 0 ? this.users.img : $r("app.media.avatar_icon1"),
                  content: this.mContent,
                  category: this.mCategory % 2 === 0 ? 0 : 1

                })
                //清空输入框数据
                this.mContent = ''
                this.listScroller.scrollToIndex(this.messagelist.length -1)
                this.mCategory ++
              })

          }
        }
      }
      .margin({ top: 8, left: 12, right: 12, bottom: 8 })  // 整体外边距
      .height(50)  // 合适的高度
      .backgroundColor('#f5f5f5')  // 浅灰背景
      .alignItems(VerticalAlign.Center)  // 垂直居中对齐
      .width('100%')
    }
  }
}

  

/**
 # encoding: utf-8
 # 版权所有  2025 ©涂聚文有限公司™ ®
 # 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
 # 描述:
 # Author    : geovindu,Geovin Du 涂聚文.
 # IDE       : DevEco Studio 5.1.1  HarmonyOS ArKTS
 # os        : windows 10
 # database  : mysql 9.0 sql server 2019, postgreSQL 17.0  Oracle 21c Neo4j
 # Datetime  : 2025/8/2 23:56
 # User      :  geovindu
 # Product   : DevEco Studio
 # Project   : SQLiteApp
 # File      : WxControl.ets
 **/
import { UserMessageBase } from '../constant/UserMessageBase';
import { UserInfoBase } from '../constant/UserInfoBase'
import { router } from '@kit.ArkUI';

@Component//表示组件
export default struct WxControl {

  @Prop useritem: UserMessageBase;
  @Prop userinfo: UserInfoBase;

  build() {

    // 外层Row设置主轴靠右对齐,确保内部元素整体靠右
    Row() {
      if(this.useritem.category===0) {
        Image(this.userinfo.img)
          .width(40)
          .height(50)
          .margin({right: 8})
          .borderRadius(5)
          .objectFit(ImageFit.Contain)
        // 移除不必要的align,由外层Row统一控制对齐
      }
      Text(this.useritem.content)
        .fontSize($r('app.float.pagemessagesize'))
        .fontWeight(FontWeight.Bold)
        .backgroundColor(this.useritem.category===0?'#ffffff': '#ff81cd0a') // 白色背景
        .borderRadius(10) // 圆角效果,数值可调整
        .padding({ left: 12, right: 12, top: 8, bottom: 8 }) // 文本与背景的内边距
        .margin({ right: 8 }) // 图片与文本之间的间距
        .onClick(() => {
          router.pushUrl({
            url: 'pages/weixin/WXHome',
            params: {
              user: this.useritem // 需要传递的参数
            }
          })
        })
        .width('70%')
      if(this.useritem.category===1) {
        Image(this.useritem.img)
          .ImgExtend()
        // 移除不必要的align,由外层Row统一控制对齐
      }
    }
    .width('100%')
    .justifyContent(this.useritem.category===0?FlexAlign.Start:FlexAlign.End) // 关键:Row内元素靠右排列 FlexAlign.End
    .align(this.useritem.category===0?Alignment.Start:Alignment.End) // Alignment.End
    .margin({ right: 1})

  }

}

@Extend(Image)
function ImgExtend() {
  .width(40)
  .height(50)
  .margin({ left: 8 })
  .borderRadius(5)
  .objectFit(ImageFit.Contain)
}

  

 

页面转值和获值

   .onClick(() => {
             router.pushUrl({
               url: 'pages/weixin/WXChatDetailsPage',
               params: {
                 userInfo: item
               }
             })

  

获取值

let params = router.getParams() as Record<string,UserInfoBase>
let mUserInfo = params.userInfo

  

 

image

 

aeea0a4f8d6bb345d850055d3ae0a23

 

 

import socket from '@ohos.net.socket';
import util from '@ohos.util';
import promptAction from '@ohos.promptAction'
import fs from '@ohos.file.fs';
import picker from '@ohos.file.picker';
import web_webview from '@ohos.web.webview'

  

image

 

13f3e0bd6163a18fb6450000772ae70

 

帮助文档: 

https://docs.openharmony.cn/pages/v5.1/zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-container-waterflow.md
https://developer.huawei.com/consumer/cn/doc/harmonyos-references/ohos-arkui-advanced-dialog

 

posted @ 2025-08-02 23:28  ®Geovin Du Dream Park™  阅读(12)  评论(0)    收藏  举报