簡體   English   中英

用資源字符串替換“占位符”?

[英]Replace “placeholders” with resource strings?

我的問題的背景是我正在嘗試本地化一些HTML文件,但是我不想為每種語言都復制整個HTML,我只是想以“ Android方式”進行操作,並使用本地化HTML中的字符串資源。

假設我在字符串中有一些HTML,其中的占位符應在將HTML發送到WebView之前用字符串資源替換-我該怎么做?

假設例如我有這個HTML:

<div>[myTitle]</div>
<div>[myContent]</div>

和這些字符串資源:

<string name="myTitle">My title</string>
<string name="myContent">My content</string>

現在,舉個簡單的例子,我可以只使用String.replace(),但是如果我想使其更具動態性,那怎么辦,也就是說,當我向其添加更多占位符時,我不必寫任何新的替換代碼。 HTML? 我知道這是有可能的,但我只是無法在線找到任何示例(大多數正則表達式示例都是簡單的靜態搜索和替換操作)。

通過反復試驗,我設法自己提出了這個解決方案,不確定是否還有更好/更有效的解決方案?

// Read asset file into String
StringBuilder buf = new StringBuilder();
InputStream is = null;
BufferedReader reader = null;

try{
    is = getActivity().getAssets().open("html/index.html");
    reader= new BufferedReader(new InputStreamReader(is, "UTF-8"));
    String line;

    while ((line=reader.readLine()) != null) {
        buf.append(line);
    }
}
catch(IOException e){
    e.printStackTrace();
}
finally{
    try{
        reader.close();
        is.close();
    }
    catch(IOException e){
        e.printStackTrace();
    }

}

String htmlStr = buf.toString();


// Create Regex matcher to match [xxx] where xxx is a string resource name
Pattern p = Pattern.compile("\\[(.*?)\\]");
Matcher m = p.matcher( htmlStr );


// Replace matches with resource strings
while(m.find()) {
    String placeholder = m.group(); // Placeholder including [] -> [xxx]
    String placeholderName = m.group(1); // Placeholder name    -> xxx

    // Find the string resource
    int resId = getResources().getIdentifier(placeholderName, "string", getActivity().getPackageName() );

    // Resource not found?              
    if( resId == 0 )
        continue;

    // Replace the placeholder (including []) with the string resource              
    htmlStr = htmlStr.replace(placeholder, getResources().getString( resId ));

    // Reset the Matcher to search in the new HTML string
    m.reset(htmlStr);           
}


// Load HTML string into WebView
webView.loadData(htmlStr, "text/html", "UTF-8");

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM