在WebView中按下后退按钮如何返回上一页?

发布于 2024-11-09 11:14:18 字数 1585 浏览 0 评论 0原文

我有一个应用程序,其中有一个 WebView,可以在其中显示一些网站。它有效,单击网页中的链接会转到我的应用程序内网站的下一页。但是当我点击手机的后退按钮时,它会直接进入我的应用程序。我想返回网站的上一页。我该怎么做?

这是我正在使用的代码示例:

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);
            }
        });
    }
}

I have an app in which I have a WebView where I display some websites. 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);
            }
        });
    }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(19

孤独难免 2024-11-16 11:14:19

在 Kotlin 中 friederbluemle 的答案是:

webView.setOnKeyListener { v, keyCode, event ->
            var rv = false
            if (event.action == KeyEvent.ACTION_DOWN &&
                keyCode ==  KeyEvent.KEYCODE_BACK) {
                (v as WebView).goBack()
                rv = true
            }
            rv
        }

In Kotlin friederbluemle's answer is:

webView.setOnKeyListener { v, keyCode, event ->
            var rv = false
            if (event.action == KeyEvent.ACTION_DOWN &&
                keyCode ==  KeyEvent.KEYCODE_BACK) {
                (v as WebView).goBack()
                rv = true
            }
            rv
        }
初见终念 2024-11-16 11:14:19

使用此代码返回页面,当最后一页出现时,然后退出活动

 @Override
    public void onBackPressed() {
        super.onBackPressed();
        Intent intent=new Intent(LiveImage.this,DashBoard.class);
        startActivity(intent);
    }

use this code to go back on page and when last page came then go out of activity

 @Override
    public void onBackPressed() {
        super.onBackPressed();
        Intent intent=new Intent(LiveImage.this,DashBoard.class);
        startActivity(intent);
    }
樱桃奶球 2024-11-16 11:14:18

我在 WebView 的活动中使用类似的内容:

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (event.getAction() == KeyEvent.ACTION_DOWN) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_BACK:
                if (mWebView.canGoBack()) {
                    mWebView.goBack();
                } else {
                    finish();
                }
                return true;
        }

    }
    return super.onKeyDown(keyCode, event);
}

编辑:

为了使此代码正常工作,您需要向包含 WebView 的 Activity 添加一个字段:

private WebView mWebView;

onCreate()< 中初始化它/code> 方法,你应该可以开始了。

mWebView = (WebView) findViewById(R.id.webView);

I use something like this in my activities with WebViews:

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (event.getAction() == KeyEvent.ACTION_DOWN) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_BACK:
                if (mWebView.canGoBack()) {
                    mWebView.goBack();
                } else {
                    finish();
                }
                return true;
        }

    }
    return super.onKeyDown(keyCode, event);
}

Edit:

For this code to work, you need to add a field to the Activity containing the WebView:

private WebView mWebView;

Initialize it in the onCreate() method and you should be good to go.

mWebView = (WebView) findViewById(R.id.webView);
橙幽之幻 2024-11-16 11:14:18

如果使用 Android 2.2 及更高版本(现在大多数设备),以下代码将满足您的需求。

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

If using Android 2.2 and above (which is most devices now), the following code will get you what you want.

@Override
public void onBackPressed() {
    if (webView.canGoBack()) {
        webView.goBack();
    } else {
        super.onBackPressed();
    }
}
昔梦 2024-11-16 11:14:18

这是我的解决方案。它也适用于 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;
    }
});

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;
    }
});
永言不败 2024-11-16 11:14:18

下一个按钮和进度条的完整参考:在 webview 中放置后退和下一个按钮

如果您愿意单击手机的后退按钮时转到后退页面,使用以下方法:

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

您还可以创建自定义后退按钮,如下所示:

btnback.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub

            if (wv.canGoBack()) {
                wv.goBack();
            }
        }
    }); 

Full reference for next button and progress bar : put back and next button in webview

If you want to go to back page when click on phone's back button, use this:

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

You can also create custom back button like this:

btnback.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub

            if (wv.canGoBack()) {
                wv.goBack();
            }
        }
    }); 
心房敞 2024-11-16 11:14:18

焦点也应该在 onBackPressed 中检查

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

Focusing should also be checked in onBackPressed

    @Override
    public void onBackPressed() {
        if (mWebview.isFocused() && mWebview.canGoBack()) {
            mWebview.goBack();       
        } else {
            super.onBackPressed();
            finish();
        }
    }
ㄟ。诗瑗 2024-11-16 11:14:18

为什么不使用onBackPressed()

@Override
public void onBackPressed() {
    // super.onBackPressed(); Do not call me!

    // Go to the previous web page.
}

Why not use onBackPressed()?

@Override
public void onBackPressed() {
    // super.onBackPressed(); Do not call me!

    // Go to the previous web page.
}
九命猫 2024-11-16 11:14:18

这是确认退出的代码:

