Header ads

Header ads
» » WebView

WebView trong Android

Trong Android, Đối tượng WebView dùng để hiện thị trang trong một ứng dụng. Trang web có thể được tải từ cùng một ứng dụng hoặc URL. WebView được sử dụng để hiển thị nội dung trực tuyến trong Activity của Android. Chúng ta cũng có thể hiện thị HTML trong ứng dụng Android, bằng cách sử dụng WebView.














Android WebView sử dụng bộ máy webkit để hiển thị trang web  android.webkit.WebView là lớp con của lớp AbsoluteLayout.


Để thêm Web View trong ứng dụng, Trong tập tin chúng ta thêm phần tử <WebView>, Cũng có thể thêm trong Java Class
WebView code trong XML
  <WebView  android:id="@+id/simpleWebView"    android:layout_width="fill_parent"  android:layout_height="fill_parent" />


Phân Quyền truy cập Internet cho WebView
Để Activity có thể truy cập được internet và tải trang web trong webview. Chúng ta cần phải phân quyền truy cập internet cho ứng dụng trong tập tin Manifest (Manifest.xml).
Code phân quyền:
  <!--Add this before application tag in AndroidManifest.xml-->  <uses-permission android:name="android.permission.INTERNET" />

Các phương thức thường dụng của WebView
Dưới đây là một số phương thức thường dùng để cấu hình WebView trong ứng dụng của chúng ta
1. loadUrl() – Tải một trang web vào ứng dụng
  loadUrl(String url)
Phương thức này dùng để tải trang web vào trong ứng dụng. Trong phương thức này chúng ta phải chỉ ra url của trang web mà chúng ta muốn tải trong WebView
  *Add in Oncreate() funtion after setContentView()*/  // initiate a web view  WebView simpleWebView=(WebView) findViewById(R.id.simpleWebView);  // specify the url of the web page in loadUrl function  simpleWebView.loadUrl("http://hocviendaotao.com");
2. loadData() – Tải  Html tĩnh vào WebView
  loadData(String data, String mimeType, String encoding)
Phương thức này sử dụng để tải trang HTML tĩnh vào trong WebView. Phương thức loadData có 3 tham số:
String Data: Nội dung văn bản trong thẻ HTML
 String mimeType:cho phép ấn định định dạng mở tập tin cho trình duyệt
String encoding: Bảng mã cho văn bản
  /*Add in Oncreate() funtion after setContentView()*/  // initiate a web view  WebView webView = (WebView) findViewById(R.id.simpleWebView);  // static html string data  String customHtml = "<html><body><h1>Hello, AbhiAndroid</h1>" +          "<h1>Heading 1</h1><h2>Heading 2</h2><h3>Heading 3</h3>" +          "<p>This is a sample paragraph of static HTML In Web view</p>" +          "</body></html>";  // load static html data on a web view  webView.loadData(customHtml, "text/html", "UTF-8");

3. shouldOverrideUrlLoading () - Tải trang web từ xa vào WebView sử dụng WebViewClient:
WebViewClient giúp chúng tôi giám sát sự kiện trong WebView. Chúng ta phải nạp chồng (Override) lại phương thức shouldOverrideUrlLoading (). Phương thức này cho phép chúng ta thực hiện hành động khi một url được chọn. Chúng ta có thể thiết lập WebViewClient trong WebView bằng phương thức setWebViewClient ().Vi dụ chúng ta tải một url bằng cách sử dụng ứng dụng web view client trong WebView.
  WebView simpleWebView=(WebView) findViewById(R.id.simpleWebView);  /*Add in Oncreate() funtion after setContentView()*/        // set web view client  simpleWebView.setWebViewClient(new MyWebViewClient());    // string url which you have to load into a web view  String url = "http://hocviendaotao.com/";  simpleWebView.getSettings().setJavaScriptEnabled(true);  simpleWebView.loadUrl(url); // load the url on the web view  }    // custom web view client class who extends WebViewClient  private class MyWebViewClient extends WebViewClient {  @Override  public boolean shouldOverrideUrlLoading(WebView view, String url) {  view.loadUrl(url); // load the url  return true;
