WebView小Demo

3121 ワード

// :
<?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" >
    <LinearLayout 
        android:orientation="horizontal"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
    >
       <EditText 
           android:id="@+id/urlEditText"
           android:layout_width="255dip"
           android:layout_height="wrap_content"        
           android:lines="1"
           android:inputType="textUri"
           android:imeOptions="actionGo"
       />  
       <Button 
           android:id="@+id/button"
           android:layout_width="wrap_content"  
           android:layout_height="wrap_content"
           android:text="@string/button"
       />
   </LinearLayout>
   <WebView
       android:id="@+id/webView"
       android:layout_height="0dip"
       android:layout_width="match_parent"
       android:layout_weight="1.0"
    />
</LinearLayout>



//Activity :
package cn.com.bravesoft;
import android.app.Activity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.EditText;

public class WebViewTest1Activity extends Activity {
	private EditText urlWebView;
	private Button button;
	private WebView webView;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        urlWebView=(EditText) findViewById(R.id.urlEditText);
        button=(Button) findViewById(R.id.button);
        webView=(WebView) findViewById(R.id.webView);
        
        button.setOnClickListener(new OnClickListener() {// 			
			@Override
			public void onClick(View v) {
				openBrose();				
			}
		});
        urlWebView.setOnKeyListener(new OnKeyListener() {// . 
			@Override
			public boolean onKey(View v, int keyCode, KeyEvent event) {
				if(keyCode==KeyEvent.KEYCODE_ENTER){
					openBrose();
					return true;
				}
				return false;
			}
		});
    }
    
    private void openBrose(){
    	webView.getSettings().setJavaScriptEnabled(true);// JavaScript
    	webView.loadUrl(urlWebView.getText().toString());// url    	
    }
}