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

时间:2016-06-06 18:45:09

标签: android android-fragments webview

我想在我的WebView片段中实现一个代码,以回到之前的页面。我找到了一个解决方案here,但我不知道在我的WebView片段中将它添加到何处。有人可以帮我弄这个吗?我应该将它添加到MainActivity还是我的WebView片段中?

MyWebViewFragment.java:

package tkr.firstprojects.com.tkr;

import android.app.Fragment;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebBackForwardList;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class MyWebViewFragment extends Fragment {

WebView webview;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.web_fragment, container,
            false);

    Bundle bundle = getArguments();

    String url = bundle.getString("url");

    webview = (WebView) rootView.findViewById(R.id.webView1);

    WebSettings settings = webview.getSettings();
    settings.setJavaScriptEnabled(true);
    settings.setBuiltInZoomControls(true);
    settings.setSupportZoom(true);


    webview.loadUrl(url);

    webview.setWebViewClient(new WebViewClient() {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {

            view.loadUrl(url);
            return true;
        }



    });

    return rootView;


 }
}

这是我想从解决方案中添加的代码,以回到之前的页面。我应该在哪里添加这个?

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

1 个答案:

答案 0 :(得分:1)

在片段活动中

@Override
public void onBackPressed() {
   //Get fragment and webview from the fragment
   webview.goBack();
}