选择图库图片后,再次选择图库会保留上次选择结果

​在三方获取图库图片时候,当选完图片返回后如果需要再次添加选择更多图片。想再此打开图库选择图片时,会将已经选择的图片信息传递给媒体库接口,让媒体库将图片状态变为已选择。

HarmonyOS
2024-05-21 20:51:25
浏览
收藏 0
回答 1
待解决
回答 1
按赞同
/
按时间
pumayze

使用的核心API

ohos.file.picker

核心代码介绍

@Entry 
@Component 
struct Index { 
  @State message: string = ''; 
  private resultUri: string[] = []; 
  @State mediaItems: string[] = [] 
  @State maxSelectCount: string = '0' 
  scroller: Scroller = new Scroller() 
  @State isShowSerialNum: boolean = false; 
  
  private context: common.UIAbilityContext = getContext() as common.UIAbilityContext; 
  
  
  aboutToAppear(){ 
    this.setPreferredOrientation( 
      // AppStorage.get<common.UIAbilityContext>('photosAbilityContext') as common.UIAbilityContext, 
      this.context, 
      window.Orientation.AUTO_ROTATION_RESTRICTED); 
  } 
  
  setPreferredOrientation(context: common.UIAbilityContext, orientation: number): void { 
    try { 
      window.getLastWindow(context, (err, data) => { 
        if (err.code || !data) { 
          // Log.error(TAG, 'Failed to obtain the top window. Cause: ' + JSON.stringify(err)); 
          return; 
        } 
        let windowClass = data; 
        windowClass.setPreferredOrientation(orientation, (err) => { 
          if (err.code) { 
            // Log.error(TAG, 'Failed to set window orientation. Cause: ' + JSON.stringify(err)); 
            return; 
          } 
          // Log.info(TAG, 'Succeeded in setting window orientation.'); 
        }); 
      }); 
    } catch (exception) { 
      // Log.error(TAG, 'Failed to set window orientation. Cause: ' + JSON.stringify(exception)); 
    } 
  } 
  
  private firstEnter() { 
    this.multiPick().then((result: ability.AbilityResult) => { 
      // Log.info(TAG, `AbilityResult = ${JSON.stringify(result)}`); 
      let want: Want | null = result.want as Want; 
      if (want == null || want.parameters == null) return; 
      this.resultUri = want.parameters['select-item-list'] as string[]; 
      // Log.info(TAG, `item list= ${JSON.stringify(this.resultUri)}`); 
      let length = this.resultUri.length; 
      this.message = `已选择 ${length} 张图片`; 
      this.mediaItems = [...this.resultUri] 
    }); 
  } 
  
  private secondEnter() { 
    this.multiPickWithData().then((result: ability.AbilityResult) => { 
      // Log.info(TAG, `AbilityResult = ${JSON.stringify(result)}`); 
      if (result.resultCode === -1) { 
        this.message = '' 
        this.resultUri = [] 
      } 
      let want: Want | null = result.want as Want; 
      if (want == null || want.parameters == null) return; 
      this.resultUri = want.parameters['select-item-list'] as string[]; 
      // Log.info(TAG, `item list= ${JSON.stringify(this.resultUri)}`); 
      let length = this.resultUri.length; 
      this.message = `已选择 ${length} 张图片`; 
      this.mediaItems = [...this.resultUri] 
    }); 
  } 
  
  
  @Builder showMediaItems() { 
    Column() { 
      Grid(this.scroller) { 
        ForEach(this.mediaItems, (item: string) => { 
          GridItem() { 
            if (item.endsWith('mp4')) { 
              Video({ src: item }) 
                .width('100%') 
                .height('100%') 
            } else { 
              Image(item) 
                .width('100%') 
                .height('100%') 
            } 
          } 
          .width('100%') 
          .aspectRatio(1) 
        }, (item: string) => item) 
      } 
      .columnsTemplate('1fr 1fr 1fr 1fr') 
      .columnsGap(10) 
      .rowsGap(10) 
      .onScrollIndex((first: number) => { 
        console.info(first.toString()) 
      }) 
      .height('100%') 
      .width('90%') 
    } 
    .width('100%') 
    .height(350) 
    .padding({ top: 10 }) 
  } 
  