@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();    
        }   
    }

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();    
        }   
    }
睫毛上残留的泪 2024-11-16 11:14:18

在 kotlin 中:

override fun onBackPressed() {
    when {
        webView.canGoBack() -> webView.goBack()
        else -> super.onBackPressed()
    }
}

webView - xml 中 webview 组件的 id(如果使用合成引用)。

In kotlin:

override fun onBackPressed() {
    when {
        webView.canGoBack() -> webView.goBack()
        else -> super.onBackPressed()
    }
}

webView - id of the webview component in xml, if using synthetic reference.

嗼ふ静 2024-11-16 11:14:18
@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);
}
@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);
}
猫烠⑼条掵仅有一顆心 2024-11-16 11:14:18
 WebView mWebView;

 mWebView = findViewById(R.id.webView);

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

 mWebView = findViewById(R.id.webView);

    @Override
    public void onBackPressed() {
        if (webView.canGoBack()) {
            webView.goBack();
        } else {
            super.onBackPressed();
        }
    }
余生共白头 2024-11-16 11:14:18

我想我有点晚了,但根据 android 文档 ,您可以通过以下代码在片段内自定义后退导航。

 requireActivity().onBackPressedDispatcher.addCallback(this) {
            // Handle the back button event
            if (binding.webView.canGoBack()){
                binding.webView.goBack()
            } else {
                findNavController().popBackStack()
            }
        }

您可以根据需要自定义 webView 无法返回时要执行的操作。

I think I'm a little late but according to the android documentation, you can have custom back navigation inside fragments done by the following piece of code.

 requireActivity().onBackPressedDispatcher.addCallback(this) {
            // Handle the back button event
            if (binding.webView.canGoBack()){
                binding.webView.goBack()
            } else {
                findNavController().popBackStack()
            }
        }

you can customize what to do when you the webView cant go back as per your needs.

音盲 2024-11-16 11:14:18

FoamyGuy 的第一个答案是正确的,但我有一些补充;低声誉不允许我发表评论。如果由于某些原因您的页面无法加载,请确保设置一个标记来记录失败,然后在 onBackPressed 覆盖中检查它。否则,您的 canGoBack() 将永远执行,而不会前往实际的返回活动(如果存在):

//flag with class wide access 
public boolean ploadFailFlag = false;

//your error handling override
@Override
public void onReceivedError(WebView view, WebResourceRequest req, WebResourceError rerr) {
    onReceivedError(view, rerr.getErrorCode(), rerr.getDescription().toString(), req.getUrl().toString());
    ploadFailFlag = true;       //note this change 
    .....
    .....
}

//finally to the answer to this question:
@Override
public void onBackPressed() {
    if(checkinWebView.canGoBack()){
        //if page load fails, go back for web view will not go back - no page to go to - yet overriding the super 
        if(ploadFailFlag){
            super.onBackPressed();
        }else {
            checkinWebView.goBack();
        }
    }else {
        Toast.makeText(getBaseContext(), "super:", Toast.LENGTH_LONG).show();
        super.onBackPressed();
    }
}

The first answer by FoamyGuy is correct but I have some additions; low reputations cannot allow me to do comments. If for some reasons your page fails to load, ensure that you set a flag to take note of the failure and then check it on the onBackPressed override. Otherwise your canGoBack() will be forever executed without heading to the actual back activity if it was there:

//flag with class wide access 
public boolean ploadFailFlag = false;

//your error handling override
@Override
public void onReceivedError(WebView view, WebResourceRequest req, WebResourceError rerr) {
    onReceivedError(view, rerr.getErrorCode(), rerr.getDescription().toString(), req.getUrl().toString());
    ploadFailFlag = true;       //note this change 
    .....
    .....
}

//finally to the answer to this question:
@Override
public void onBackPressed() {
    if(checkinWebView.canGoBack()){
        //if page load fails, go back for web view will not go back - no page to go to - yet overriding the super 
        if(ploadFailFlag){
            super.onBackPressed();
        }else {
            checkinWebView.goBack();
        }
    }else {
        Toast.makeText(getBaseContext(), "super:", Toast.LENGTH_LONG).show();
        super.onBackPressed();
    }
}
与酒说心事 2024-11-16 11:14:18

