- 在布局文件(例如activity_main.xml)中添加一个WebView组件:
xmlCopy code
- 在Java代码中加载HTML内容并设置分页效果:
javaCopy code
import android.annotation.SuppressLint;
import android.os.Bundle;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
private WebView webView;
@SuppressLint("SetJavaScriptEnabled")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webView = findViewById(R.id.webview);
// 设置WebView的配置
WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true); // 启用JavaScript
// 设置WebView的客户端
webView.setWebViewClient(new WebViewClient());
webView.setWebChromeClient(new WebChromeClient());
// 加载HTML内容
String htmlContent = "This is some sample HTML content.
";
webView.loadDataWithBaseURL(null, htmlContent, "text/html", "UTF-8", null);
// 执行JavaScript脚本以实现分页效果
webView.setWebViewClient(new WebViewClient() {
@Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
// 执行JavaScript脚本以实现分页效果
String javascript = "javascript:(function() {" +
" var maxScrollHeight = document.documentElement.scrollHeight;" +
" var currentPage = 0;" +
" var pageSize = window.innerHeight;" +
" var pageCount = Math.ceil(maxScrollHeight / pageSize);" +
" function nextPage() {" +
" if (currentPage < pageCount - 1) {" +
" currentPage++;" +
" window.scrollTo(0, currentPage * pageSize);" +
" }" +
" }" +
" function previousPage() {" +
" if (currentPage > 0) {" +
" currentPage--;" +
" window.scrollTo(0, currentPage * pageSize);" +
" }" +
" }" +
" window.addEventListener('keyup', function(event) {" +
" if (event.key === 'ArrowRight' || event.key === 'PageDown') {" +
" nextPage();" +
" } else if (event.key === 'ArrowLeft' || event.key === 'PageUp') {" +
" previousPage();" +
" }" +
" });" +
"})();";
webView.loadUrl(javascript);
}
});
}
}
以上代码中,我们使用WebView加载了一个简单的HTML内容,并在WebView的onPageFinished回调中执行了JavaScript脚本来实现分页效果。JavaScript脚本监听了键盘事件,当用户按下"ArrowRight"、"PageDown"键时,会切换到下一页;当用户按下"ArrowLeft"、"PageUp"键时,会切换到上一页。
请注意,为了使JavaScript代码生效,我们需要在AndroidManifest.xml文件中添加android.permission.INTERNET权限。