关于使用webview加载html代码块

最近开发app,发现需要用webview加载html代码块,需要将服务端返回的代码块转换为可以通过webview加载的数据,例如:

<p>Our Growing Tomatoes Guide covers everything from planting through harvesting! Tomatoes are not hard to grow; they’re incredibly productive, versatile in the kitchen, and so delicious off the vine. Our guide covers all the information you need to grow tomatoes successfully—including selecting tomato varieties, starting seeds, transplanting tomatoes outside, using tomato stakes and cages, and tomato plant care.<br><br>Tomatoes are long-growing, heat-seeking, sun lovers! These warm-season plants do not tolerate frost. In most regions, the soil is not warm enough until April or May, but it depends on where you live.</p><p><img src="https://www.enflower.info/file/flower/flower/detail/2012042237179761.jpeg" style="max-width:100%;"></p><p>HOW LONG DOES IT TAKE TO GROW A TOMATO?<br>This is one of our most common questions. The days to harvest depends on the cultivar, but the days to maturity ranges from 60 days to more than 80 days. <br><br>Due to a relatively long growing season, tomatoes are most commonly transplanted rather than direct-seeded into the garden. Transplants can be purchased in garden nurseries. Look for short, stocky plants with dark green color and straight, sturdy stems about the size of a pencil or thicker. Avoid plants with yellowing leaves, spots, or stress damage; avoid plants with flowers or fruits already in progress.<br><br>TYPES OF TOMATOES<br>Tomatoes are available in a wide variety of sizes, from tiny grape-size types to giant beefstakes. The choice also depends on how you will use this verstaile fruit in the kitchen. For example, Roma tomatoes are not very good eaten fresh, but are well suited for sauces and ketchups. Tomato cultivars can be classified according to their growth habit:<br><br>Determinate tomatoes are plants that grow to pre-determined height. They are good choices for canning and sauce-making.<br>Indeterminate tomatoes increase in height throughout the growing season because the terminal of the stem continues to produce foliar growth rather than set flowers. The fruits on these plants are produced continually through the season along the side shoots of the plant. Indeterminate tomatoes are the choice if you want to spread out the harvest over a longer period of time.<br>Tomatoes do need vigilant care, as the crop is susceptible to pests and diseases. To avoid problems, choose disease-resistant cultivars whenever possible. Also, note that tomato plants will be more susceptible to soil-borne disease and rot if not kept off the ground with a stake or other support system. We’ll cover all these essentials in the tomato guide below.</p>

转换函数:

   public static String getHtmlData(String bodyHTML) {
        String head = "<head>" +
                "<meta name=\"viewport\" content=\"width=device-width, initial-scale=default.0, user-scalable=no\"> " +
                "<style>html{padding:15px;} body{word-wrap:break-word;font-size:13px;padding:0px;margin:0px} p{padding:0px;margin:0px;font-size:13px;color:#222222;line-height:default.3;} img{padding:0px,margin:0px;max-width:100%; width:100%; height:auto;}</style>" +
                "</head>";
        return "<html>" + head + "<body>" + bodyHTML + "</body></html>";
    }
    //如果width:100%,则显示的图片是填充状态,设置auto图片显示很小

webview设置:

 WebSettings settings = mWebView.getSettings();
        settings.setTextZoom(450);//设置字体大小
        settings.setJavaScriptCanOpenWindowsAutomatically(true); // 设置JS是否可以打开WebView新窗口
        settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        settings.setSupportZoom(true); // 支持缩放
        settings.setBuiltInZoomControls(true); // 支持手势缩放
        settings.setDatabaseEnabled(true);//数据库存储API是否可用,默认值false。
        settings.setSaveFormData(true);//WebView是否保存表单数据,默认值true。
        settings.setDomStorageEnabled(true);//DOM存储API是否可用,默认false。
        //190925
        settings.setBlockNetworkImage(false);//解决图片不显示
        settings.setUseWideViewPort(true); // 将图片调整到适合WebView的大小