如果有人想在 fragment 中处理 webView 的 backPressed,那么他可以使用下面的代码。

  1. 将以下代码复制到您的 Activity 类中(包含片段 YourFragmmentName

    <前><代码>@Override
    公共无效onBackPressed(){
    列表<片段> fragmentList = getSupportFragmentManager().getFragments();

    布尔处理 = false;
    for(对象 f:fragmentList) {
    if(f 你的片段名称实例) {
    处理 = ((YourFragmentName)f).onBackPressed();
    如果(已处理){
    休息;
    }
    }
    }

    如果(!处理){
    super.onBackPressed();
    }

    }

  2. 将此代码复制到片段 YourFragmentName 中

    public boolean onBackPressed() {
       如果 (webView.canGoBack()) {
           webView.goBack();
           返回真;
       } 别的 {
           返回假;
       }
    }
    

Notes

  • Activity 应替换为您正在使用的实际 Acitivity 类。
  • YourFragmentName 应替换为您的片段的名称。
  • YourFragmentName 中声明 webView,以便可以从函数内访问它。

If someone wants to handle backPressed for a webView inside a fragment, then he can use below code.

  1. Copy below code into your Activity class (that contains a fragment YourFragmmentName)

    @Override
    public void onBackPressed() {
    List<Fragment> fragmentList = getSupportFragmentManager().getFragments();
    
    boolean handled = false;
    for(Object f: fragmentList) {
        if(f instanceof YourFragmentName) {
            handled = ((YourFragmentName)f).onBackPressed();
            if(handled) {
                break;
            }
        }
    }
    
    if(!handled) {
        super.onBackPressed();
    }
    

    }

  2. Copy this code in the fragment YourFragmentName

    public boolean onBackPressed() {
       if (webView.canGoBack()) {
           webView.goBack();
           return true;
       } else {
           return false;
       }
    }
    

Notes

  • Activity should be replaced with the actual Acitivity class you are using.
  • YourFragmentName should be replaced with the name of your Fragment.
  • Declare webView in YourFragmentName so that it can be accessed from within the function.
深府石板幽径 2024-11-16 11:14:18

您可以在片段中尝试对 webview 进行此操作:

private lateinit var webView: WebView

override fun onCreateView(
    inflater: LayoutInflater,
    container: ViewGroup?,
    savedInstanceState: Bundle?
): View? {
    val root = inflater.inflate(R.layout.fragment_name, container, false)
    webView = root!!.findViewById(R.id.home_web_view)
    var url: String = "http://yoururl.com"
    webView.settings.javaScriptEnabled = true
    webView.webViewClient = WebViewClient()
    webView.loadUrl(url)
    webView.canGoBack()
    webView.setOnKeyListener{ v, keyCode, event ->
        if(keyCode == KeyEvent.KEYCODE_BACK && event.action == MotionEvent.ACTION_UP
            && webView.canGoBack()){
            webView.goBack()
            return@setOnKeyListener true
        }
        false
    }
    return root
}

You can try this for webview in a fragment:

private lateinit var webView: WebView

override fun onCreateView(
    inflater: LayoutInflater,
    container: ViewGroup?,
    savedInstanceState: Bundle?
): View? {
    val root = inflater.inflate(R.layout.fragment_name, container, false)
    webView = root!!.findViewById(R.id.home_web_view)
    var url: String = "http://yoururl.com"
    webView.settings.javaScriptEnabled = true
    webView.webViewClient = WebViewClient()
    webView.loadUrl(url)
    webView.canGoBack()
    webView.setOnKeyListener{ v, keyCode, event ->
        if(keyCode == KeyEvent.KEYCODE_BACK && event.action == MotionEvent.ACTION_UP
            && webView.canGoBack()){
            webView.goBack()
            return@setOnKeyListener true
        }
        false
    }
    return root
}
泪痕残 2024-11-16 11:14:18

这是 Kotlin 的解决方案:

override fun onKeyUp(keyCode: Int, event: KeyEvent?): Boolean {
    if (event?.action != ACTION_UP || event.keyCode != KEYCODE_BACK) {
        return super.onKeyUp(keyCode, event)
    }

    if (mWebView.canGoBack()) {
        mWebView.goBack()
    } else {
        finish()
    }
    return true
}

Here is the Kotlin solution:

override fun onKeyUp(keyCode: Int, event: KeyEvent?): Boolean {
    if (event?.action != ACTION_UP || event.keyCode != KEYCODE_BACK) {
        return super.onKeyUp(keyCode, event)
    }

    if (mWebView.canGoBack()) {
        mWebView.goBack()
    } else {
        finish()
    }
    return true
}
扎心 2024-11-16 11:14:18

您应该在类中使用以下库来处理 onBackKeyPressed。
canGoBack() 检查 webview 是否可以引用上一页。如果可能,请使用 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
    }
}

You should the following libraries on your class handle the onBackKeyPressed.
canGoBack() checks whether the webview can reference to the previous page. If it is possible then use the goBack() function to reference the previous page (go back).

@Override
public void onBackPressed() {
    if( mWebview.canGoBack()){
        mWebview.goBack(); 
    } else {
        //Do something else. like trigger pop up. Add rate app or see more app
    }
}
一人独醉 2024-11-16 11:14:18

官方 Kotlin 方式:

override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
    // 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)
}

https://developer.android.com/guide/webapps/ webview.html#NavigatingHistory

Official Kotlin Way:

override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
    // 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)
}

https://developer.android.com/guide/webapps/webview.html#NavigatingHistory

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文