如何在片段中处理webview背压

时间:2017-08-01 16:25:23

标签: android webview fragment android-webview back

我想在网页视图中返回按功能,转到网页视图中的上一页(片段中)...

Here is the fragment code

我尝试添加以下不起作用的代码:

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {

    if (keyCode == KeyEvent.KEYCODE_BACK){
        if(Wv.canGoBack()){
            Wv.goBack();
            return true;
        }
    }
    return super.onKeyDown(keyCode, event);
}

我该如何解决这个问题?

2 个答案:

答案 0 :(得分:1)

这项工作对我来说

public class MyWebView extends Fragment {
    private WebView mWebView;
    private View rootView;
    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message message) {
            switch (message.what) {
                case 1:{
                    webViewGoBack();
                }break;
            }
        }
    };

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        rootView = inflater.inflate(R.layout.testwebview, null);
        mWebView = (WebView)rootView.findViewById(R.id.webview);


        mWebView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
        mWebView.getSettings().setBuiltInZoomControls(false);
        mWebView.loadUrl("myurl...");
        mWebView.setOnKeyListener(new View.OnKeyListener(){

            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_BACK
                        && event.getAction() == MotionEvent.ACTION_UP
                        && mWebView.canGoBack()) {
                    handler.sendEmptyMessage(1);
                    return true;
                }

                return false;
            }

        });
            return rootView;
    }

    private void webViewGoBack(){
        mWebView.goBack();
    }
}

答案 1 :(得分:0)

在您的活动中获取Fragment的实例,并覆盖onBackPressed方法。

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