ページのタイトルを取得

広告
facebookボタン
googleplusボタン
twitterボタン
ダミーボタン
bloggerボタン

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

getTitle
public String getTitle()
Get the title for the current page. This is the title of the current 
page until BrowserCallback.onReceivedTitle is called.

Returns
  The title for the current page.

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

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

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

    WebView webview = new WebView(this);

    /* ... */

    String title = webview.getTitle();
}

サンプルプログラム

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

Test08_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 Test08_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 title = webview.getTitle();
        AlertDialog.show(this, "Title", title, "ok", false);
    }
}

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

ページのタイトルを取得

初期値として指定したURLが表示されます。

ページが表示されている状態で「Info」ボタンをクリックすると、現在のページのタイトルをダイアログで表示します。

ページのタイトルを取得

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

ページのタイトルを取得

ページのタイトルを取得

( Written by T.buzz.Ikura+ )

Facebook Page