安卓渲染Html 并做分頁,你學會了嗎?
在安卓應用中渲染HTML并實現分頁,你可以使用WebView組件來加載和顯示HTML內容,并結合JavaScript和CSS來實現分頁效果。下面是一個簡單的示例代碼,演示如何在安卓應用中實現HTML渲染和分頁功能:
- 在布局文件(例如activity_main.xml)中添加一個WebView組件:
xmlCopy code
<WebView
android:id="@+id/webview"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
- 在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 = "<html><body><h1>Hello, WebView!</h1><p>This is some sample HTML content.</p></body></html>";
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權限。