WebView中的OnKeyDown事件未处理 - Android

时间:2016-03-13 07:48:36

标签: android button webview back

我无法在WebView内的Android上调用Back按钮。我尝试使用OnKeyDownOnKeyOnBackPressed 我目前的代码如下:

public class MainActivity extends AppCompatActivity {
    final Activity activity = this;
    private WebView mWebView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mWebView = (WebView) findViewById(R.id.activity_main_webview);
        WebSettings webSettings = mWebView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        mWebView.loadUrl("file:///android_asset/index.html");

    }
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK) && mWebView!=null && mWebView.canGoBack()) {
            mWebView.goBack();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

}

错误表示函数OnKeyDown未实现......任何想法? 非常感谢你:))

1 个答案:

答案 0 :(得分:1)

试试此代码

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

更新:如果上面的代码失败,请尝试这个

@Override
public void onBackPressed()
{

   if (mWebView.canGoBack()) {
            mWebView.goBack();
        } else {
            finish();
        }      
}