WebView trong Android là một view giúp cho bạn có thể hiển thị 1 trang web từ URL hoặc là từ 1 trang html tùy chỉnh. Hôm này tôi xin hướng dẫn các bạn cách đưa Webview vào ứng dụng và sử dụng chúng 1 cách cơ bản để có thể load 1 trang wev từ URL hay từ 1 trang html tùy chỉnh nào đó.
1. Xây dựng giao diện.
Tôi sẽ xây dựng 1 giao diện như hình vẽ, bao gồm 1 nut button GO, khi click vào nút này sẽ hiển thị trang web ở bên dưới:
Code giao diện:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="fill_parent" android:orientation="vertical" android:layout_height="match_parent" tools:context=".MainActivity" > <Button android:id="@+id/btGo" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="#41BE02" android:layout_gravity="center" android:text="Go" /> <WebView android:id="@+id/webView1" android:layout_width="match_parent" android:layout_height="match_parent" /> </LinearLayout>
2. Xử lý code
- Tôi đã gán id cho WebView là webView1, và việc lấy id này trong activity hoàn toàn tương tự như các view khác.:
webView = (WebView) findViewById(R.id.webView1);
- Để đặt địa chỉ URL cho Webview tôi dùng phương thức : webView.loadUrl() và để bật Javascript lên tôi dùng webView.getSettings().setJavaScriptEnabled(true);
- Bạn cần chỉnh sửa file AndroidManifest.xml để cấp quyền truy cập mạng internet bằng cách thêm dòng lệnh sau :
<uses-permission android:name=”android.permission.INTERNET” />
Và đây là code:
package com.tien.webviewdemo; import android.os.Bundle; import android.app.Activity; import android.view.Menu; import android.view.View; import android.view.View.OnClickListener; import android.webkit.WebView; import android.widget.Button; public class MainActivity extends Activity { private Button btGo; private WebView webView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); btGo =(Button) findViewById(R.id.btGo); webView = (WebView) findViewById(R.id.webView1); btGo.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub webView.getSettings().setJavaScriptEnabled(true); webView.loadUrl("http://www.goclaptrinh.com"); } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } }
Ảnh demo:
3. Hiển thị giao diện XML tùy chỉnh.
Để hiển thị một trang HTML tùy chỉnh thì bạn thay code trên bàng đoạn code xử lý sau:
webView.getSettings().setJavaScriptEnabled(true); String html = "<html><body><h1>Chào mừng bạn đến với blog GOCLAPTRINH.COM</h1></body></html>"; webView.loadData(html, "text/html", "UTF-8");