WebView с диалоговым окном открытия кнопки назад - PullRequest
0 голосов
/ 04 мая 2011

Я создаю приложение, которое открывает URL-адрес внутри веб-просмотра. Затем при нажатии кнопки «Назад» открывается диалоговое окно, спрашивающее пользователя, уверены ли они, что хотят выйти. Хотя диалоговое окно работает правильно, приложение не будет загружать веб-сайт, и теперь у меня возникают ошибки, поэтому я не могу даже скомпилировать, когда вставляю HelloWebViewClient. Вы предлагаете что-нибудь? Спасибо!

Вот мой код:

package de.vogella.android.alertdialog;





import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Toast;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class ShowMyDialog extends Activity {
    private WebView webview;

    /** Called when the activity is first created. */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK)) {
            openMyDialog(null);
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }




    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        webview = (WebView) findViewById(R.id.webview);
        webview.setWebViewClient(new HelloWebViewClient());
        webview.getSettings().setJavaScriptEnabled(true);
        webview.setInitialScale(50); 
        webview.getSettings().setUseWideViewPort(true); 
        webview.loadUrl("http://mdsitest2.com/");
    }
    private class HelloWebViewClient extends WebViewClient {

        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);
            return true;


            }







    public void openMyDialog(View view) {
        showDialog(10);
    }

    @Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
        case 10:
            // Create our AlertDialog
            Builder builder = new AlertDialog.Builder(this);
            builder.setMessage("Are you sure you want to exit?")
                    .setCancelable(true)
                    .setPositiveButton("Yes",
                            new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog,
                                        int which) {
                                    // Ends the activity
                                    ShowMyDialog.this.finish();
                                }
                            })
                    .setNegativeButton("Keep Guessing!",
                            new DialogInterface.OnClickListener() {

                                @Override
                                public void onClick(DialogInterface dialog,
                                        int which) {
                                    Toast.makeText(getApplicationContext(),
                                            "Good Luck!",
                                            Toast.LENGTH_SHORT).show();
                                }
                            });


            AlertDialog dialog = builder.create();
            dialog.show();

        }
        return super.onCreateDialog(id);
    }
}

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">



<WebView  xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/webview"
    android:layout_height="fill_parent" android:layout_width="fill_parent" android:scrollbarAlwaysDrawVerticalTrack="false"/>




</LinearLayout>

1 Ответ

0 голосов
/ 04 мая 2011

Попробуйте переопределить кнопку onBackPressed вместо того, чтобы делать это через onKeyDown.Также реализовать комментарий Пикси сделал ...

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...