Androidプログラマへの道 〜 Moonlight 明日香 〜 - 閲覧履歴に基づいて移動する
Webページの閲覧するとその履歴が内部的に保持されている.
閲覧履歴に基づいて前後のWebページに移動するには, ウェブビュー(WebView)クラスのgoBack/goForwardメソッドを利用する.


               ↓ Back


閲覧履歴に基づいて前後に移動

  • res/layout/main.xml
    • 各ボタンにonClickメソッドを設定する.
    • WebView要素を定義する.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  >
  <LinearLayout
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    >
    <Button android:id="@+id/button01_id"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="@string/button01_label"
      android:layout_weight="1"
      android:onClick="onClickButton"
      />
    <Button android:id="@+id/button02_id"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="@string/button02_label"
      android:layout_weight="1"
      android:onClick="onClickButton"
      />
  </LinearLayout>
  <WebView android:id="@+id/webview_id"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    />
</LinearLayout>
  • WebView01.java
    • onClickイベントハンドラとして, onClickButtonメソッドを実装する.
    • ビューのIDを取得する.
    • WebView#canGoBack/canGoForwardメソッドで, 移動可能か確認する.
    • WebView#goBack/goForwardメソッドで, 閲覧履歴に基づいて移動する.
package com.moonlight_aska.android.webview01;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class WebView01 extends Activity {
  private WebView web;
  /** Called when the activity is first created. */
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    web = (WebView)findViewById(R.id.webview_id);
    web.setWebViewClient(new WebViewClient());
    web.loadUrl("http://www.google.com");
  }

  public void onClickButton(View v) {
    int id = v.getId();
    if(id == R.id.button01_id) { // Back
      if(web.canGoBack()) {
        web.goBack();
      }
    }
    else if(id == R.id.button02_id) { // Forward
      if(web.canGoForward()) {
        web.goForward();
      }
    }
  }
}