2011-08-31 12 views
2

다음과 같은 HTML 템플릿을 상상해보십시오.HTML 템플릿을 WebView에로드하려면 어떻게해야합니까?

<html> 
<head> 
    <style type="text/css"> 
     body { 
      color: white; 
     } 
    </style> 
</head> 
<body> 
The changes include: 
<br/><br/> 
%1$s 
<br/><br/> 
Would you like to update now? 
</body> 
</html> 

webView.loadUrl("file:///android_asset/html/upgrade.html")로 WebView에 내용을로드 할 수 있다는 것을 알고 있습니다. 하지만 String.format()을 사용하여 XML 파일에서로드하는 것처럼 런타임시 $ 1을 바꾸기를 원합니다.

파일 내용을 먼저 String으로로드하여 String.format()을 실행 한 다음 webView.loadData()을 대신 사용할 수 있습니까?

답변

5

나는 this answer to a similar question 기반으로하는 솔루션 함께했다 : 나는 코드에서 문자열로 그 HTML의 모든 물건 싶지 않아

String prompt = ""; 
AssetManager assetManager = getApplicationContext().getResources().getAssets(); 
try { 
    InputStream inputStream = assetManager.open("html/upgrade-alert.html"); 
    byte[] b = new byte[inputStream.available()]; 
    inputStream.read(b); 
    prompt = String.format(new String(b),changes); 
    inputStream.close(); 
} catch (IOException e) { 
    Log.e(LOGTAG, "Couldn't open upgrade-alert.html", e); 
} 

WebView html = new WebView(this); 
html.loadData(prompt,"text/html","utf-8"); 
1

일부 문자열에 전체 HTML을 쓰고 바꿀 문자열 하나를 대체 한 다음 loadData를 사용하여로드하십시오.

http://developer.android.com/resources/samples/ApiDemos/src/com/example/android/apis/view/WebView1.html

http://sriram-iyengar.blogspot.com/2011/05/android-webview-loaddata-and-encoding.html

+0

- 더 낫다고 선호 내 텍스트와 HTML을 리소스 파일에 보관합니다. strings.xml에 넣으려고했지만 모든 대괄호와 따옴표를 벗어나야합니다. 엉망입니다. –

0

같은 그럼 당신은 DOM 같은 웹보기에서 HTML을 얻고 TagNodes를 통해이를 변경 HTMLCleaner를 사용할 수 있습니다. HTMLCLeaner를 사용하여 노드를 얻는 방법의 예는 특정 속성을 제공합니다. 물론 AsyncTask에서이 작업을 수행해야합니다. 그러면 UI가 차단되지 않습니다.

public static String snapFromCleanedHTMLWithXPath(String stringURL, String xPath, String attrToStrip) { 
    String snap = ""; 

    // create an instance of HtmlCleaner 
    HtmlCleaner cleaner = new HtmlCleaner(); 

    // take default cleaner properties 
    CleanerProperties props = cleaner.getProperties(); 

    props.setAllowHtmlInsideAttributes(true); 
    props.setAllowMultiWordAttributes(true); 
    props.setRecognizeUnicodeChars(true); 
    props.setOmitComments(true); 

    // open a connection to the desired URL 
    URL url; 
    try { 
     url = new URL(stringURL); 
     URLConnection conn = url.openConnection(); 

     // use the cleaner to "clean" the HTML and return it as a TagNode object 
     TagNode root = cleaner.clean(new InputStreamReader(conn.getInputStream())); 

     Object[] foundNodes = root.evaluateXPath(xPath); 

     if (foundNodes.length > 0) { 
      // casted to a TagNode 
      TagNode foundNode = (TagNode) foundNodes[0]; 
      snap = foundNode.getAttributeByName(attrToStrip); 
     } 
    } catch (MalformedURLException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } catch (IOException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } catch (XPatherException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 
    cleaner = null; 
    props = null; 
    url = null; 
    return snap; 
} 

HTMLCLeaner-Website

+0

감사합니다. @echnchnaehkeee. 흥미로운 접근 방식이지만, 필자의 필요에 따라 조금 복잡합니다. 기본적으로 파일의 내용을 문자열로 읽어서 문자열 바꾸기를 할 수 있기를 원합니다. –

+0

아마도이 방법으로 원하는 것을 얻을 수 있습니다. http://lexandera.com/2009/01/injecting-javascript-into-a-webview/ 도움이 되었기를 바랍니다. ^^ – einschnaehkeee

관련 문제