  build() { 
    Column() { 
      Column() { 
        Text('模拟第三方应用') 
          .fontSize(40) 
      } 
  
      Column() { 
        Text(this.message) 
          .fontSize(30) 
          .fontWeight(FontWeight.Bold) 
      } 
  
      Column() { 
        Row() { 
          Text('最大选择数量: ') 
          TextInput({ placeholder: '请输入最大选择数量', text: this.maxSelectCount }) 
            .width(150) 
            .onChange((value: string) => { 
              this.maxSelectCount = value 
            }) 
        } 
      }.margin({ bottom: 10 }) 
  
      Column() { 
        Row() { 
          Text('是否显示序号: ') 
          Toggle({ type: ToggleType.Switch, isOn: false }) 
            .onChange((isShowSerialNum: boolean) => { 
              this.isShowSerialNum = isShowSerialNum 
            }) 
        } 
      }.margin({ bottom: 10 }) 
      Column() { 
        Button('选择') 
          .width(200) 
          .onClick(() => { 
            this.resultUri = this.resultUri?.length ? this.resultUri : [] 
            if (this.resultUri.length === 0) { 
              this.firstEnter() 
            } else { 
              this.secondEnter() 
            } 
          }) 
      } 
      .width("100%") 
      .justifyContent(FlexAlign.Center) 
      .alignItems(HorizontalAlign.Center) 
  
      // this.showMediaItems() 
    } 
    .height('100%') 
    .width('100%') 
    .padding({bottom:30}) 
  } 
  
  async singlePick(): Promise<ability.AbilityResult> { 
    // let context: common.UIAbilityContext = AppStorage.get<common.UIAbilityContext>('formContext') as common.UIAbilityContext; 
    let param: Want = { 
      bundleName: 'com.huawei.hmos.photos', 
      abilityName: 'com.huawei.hmos.photos.MainAbility', 
      parameters: { 
        uri: WANT_PARAM_URI_SELECT_SINGLE, 
      } 
    }; 
    // Log.debug(TAG, `routeToTimelinePage parm: ${JSON.stringify(param)}`); 
    let result = await this.context.startAbilityForResult(param); 
    return result; 
  } 
  
  async multiPick(): Promise<ability.AbilityResult> { 
    // let context: common.UIAbilityContext = AppStorage.get<common.UIAbilityContext>('formContext') as common.UIAbilityContext; 
    let param: Want = { 
      bundleName: 'com.huawei.hmos.photos', 
      abilityName: 'com.huawei.hmos.photos.MainAbility', 
      parameters: { 
        uri: WANT_PARAM_URI_SELECT_MULTIPLE, 
        preData: this.resultUri, 
        maxSelectCount: this.maxSelectCount, 
        isShowSerialNum: this.isShowSerialNum 
      } 
    }; 
    // Log.debug(TAG, `routeToTimelinePage parm: ${JSON.stringify(param)}`); 
    let result = await this.context.startAbilityForResult(param); 
    return result; 
  } 
  
  async multiPickWithData(): Promise<ability.AbilityResult> { 
    // let context: common.UIAbilityContext = AppStorage.get<common.UIAbilityContext>('formContext') as common.UIAbilityContext; 
    // Log.debug(TAG, `multiPickWithData`); 
    let param: Want = { 
      bundleName: 'com.huawei.hmos.photos', 
      abilityName: 'com.huawei.hmos.photos.MainAbility', 
      parameters: { 
        uri: WANT_PARAM_URI_SELECT_MULTIPLE, 
        preData: this.resultUri, 
        maxSelectCount: this.maxSelectCount, 
        isShowSerialNum: this.isShowSerialNum 
      } 
    }; 
    // Log.debug(TAG, `multiPickWithData parm: ${JSON.stringify(param)}`); 
    let result = await this.context.startAbilityForResult(param); 
    return result; 
  } 
}

实现效果

适配版本信息

DevEco Studio Version: 4.1.1.400

SDK:HarmoneyOS 4.1.0.25

分享
微博
QQ
微信
回复
2024-05-22 16:59:53
相关问题
拉起相册选择图片页面失败
562浏览 • 1回复 待解决
怎样让用户选择并加载图片
7547浏览 • 1回复 待解决
打开图库应用时偶尔闪退
1345浏览 • 0回复 待解决
进入相册或拍照选择图片做头像
12227浏览 • 2回复 已解决
把应用沙箱下的图片保存到图库
423浏览 • 1回复 待解决
分布式如何读写图库图片或者视频?
3292浏览 • 1回复 待解决
docker 容器怎么选择时区?
1274浏览 • 1回复 待解决
应用分类应该怎么选择
3744浏览 • 2回复 待解决
gamePlayerId和teamPlayerId怎么选择
690浏览 • 1回复 待解决
选择相册怎么等待返回啊?
925浏览 • 1回复 待解决
图库支持打开哪些格式啊?
1233浏览 • 1回复 待解决
DevEcoStudio没有列选择编辑功能吗?
6080浏览 • 1回复 已解决
HarmonyOS SDK和openHarmony SDK怎么选择
6434浏览 • 1回复 待解决
鸿蒙怎么跳转进入email 选择
6078浏览 • 1回复 待解决
如何选择Navigation 组件与 Tabs 组件
872浏览 • 1回复 待解决