Android の WebView を使う簡単なサンプル
注意すべきは、表示したページのリンクをクリックしてスマホのブラウザを起動しないように
WebViewClient インスタンスをセットすること。
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.EditText;
public class SampleWebView extends Activity {
private WebView web;
/**
* Called when the activity is first created.
*/
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//
final Button button = (Button)findViewById(R.id.button1);
this.web = (WebView)findViewById(R.id.webView1);
this.web.getSettings().setJavaScriptEnabled(true);
final OnClickListener listner = new OnClickListener(){
@Override
public void onClick(View v){
// URL を入力する EditText
final EditText edit = (EditText)findViewById(R.id.editText1);
getWebView().loadUrl(edit.getText().toString());
getWebView().requestFocus();
}
};
button.setOnClickListener(listner);
// WebView を default client にして default browse 起動しないように
this.web.setWebViewClient(new WebViewClient());
}
protected WebView getWebView(){
return this.web;
}
}
main.xml は、以下
<?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"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
<LinearLayout android:id="@+id/linearLayout1" android:layout_width="match_parent"
android:layout_height="wrap_content">
<EditText android:layout_width="wrap_content" android:id="@+id/editText1"
android:layout_weight="1" android:layout_height="wrap_content">
<requestFocus></requestFocus>
</EditText>
<Button android:text="Go" android:id="@+id/button1" android:layout_width="wrap_content"
android:layout_height="wrap_content"></Button>
</LinearLayout>
<WebView android:id="@+id/webView1" android:layout_width="match_parent"
android:layout_height="match_parent"></WebView>
</LinearLayout>