Home >Web Front-end >CSS Tutorial >How to Best Display Custom HTML Content with CSS in an Android WebView?
Displaying Custom HTML Content in a WebView
Question:
An application utilizes JSoup to fetch HTML data from a message board thread. The goal is to render this HTML in a WebView with custom CSS to optimize its appearance for mobile devices. Two approaches are being considered: injecting CSS directly into the HTML data or utilizing a separate CSS file from the app's assets.
Answer:
webview.loadDataWithBaseURL provides a convenient solution by allowing you to specify a base URL and load data with references to local assets. This approach eliminates the need for manual CSS injection and simplifies the process.
Implementation:
htmlData = "<link rel=\"stylesheet\" type=\"text/css\" href=\"style.css\" />" + htmlData;
webView.loadDataWithBaseURL("file:///android_asset/", htmlData, "text/html", "UTF-8", null);
Note:
If the HTML data is loaded from the assets directory, specifying a base URL is not necessary. This method allows the WebView to resolve relative links to CSS files located within the assets folder.
The above is the detailed content of How to Best Display Custom HTML Content with CSS in an Android WebView?. For more information, please follow other related articles on the PHP Chinese website!