4. canGoBack() – Di chuyển trang một trang web về trước nếu trang web đó tồn tại trong history.
Phương thức này được sử dụng để xem một WebView có một trang web tồn tại trong mục lịch sử (history) để trở lại hay không. Phương thức này trả về giá trị Boolean đúng hoặc sai. Nếu nó trả về true thì phương thức canGoBack () được sử dụng để di chuyển một trang trước đó. Ví dụ kiểm tra xem trang web có history để trở về trang trước đó?
  // initiate a web view  WebView simpleWebView=(WebView)findViewById(R.id.simpleWebView);  // checks whether a web view has a back history item or not  Boolean canGoBack=simpleWebView.canGoBack();
5. canGoForward() –Di chuyển đến trang kế tiếp nếu trang kế tiếp tồn tại trong history.
Phương thức này được sử dụng để xem một WebView có một trang web tồn tại trong mục lịch sử (history) để di chuyển đến trang kế tiếp hay không. Phương thức này trả về giá trị Boolean đúng hoặc sai. Nếu nó trả về true thì phương thức canGoForward() được sử dụng để di chuyển một trang kế tiếp. Ví dụ kiểm tra xem trang web có history để di chuyển đến kế tiếp?
  // initiate a web view   WebView simpleWebView=(WebView)findViewById(R.id.simpleWebView);  // checks whether a web view has a forward history item or not   Boolean canGoForword=simpleWebView.canGoForward() ;
6. clearHistory() – Xóa tất cả lịch sử  trong WebView 
Phương thức này dùng để xóa tất cả lịch sử của WebView
  WebView simpleWebView=(WebView)findViewById(R.id.simpleWebView); // initiate a web view  simpleWebView.clearHistory(); // clear the forward and backward history


Ví dụ: Trong ví dụ này chúng ta sẽ làm ứng dụng gồm có 1 WebView và 2 Button. Khi người sử click vào Button "Load Web Page"  sẽ xuất hiện trang website hocviendaotao.com, Click vào  Button "Load Static HTML" Xuất hiện văn bản web tĩnh HTML. Tiến hành tạo project, vào thư mục  res /layout -> activity_main.xml thiết kế giao diện sau:
Bước 1: Tạo một project tên là WebViewFile->New->Android Application Project điền các thông tin ->Next ->Finish
Bước 2: Mở res -> layout -> xml (hoặc) activity_main.xml và thêm code, chúng ta sẽ tạo các đối tượng SeekBar trong Linear Layout.
  <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"      xmlns:tools="http://schemas.android.com/tools"      android:layout_width="match_parent"      android:layout_height="match_parent"      android:orientation="vertical"      android:paddingBottom="@dimen/activity_vertical_margin"      android:paddingLeft="@dimen/activity_horizontal_margin"      android:paddingRight="@dimen/activity_horizontal_margin"      android:paddingTop="@dimen/activity_vertical_margin"      tools:context=".MainActivity">        <LinearLayout          android:layout_width="fill_parent"          android:layout_height="wrap_content"          android:orientation="horizontal"          android:weightSum="2">            <Button              android:id="@+id/btnLoadWebPage"              android:layout_width="0dp"              android:layout_height="wrap_content"              android:layout_marginRight="10dp"              android:layout_weight="1"              android:background="#444"              android:text="Load Web Page"              android:textColor="#fff"              android:textSize="14sp"              android:textStyle="bold" />            <Button              android:id="@+id/btnLoadFromStaticHtml"              android:layout_width="0dp"              android:layout_height="wrap_content"              android:layout_marginLeft="10dp"              android:layout_weight="1"              android:background="#444"              android:text="Load Static HTML"              android:textColor="#fff"              android:textSize="14sp"              android:textStyle="bold" />      </LinearLayout>        <WebView          android:id="@+id/simpleWebView"          android:layout_width="fill_parent"          android:layout_height="fill_parent"          android:layout_marginTop="20dp"          android:scrollbars="none" />    </LinearLayout>  