//        settings.setLoadWithOverviewMode(true); // 自适应屏幕
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP) {
            settings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
        mWebView.setHorizontalScrollBarEnabled(false);//去掉webview的滚动条,水平不显示
        mWebView.setScrollbarFadingEnabled(true);
        //20190918
        mWebView.setScrollBarStyle(View.SCROLLBARS_OUTSIDE_OVERLAY);
        mWebView.setOverScrollMode(View.OVER_SCROLL_NEVER); // 取消WebView中滚动或拖动到顶部、底部时的阴影

然后就可以完美展示了~~
注意,当使用webview加载时,系统8.1以上加载会失败,
可以使用:mWebView.loadDataWithBaseURL(null,html, "text/html;charset=utf-8", "utf-8",null);
ps:最近一个开源视频编辑项目:传送门

### 回答1: 使用Android Studio中的nanohttpd库创建HTTP服务器,并使用WebView打开HTML页面的步骤如下: 1. 首先,在build.gradle文件中的dependencies块中添加依赖项: ``` implementation 'org.nanohttpd:nanohttpd-webserver:2.3.1' ``` 2. 在需要创建HTTP服务器的Activity中,创建一个继承自NanoHTTPD的子类。例如: ```java public class MyServer extends NanoHTTPD { public MyServer() { super(8080); // 设置服务器端口为8080 } @Override public Response serve(IHTTPSession session) { String uri = session.getUri(); // 获取请求的URI // 判断请求的URI是否为根目录,如果是,则返回HTML页面,否则返回404错误 if (uri.equals("/")) { try { InputStream inputStream = getAssets().open("index.html"); // 打开assets文件夹中的index.html文件 BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); StringBuilder builder = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { builder.append(line); } reader.close(); inputStream.close(); String html = builder.toString(); return newFixedLengthResponse(Response.Status.OK, "text/html", html); // 返回HTML页面 } catch (IOException e) { e.printStackTrace(); } } return newFixedLengthResponse(Response.Status.NOT_FOUND, "text/plain", "404 Not Found"); // 返回404错误 } } ``` 3. 在Activity中启动HTTP服务器,并使用WebView打开页面: ```java WebView webView = findViewById(R.id.webView); webView.getSettings().setJavaScriptEnabled(true); // 允许WebView执行JavaScript代码 MyServer server = new MyServer(); try { server.start(); // 启动HTTP服务器 } catch (IOException e) { e.printStackTrace(); } webView.loadUrl("http://localhost:8080/"); // 使用WebView打开服务器的根目录页面 ``` 以上就是使用NanoHTTPD创建HTTP服务器并使用WebView打开HTML页面的过程。在实际开发中,可以根据需要进行相应的修改和扩展。 ### 回答2: 要使用Android Studio创建一个HTTP服务器并打开HTML页面,可以使用NanoHTTPD库来实现。 首先,需要在项目的`build.gradle`文件中添加NanoHTTPD的依赖项。在`dependencies`部分添加以下代码: ``` implementation 'org.nanohttpd:nanohttpd:2.3.1' ``` 接下来,在你的Activity或Fragment中创建一个NanoHTTPD的子类,例如`MyServer`。这个子类需要实现`NanoHTTPD.IHTTPD`接口,并重写`serve()`方法来响应HTTP请求。在这个方法中,你可以通过判断请求URI来确定要返回给客户端的内容。 具体代码如下: ```java import android.content.Context; import android.webkit.WebView; import android.widget.Toast; import org.nanohttpd.protocols.http.IHTTPSession; import org.nanohttpd.protocols.http.NanoHTTPD; import org.nanohttpd.protocols.http.response.Response; import org.nanohttpd.protocols.http.response.Status; import java.io.IOException; public class MyServer extends NanoHTTPD { private Context context; public MyServer(Context context) { super(8080); this.context = context; } @Override public Response serve(IHTTPSession session) { String uri = session.getUri(); if (uri.equals("/index.html")) { String html = "<html><body><h1>Hello, World!</h1></body></html>"; return newFixedLengthResponse(Response.Status.OK, "text/html", html); } else { return newFixedLengthResponse(Response.Status.NOT_FOUND, "text/plain", "404 Not Found"); } } } ``` 然后,在你的Activity或Fragment中,可以通过创建一个WebView加载HTML页面,并启动NanoHTTPD服务器。具体代码如下: ```java import android.os.Bundle; import android.webkit.WebView; import android.webkit.WebViewClient; import androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { private WebView webView; private MyServer server; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); webView = findViewById(R.id.webView); webView.getSettings().setJavaScriptEnabled(true); webView.setWebViewClient(new WebViewClient()); server = new MyServer(this); try { server.start(); Toast.makeText(this, "Server started", Toast.LENGTH_SHORT).show(); } catch (IOException e) { e.printStackTrace(); } webView.loadUrl("http://localhost:8080/index.html"); } @Override protected void onDestroy() { super.onDestroy(); if (server != null) { server.stop(); } } } ``` 在XML布局文件中添加一个WebView用于显示HTML页面。 这样,当你运行这个应用时,会在Android设备上启动一个HTTP服务器,并使用WebView加载服务器上的HTML页面。 ### 回答3: 使用Android Studio创建HTTP服务器并在WebView中打开HTML页面需要以下步骤: 1. 首先,将nanohttpd库导入到Android Studio项目中。可以通过在项目的build.gradle文件中添加以下行来实现: ```groovy dependencies { implementation 'org.nanohttpd:nanohttpd:2.3.1' } ``` 2. 创建一个新的Java类,继承自`NanoHTTPD`类,用于实现HTTP服务器。在这个类中,需要重写NanoHTTPD的`serve()`方法,来处理HTTP请求和响应。通过使用`InputStream`读取HTML文件的内容,并将其响应给请求的客户端。 ```java public class MyHTTPServer extends NanoHTTPD { // 构造方法 public MyHTTPServer() { super(8080); } @Override public Response serve(IHTTPSession session) { String uri = session.getUri(); if (uri.equals("/")) { uri = "/index.html"; } try { InputStream inputStream = getApplicationContext().getAssets().open(uri.substring(1)); String mimeType = "text/html"; return newChunkedResponse(Response.Status.OK, mimeType, inputStream); } catch (IOException e) { e.printStackTrace(); return newFixedLengthResponse(Response.Status.NOT_FOUND, "text/plain", "File not found"); } } } ``` 3. 在AndroidManifest.xml文件中添加以下权限: ```xml <uses-permission android:name="android.permission.INTERNET" /> ``` 4. 在Activity的`onCreate()`方法中启动HTTP服务器并加载WebView: ```java public class MainActivity extends AppCompatActivity { private WebView webView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // 启动HTTP服务器 MyHTTPServer server = new MyHTTPServer(); try { server.start(); } catch (IOException e) { e.printStackTrace(); } webView = findViewById(R.id.webView); // 允许WebView执行JavaScript代码 webView.getSettings().setJavaScriptEnabled(true); // 加载HTTP服务器的地址 webView.loadUrl("http://localhost:8080"); } } ``` 以上是在Android Studio中使用NanoHTTPD库创建HTTP服务器并在WebView中打开HTML页面的步骤。可以根据需要对服务器和WebView进行进一步的自定义和配置。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值