Webview 載入文章內容

weixin_34120274發表於2016-11-21

設定listview的點選事件

ListView newslistView=(ListView) findViewById(R.id.show_news);
newslistView.setAdapter(new NewsAdapter(newss,NewsActivity.this,newslistView));
newslistView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
               public void onItemClick(AdapterView<?> parent, View view, int   position, long id) {
                Intent intent = new Intent(NewsActivity.this,ArticleActivity.class);
                News news = newss.get(position);
                String AtUrl = "http://news-at.zhihu.com/api/4/news/"+news.getId();
                intent.putExtra("AtUrl",AtUrl);
                startActivity(intent);
        }
});

新建WebView,通過url獲取html內容,問題是載入css的過程。
webview.load()這個方法會出現亂碼,查過之後發現要手動設定編碼方式為utf8

WebView wv = (WebView)findViewById(R.id.webview);
String content = getUnicodeContent();
wv.getSettings().setDefaultTextEncodingName(“UTF -8”);
wv.loadData(content, “text/html”, “UTF-8”) ;

但仍沒有解決亂碼,所以改用loadDataWithBaseURL()

     * @param baseUrl the URL to use as the page's base URL. If null defaults to
     *                'about:blank'.
     * @param data a String of data in the given encoding
     * @param mimeType the MIMEType of the data, e.g. 'text/html'. If null,
     *                 defaults to 'text/html'.
     * @param encoding the encoding of the data
     * @param historyUrl the URL to use as the history entry. If null defaults
     *                   to 'about:blank'. If non-null, this must be a valid URL.
     */
    public void loadDataWithBaseURL(String baseUrl, String data,
            String mimeType, String encoding, String historyUrl) {
        checkThread();
        mProvider.loadDataWithBaseURL(baseUrl, data, mimeType, encoding, historyUrl);
    }

載入css的方法貌似有很多,比如用js,但最後選擇了在以下方案。
要注意的是獲取到的html程式碼不一樣的情況下面的程式碼是有問題的,所以這個方法是偷懶的權宜之計

WebView webview = (WebView) findViewById(R.id.ArticleView);
String html = "<html><header><style type='text/css'>"+css+"</style></header>"
                +"<body>"+body+"</body></html>";
webview.loadDataWithBaseURL(null,html, "text/html",  "utf-8", null);

相關文章