简体   繁体   中英

Replace “placeholders” with resource strings?

The background of my question is that I'm trying to localize some HTML files, but I don't want to have full duplicates of the entire HTML for each language, I just want to do it "the Android way", and use localized string resources in my HTML.

Suppose I have some HTML in a String, with placeholders that should be replaced with string resources before sending the HTML to a WebView - how would I do that?

Suppose for instance I have this HTML:

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

and these string resources:

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

Now, for an example this simple I could just use String.replace(), but what if I want to make it more dynamic, ie I don't want to have to write any new replace-code when I add more placeholders to the HTML? I know it's possible, but I just can't find any examples online (most regex examples are simple static search-and-replace operations).

Through some trial-and-error I managed to come up with this solution on my own, not sure if there are any better/more efficient ones out there?

// 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");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM