Exit warning on Webview

Asked

Viewed 203 times

1

I’m very beginner on android, so I made my application by Android Studio using Webview, but I’m having a question, when I press the back button of Android it already leaves the app, I would like to add that warning: (Are you sure you want to leave?)

Androidactivy.java:

package com.sirseni.simpleandroidwebviewexample;

import android.app.Activity; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.webkit.WebSettings; import android.webkit.WebView; import android.webkit.WebViewClient;

public class MainActivity extends Activity {

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

        WebView myWebView = (WebView) findViewById(R.id.myWebView);
        myWebView.loadUrl("http://192.99.73.131/");

        myWebView.setWebViewClient(new MyWebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return false;
            }

        });

        WebSettings webSettings = myWebView.getSettings();
        webSettings.setJavaScriptEnabled(true);

    }

    // Use When the user clicks a link from a web page in your WebView
    private class MyWebViewClient extends WebViewClient {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            if (Uri.parse(url).getHost().equals("http://192.99.73.131/")) {
                return false;

            }

            Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
            startActivity(intent);
            return true;
        }
    } }

Androidmanifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.sirseni.simpleandroidwebviewexample">

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

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme">
        <activity
            android:screenOrientation="portrait"
            android:name=".MainActivity"
            android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

2 answers

1


You can create the one AlertDialog defining the setPositiveButton() and setNegativeButton() within the method onBackPressed() in his Activity. Within the setPositiveButton() method you enter the code to finalize your application, such as Finish(). See the full code below:

@Override
public void onBackPressed() {
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setMessage("Tem certeza que deseja sair?")
    .setCancelable(false)
    .setPositiveButton("Sim", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int id) {

            //Este método faz com que o usuario saia da aplicação 
            finish();
        }
    })
    .setNegativeButton("Não", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int id) {
            dialog.cancel();
        }
    });
    AlertDialog alert = builder.create();
    alert.show();
}

1

In your Activity override the onBackPressed method, don’t know how to do it? It’s like this:

@Override
public void onBackPressed() {

// Ai você precisa criar uma AlertDialog
confirmarSaida();

}

private void confirmarSaida() {

    //Criamos o componente AlertDialog, que nada mais é do que um "pop up".

    AlertDialog.Builder builder = new AlertDialog.Builder(getApplicationContext());
    builder.setTitle("titulo da janela"); // Ex: Aviso!
    builder.setMessage("mensagem da janela"); //Ex: Deseja realmente sair?
    builder.setNegativeButton("Não", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialogInterface, int i) {

            dialogInterface.dismiss();

        }
    });
    builder.setPositiveButton("Sim", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialogInterface, int i) {

            //Aqui você implementa o código para sair do app

        }
    });

    //Mostramos o componente alert dialog
    builder.show();


}

Remembering that for best practices on the android platform, your strings should be set in the "strings.xml" file inside the "values" folder of your project.

  • I will try, soon I will comment on the result, even so very grateful!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.