想了解更多關于開源的內容,請訪問:
51CTO 鴻蒙開發者社區
https://ost.51cto.com
對于“color”、“float”、“string”、“plural”、“media”、“profile”等類型的資源,通過"$r('app.type.name')"形式引用。其中,app為resources目錄中定義的資源;type為資源類型或資源的存放位置;name為資源名,開發者定義資源時確定。
對于rawfile目錄資源,通過"$rawfile('filename')"形式引用。
使用$r進行string資源引用。
Text($r("app.string.mystring"))
在rawfile下的資源可以通過$rawfile+文件名訪問。
Image($rawfile("img.jpg"))
方式一:通過createModuleContext(moduleName)接口創建同應用中不同module的上下文,獲取resourceManager對象后,調用不同接口訪問不同資源。
getContext(this).createModuleContext(moduleName).resourceManager.getStringByNameSync('app.string.XXX')
方式二:通過"$r"或"$rawfile"引用資源(api12支持的能力)。 1.[hsp].type.name獲取資源。其中,hsp為hsp模塊名,type為資源類型,name為資源名稱。
Text($r('[hsp].string.test_string')) .fontSize($r('[hsp].float.font_size')) .fontColor($r('[hsp].color.font_color')) Image($rawfile('[hsp].oneFile/twoFile/icon.png'))
使用變量獲取資源。
@Entry @Component struct Index { text: string = '[hsp].string.test_string'; fontSize: string = '[hsp].float.font_size'; fontColor: string = '[hsp].color.font_color'; image: string = '[hsp].media.string'; rawfile: string = '[hsp].icon.png'; build() { Row() { Text($r(this.text)) .fontSize($r(this.fontSize)) .fontColor($r(this.fontColor)) Image($r(this.image)) Image($rawfile(this.rawfile)) } } }
說明:hsp包名必須寫在[]內,”rawfile“下有多層目錄,需要從”rawfile“下面第一個目錄開始寫,如“$rawfile('[hsp].oneFile/twoFile/icon.png')”,使用"$r"和"$rawfile"跨包訪問HSP包資源無法提供編譯時的資源校驗,需要開發者自行保證使用資源存在于對應包中。
創建HSP,新建模塊,選擇shared library。
導出需要使用的資源。
導出ResManager1,以便其他模塊獲取到hsp中的resource資源。
export class ResManager1{ static getPic(): Resource{ return $r('app.media.11'); } static getDesc(): Resource{ return $r('app.string.shared_desc1'); } }
在模塊下的index.ets導出資源。
引用資源。
在引用方模塊的oh-package.json5下添加依賴,執行install。
Import加載并使用。
import {ResManager1}from 'hsp' @Entry @Component struct Index { @State message: string = 'Hello World'; build() { Row() { Column() { Text(ResManager1.getDesc()) .fontSize(50) .fontWeight(FontWeight.Bold) } .width('100%') } .height('100%') } }
新建模塊,選擇static library。
export使用的資源,并在模塊下的index.ets導出。
build出har包。
Build完成后會在模塊下生成.har文件。
引用har包,在引用方oh-package.json5下添加依賴,依賴需要到.har文件,執行install。
import 后調用har中的資源。
import {ResManager}from 'har' @Entry @Component struct Index { @State message: string = 'Hello World'; build() { Row() { Column() { Image(ResManager.getPic()).width(50) .fontSize(50) .fontWeight(FontWeight.Bold) } .width('100%') } .height('100%') } }
其他常見問題:
Q:依賴的多個模塊使用過相同資源后,以哪一個模塊的資源為準?
A:如果依賴的多個HAR之間有資源沖突,會按照依賴順序進行覆蓋(依賴順序在前的優先級較高)。
Q:是否可以通過循環變量加載資源?
A:當前支持通過$r("app.string.name" + 1)拼接的方式加載資源(包括變量拼接的形式),跨模塊的場景也適用。
想了解更多關于開源的內容,請訪問:
51CTO 鴻蒙開發者社區
https://ost.51cto.com
本文鏈接:http://www.tebozhan.com/showinfo-26-87681-0.html基于原生的跨模塊資源訪問
聲明:本網頁內容旨在傳播知識,若有侵權等問題請及時與本網聯系,我們將在第一時間刪除處理。郵件:2376512515@qq.com
上一篇: 一篇聊透云原生中的服務網格
下一篇: Next.js 14:全棧開發的新寵?