Bước 3: Mở app -> src ->MainActivity.java và thêm code.
Trong bước này chúng ta mở MainActivity và khởi tạo WebView, Button. xử lý sự kiện cho 2 Button.
  package hocviendaotao.com.webview;    import android.app.Activity;  import android.os.Bundle;  import android.view.Menu;  import android.view.MenuItem;  import android.view.View;  import android.view.View.OnClickListener;  import android.webkit.WebView;  import android.webkit.WebViewClient;  import android.widget.Button;    public class MainActivity extends Activity implements OnClickListener {   WebView simpleWebView;      Button btnLoadWebPage, btnLoadFromStaticHtml;     @Override   protected void onCreate(Bundle savedInstanceState) {    super.onCreate(savedInstanceState);    setContentView(R.layout.activity_main);        btnLoadFromStaticHtml = (Button) findViewById(R.id.btnLoadFromStaticHtml);    btnLoadFromStaticHtml.setOnClickListener(this);       btnLoadWebPage = (Button) findViewById(R.id.btnLoadWebPage);       btnLoadWebPage.setOnClickListener(this);       simpleWebView = (WebView) findViewById(R.id.simpleWebView);     }       @Override       public void onClick(View v) {           switch (v.getId()) {               case R.id.btnLoadFromStaticHtml:                   // define static html text                   String customHtml = "<html><body><h1>Hello, Hocviendaotao</h1>" +                           "<h1>Heading 1</h1><h2>Heading 2</h2><h3>Heading 3</h3>" +                           "<p>This is a sample paragraph of static HTML In Web view</p>" +                           "</body></html>";                   simpleWebView.loadData(customHtml, "text/html", "UTF-8"); // load html string data in a web view                   break;               case R.id.btnLoadWebPage:                   simpleWebView.setWebViewClient(new MyWebViewClient());                   String url = "http://hocviendaotao.com/";                   simpleWebView.getSettings().setJavaScriptEnabled(true);                   simpleWebView.loadUrl(url); // load a web page in a web view                   break;           }       }     // custom web view client class who extends WebViewClient     private class MyWebViewClient extends WebViewClient {     @Override     public boolean shouldOverrideUrlLoading(WebView view, String url) {     view.loadUrl(url); // load the url     return true;     }   }    }  
Bước 4: Mở manifests -> AndroidManifest.xml
Mở tập tin AndroidManifest.xml và phân quyền truy internet cho ứng dụng:
  <?xml version="1.0" encoding="utf-8"?>  <manifest xmlns:android="http://schemas.android.com/apk/res/android"      package="hocviendaotao.com.webview"      android:versionCode="1"      android:versionName="1.0" >        <uses-sdk          android:minSdkVersion="8"          android:targetSdkVersion="21" />      <uses-permission android:name="android.permission.INTERNET"/>        <application          android:allowBackup="true"          android:icon="@drawable/ic_launcher"          android:label="@string/app_name"          android:theme="@style/AppTheme" >          <activity              android:name=".MainActivity"              android:label="@string/app_name" >              <intent-filter>                  <action android:name="android.intent.action.MAIN" />                    <category android:name="android.intent.category.LAUNCHER" />              </intent-filter>          </activity>      </application>    </manifest>  

Ứng dụng này được phát triển bởi adt bundleandroid 4.2 sử dụng minimum sdk 11  and target sdk 21.

Sau đó click vào Button "Load Web Page".
Tham khảo từ nguồn: Hiepsiit

About Học viện đào tạo trực tuyến

Xinh chào bạn. Tôi là Đinh Anh Tuấn - Thạc sĩ CNTT. Email: dinhanhtuan68@gmail.com .
- Nhận đào tạo trực tuyến lập trình dành cho nhà quản lý, kế toán bằng Foxpro, Access 2010, Excel, Macro Excel, Macro Word, chứng chỉ MOS cao cấp, IC3, tiếng anh, phần mềm, phần cứng .
- Nhận thiết kế phần mềm quản lý, Web, Web ứng dụng, quản lý, bán hàng,... Nhận Thiết kế bài giảng điện tử, số hóa tài liệu...
HỌC VIỆN ĐÀO TẠO TRỰC TUYẾN:TẬN TÂM-CHẤT LƯỢNG.
«
Next
Bài đăng Mới hơn
»
Previous
Bài đăng Cũ hơn