Irshad Khan
Irshad Khan

Reputation: 6046

how to load android assets css files to android WebView URL

Actually I want to load complete site from internet link but i want to load css files from mobile (means not from internet). Because I want to load all page faster using internal local css file.

Example :

<!DOCTYPE html>
<html lang="en">
    <head>
        <link rel="stylesheet" href="dist/css/bootstrap.min.css" />
        <link rel="stylesheet" href="dist/css/font-awesome.min.css" />
    </head>
</html>

So Here I want to Load "bootstrap.min.css" and "font-awesome.min.css" from mobile memory only.

My Android Code :

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    String url = "http://www.MySiteName.com/";
    view = (WebView) this.findViewById(R.id.webView);

    view.getSettings().setJavaScriptEnabled(true); // Enable JavaScript Support
    view.setWebViewClient(new WebViewClient()); // Links open or Navigate in same webView not in Browser

    view.loadUrl(url);
}

Upvotes: 9

Views: 16509

Answers (2)

Jay Dwivedi
Jay Dwivedi

Reputation: 464

Please put CSS in assets folder, and refer to CSS by relative path, and load HTML to WebView by loadDataWithBaseURL() method: if your css file name is mycss.css

StringBuilder data = new StringBuilder();
data .append("<HTML><HEAD><LINK href=\"mycss.css\" type=\"text/css\" rel=\"stylesheet\"/></HEAD><body>");
data .append(tables.toString());
data .append("</body></HTML>");
webView.loadDataWithBaseURL("file:///android_asset/", data .toString(), "text/html", "utf-8", null);

thank you

Upvotes: 15

Horsty
Horsty

Reputation: 320

Because the two other answers are just copy pastas and I happened to have the same issue I will help you with my solution:

You need to specify the file path in the head section of your html file. Pay attention to the part after href

<!DOCTYPE html>
<html lang="en">
    <head>
        <link rel="stylesheet" href="file:///android_asset/bootstrap.min.css" />
        <link rel="stylesheet" href="file:///android_asset/font-awesome.min.css" />
    </head>
</html>

I just can't get my head around why the other posters just copied and pasted and didn't even read what you were trying to tell them.

I hope this helps.

Be aware that your resources folder can be named differently.

Upvotes: 10

Related Questions