在WebView中加载本地html?

Jas*_*ani 42 android webview

我想使用"file:///"将本地html加载到WebView中,因为它不允许使用cookie.有没有办法使用像"localhost"这样的东西?

其次,我找不到在getSettings()中启用cookie的方法.因为使用"file:///"时不允许使用cookie.

小智 100

你只能这样做.此解决方案从String变量加载HTML:

String html = "<html><body>Hello, World!</body></html>";
String mime = "text/html";
String encoding = "utf-8";

WebView myWebView = (WebView)this.findViewById(R.id.myWebView);
myWebView.getSettings().setJavaScriptEnabled(true);
myWebView.loadDataWithBaseURL(null, html, mime, encoding, null);
Run Code Online (Sandbox Code Playgroud)

编辑:尝试设置的第一个参数(在基本URL)loadDataWithBaseURL()为您的需求


Vir*_*iya 14

public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        WebView view = (WebView) findViewById(R.id.webView1);
        try {
        InputStream input = getResources().openRawResource(R.raw.lights);
        Reader is = new BufferedReader(
                new InputStreamReader(input, "windows-1252"));


            //InputStream input = getAssets().open("ws.TXT");
            int size;
            size = input.available();
            byte[] buffer = new byte[size];
            input.read(buffer);
            input.close();
            // byte buffer into a string
            javascrips = new String(buffer);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        // String html = readFile(is);

        view.loadDataWithBaseURL("file:///android_res/raw/", javascrips, "text/html",
                "UTF-8", null);
    }
Run Code Online (Sandbox Code Playgroud)


Ali*_*mel 9

试试这个代码.这个对我有用.

WebView mDesc = findViewById(R.id.descWv);
WebSettings settings = mDesc.getSettings();
settings.setDefaultTextEncodingName("utf-8");
mDesc.loadData(mDescText, "text/html; charset=utf-8",null);
Run Code Online (Sandbox Code Playgroud)