📜  如何在Android中使用WebView

📅  最后修改于: 2021-05-09 18:02:51             🧑  作者: Mango

public class WebView 
extends AbsoluteLayout 
implements 
    ViewTreeObserver.OnGlobalFocusChangeListener, 
    ViewGroup.OnHierarchyChangeListener

WebView是在应用程序内部显示网页的视图。它用于将应用程序转换为Web应用程序。

类层次结构:

java.lang.Object
   ↳  android.view.View
        ↳  android.view.ViewGroup
             ↳  android.widget.AbsoluteLayout
                  ↳  android.webkit.WebView

主要活动。Java

package com.example.hp.webview;
  
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.webkit.WebView;
import android.webkit.WebViewClient;
  
public class MainActivity extends AppCompatActivity {
  
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
          
        // Binding MainActivity.java with 
        // activity_main.xml file
        setContentView(R.layout.activity_main);
          
        // Find the WebView by its unique ID
        WebView w = (WebView) findViewById(R.id.web);
          
        // loading http://www.google.com url in the the WebView.
        w.loadUrl("http://www.google.com");
          
        // this will enable the javascipt.
        w.getSettings().setJavaScriptEnabled(true);
          
        // WebViewClient allows you to handle 
        // onPageFinished and override Url loading.
        w.setWebViewClient(new WebViewClient());
          
    }
}

activity_main.xml

在xml文件中,仅在RelativeLayout内部使用WebView。



  
    
        android:layout_width="368dp"
          
        
        android:id="@+id/web"
          
        
        android:layout_height="495dp"
          
        tools:layout_editor_absoluteX="8dp"
        tools:layout_editor_absoluteY="8dp" />

AndroidManifest.xml中,需要包含以下权限才能访问互联网:

"uses-permission android:name="android.permission.INTERNET"