ページのURLを取得

広告

ページを表示した時に、表示されているページのURLを取得する方法を確認します。「WebView」クラスで用意されている「getUrl」メソッドを使います。

Get the url for the current page. This is not always the same as the url 
passed to BrowserCallback.onPageStarted because although the load for 
that url has begun, the current page may not have changed.

Returns
  The url for the current page.

メソッドを実行すると戻り値として現在表示されているページのURLを取得できます。

具体的には次のように記述します。

@Override protected void onCreate(Bundle icicle) {
    super.onCreate(icicle);

    WebView webview = new WebView(this);

    /* ... */

    String url = webview.getUrl();
}

サンプルプログラム

それでは実際に試してみます。プロジェクトを作成しソースコードを次のように変更しました。

Test09_01.java

package jp.javadrive.android;

import android.app.Activity;
import android.os.Bundle;
import android.widget.LinearLayout;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.widget.Button;
import android.view.View.OnClickListener;
import android.app.AlertDialog;

public class Test09_01 extends Activity implements OnClickListener{

    private final int FP = ViewGroup.LayoutParams.FILL_PARENT; 
    private final int WC = ViewGroup.LayoutParams.WRAP_CONTENT; 

    private Button buttonInfo;
    private WebView webview;

    @Override protected void onCreate(Bundle icicle) {
        super.onCreate(icicle);

        LinearLayout linearLayout = new LinearLayout(this);
        linearLayout.setOrientation(LinearLayout.VERTICAL);
        setContentView(linearLayout);

        buttonInfo = new Button(this);
        buttonInfo.setText("Info");
        buttonInfo.setOnClickListener(this);

        webview = new WebView(this);
        webview.loadUrl("http://www.google.co.jp/");

        linearLayout.addView(buttonInfo, createParam(WC, WC));
        linearLayout.addView(webview, createParam(WC, WC));
    }

    private LinearLayout.LayoutParams createParam(int w, int h){
        return new LinearLayout.LayoutParams(w, h);
    }

    public void onClick(View v) {
        String url = webview.getUrl();
        AlertDialog.show(this, "URL", url, "ok", false);
    }
}

ビルド後にエミュレーター上で実行します。

ページのURLを取得

初期値として指定したURLが表示されます。「Info」ボタンをクリックすると、現在のページのURLをダイアログで表示します。

ページのURLを取得

他のページでも試してみます。

ページのURLを取得

ページのURLを取得

( Written by Tatsuo Ikura )

Profile
profile_img

著者 / TATSUO IKURA

プログラミングや開発環境構築の解説サイトを運営しています。