05. 戻る、進む

04番までだと、1つ前に戻ることができなくて不便です。ついでに「進む」も実装してみましょう。

まずはレイアウト定義ファイル(layout/linearlayout.xml)を開き、ボタンを2つ追加します。

(太字部分)

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >
    <WebView
        android:id="@+id/webview"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_weight="1" />
    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
        <Button
            android:id="@+id/left_button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="←" />
        <Button
            android:id="@+id/right_button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="→" />
        <EditText
            android:id="@+id/addressbar"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:lines="1"
            android:hint="検索キーワード" />
        <Button
            android:id="@+id/ok_button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="実行" />
    </LinearLayout>
</LinearLayout>

次にJavaコードを変更します。(太字部分を追加)

    @Override
    protected void onCreate(Bundle savedInstanceState) {
         :
         :
        Button ok_button = (Button) findViewById(R.id.ok_button);
        ok_button.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                // TODO 自動生成されたメソッド・スタブ
                EditText addressbar = (EditText) findViewById(R.id.addressbar);
                String search_text = "https://www.google.co.jp/#q=" + addressbar.getText().toString();
                webview.loadUrl(search_text);
            }
        });
        Button left_button = (Button) findViewById(R.id.left_button);
        left_button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(webview.canGoBack()) webview.goBack();  //①
            }
        });
        Button right_button = (Button) findViewById(R.id.right_button);
        right_button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(webview.canGoForward()) webview.goForward();  //②
            }
        });
         :
         :

①は「戻る」ボタンの実装です。if文で、

webview.canGoBack()

をチェックしています。読んで字の如く、戻ることができる状態か?という意味です。これがtrueのときに

webview.goBack()

を実行します。②も同様の考え方で「進む(元に戻る、を戻る)」ボタンも実装します。

capture

これで、基本実装は完了です。