如果在WebView中按下後退按鈕,如何返回上一頁?

本文翻譯自:How to go back to previous page if back button is pressed in WebView?

I have an app in which I have a WebView where I display some websites. 我有一個應用程序,其中有一個WebView ,可以顯示一些網站。 It works, clicking a link in the webpage goes to the next page in the website inside my app. 它的工作原理是,單擊網頁中的鏈接可轉到應用程序內網站的下一頁。 But when I click the phone's back button, it takes me straight into my app. 但是,當我單擊手機的後退按鈕時,它將帶我直接進入我的應用程序。 I want to go back to the previous page in the website instead. 我想回到網站的上一頁。 How can I do this? 我怎樣才能做到這一點?

Here is the code sample I'm using: 這是我正在使用的代碼示例:

public class Webdisplay extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);

        this.getWindow().requestFeature(Window.FEATURE_PROGRESS);
        setContentView(R.layout.webdisplay);

        getWindow().setFeatureInt(Window.FEATURE_PROGRESS,
                Window.PROGRESS_VISIBILITY_ON); 

        Toast loadingmess = Toast.makeText(this,
                "Cargando El Diario de Hoy", Toast.LENGTH_SHORT);
        loadingmess.show();

        WebView myWebView;

        myWebView = (WebView) findViewById(R.id.webview);
        myWebView.getSettings().setJavaScriptEnabled(true);
        myWebView.loadUrl("http://www.elsalvador.com");
        myWebView.setWebViewClient(new WebViewClient());
        myWebView.setInitialScale(1);
        myWebView.getSettings().setBuiltInZoomControls(true);
        myWebView.getSettings().setUseWideViewPort(true);

        final Activity MyActivity = this;
        myWebView.setWebChromeClient(new WebChromeClient() 
        {
            public void onProgressChanged(WebView view, int progress)   
            {
                MyActivity.setTitle("Loading...");
                MyActivity.setProgress(progress * 100); 

                if(progress == 100)
                    MyActivity.setTitle(R.string.app_name);
            }
        });
    }
}

#1樓

參考:https://stackoom.com/question/PUwP/如果在WebView中按下後退按鈕-如何返回上一頁


#2樓

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    // Check if the key event was the Back button and if there's history
    if ((keyCode == KeyEvent.KEYCODE_BACK) && myWebView.canGoBack()) {
        myWebView.goBack();
        return true;
    }
    // If it wasn't the Back key or there's no web page history, bubble up to the default
    // system behavior (probably exit the activity)
    return super.onKeyDown(keyCode, event);
}

#3樓

This is my solution. 這是我的解決方案。 It works also in Fragment. 它也可以在片段中使用。

webView.setOnKeyListener(new OnKeyListener()
{
    @Override
    public boolean onKey(View v, int keyCode, KeyEvent event)
    {
        if(event.getAction() == KeyEvent.ACTION_DOWN)
        {
            WebView webView = (WebView) v;

            switch(keyCode)
            {
                case KeyEvent.KEYCODE_BACK:
                    if(webView.canGoBack())
                    {
                        webView.goBack();
                        return true;
                    }
                    break;
            }
        }

        return false;
    }
});

#4樓

here is a code with confirm exit: 這是帶有確認退出的代碼:

@Override
    public void onBackPressed()
    {
        if(webView.canGoBack()){
            webView.goBack();
        }else{
            new AlertDialog.Builder(this)
            .setIcon(android.R.drawable.ic_dialog_alert)
            .setTitle("Exit!")
            .setMessage("Are you sure you want to close?")
            .setPositiveButton("Yes", new DialogInterface.OnClickListener()
            {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    finish();    
                }

            })
            .setNegativeButton("No", null)
            .show();    
        }   
    }

#5樓

Focusing should also be checked in onBackPressed 聚焦也應在onBackPressed中檢查

    @Override
    public void onBackPressed() {
        if (mWebview.isFocused() && mWebview.canGoBack()) {
            mWebview.goBack();       
        } else {
            super.onBackPressed();
            finish();
        }
    }

#6樓

You should the following libraries on your class handle the onBackKeyPressed. 您應該在您的類中的以下庫處理onBackKeyPressed。 canGoBack() checks whether the webview can reference to the previous page. canGoBack()檢查Web視圖是否可以引用上一頁。 If it is possible then use the goBack() function to reference the previous page (go back). 如果可能的話,請使用goBack()函數引用上一頁(返回)。

 @Override
        public void onBackPressed() {
          if( mWebview.canGoBack()){
               mWebview.goBack(); 
           }else{
            //Do something else. like trigger pop up. Add rate app or see more app
           }
  }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章