• After 15+ years, we've made a big change: Android Forums is now Early Bird Club. Learn more here.

Webview Example

Hello

I am a newbie.

I am using Android Studio (Android Studio Dolphin | 2021.3.1 Patch 1).

Is there a simple 'webview' example which I can refer to?

Please advise.

Thanks.
 
Here is a simple example of how to use a WebView in an Android app:

Code:
import android.os.Bundle;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

    private WebView webView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        webView = findViewById(R.id.webview);
        webView.setWebViewClient(new WebViewClient());
        webView.loadUrl("https://www.example.com");
    }

    @Override
    public void onBackPressed() {
        if (webView.canGoBack()) {
            webView.goBack();
        } else {
            super.onBackPressed();
        }
    }
}

You will need to add the INTERNET permission to your app's manifest file in order to use a WebView. To do this, add the following line to your AndroidManifest.xml file:

Code:
<uses-permission android:name="android.permission.INTERNET"/>

You will also need to add the WebView element to your layout file. For example, you could add the following to your activity_main.xml layout file:

Code:
<WebView
    android:id="@+id/webview"
    android:layout_width="match_parent"
    android:layout_height="match_parent"/>
 
Back
Top Bottom