模拟器测程序坑死人啊,模拟器监听不到返回键的长按事件,搞了半天没看出问题,于是拿真机跑了一下,而真机能!
public class MainActivity extends ActionBarActivity { WebView mWebView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mWebView = (WebView) findViewById(R.id.mWebView); mWebView.loadUrl("https://www.baidu.com/"); mWebView.setWebViewClient(new WebViewClient(){//网页在webview中打开,不跳转浏览器 @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { view.loadUrl(url); return true; } }); } @Override public boolean dispatchKeyEvent(KeyEvent event) {//按键事件分发 if (event.getKeyCode()==event.KEYCODE_BACK ){ if (event.isLongPress()){ Log.e("","长按"); finish(); return true;//返回true表示消费事件(拦截事件),事件不再向下传递 } else { if(mWebView.canGoBack()){ Log.e("","后退"); mWebView.goBack(); return true; } } } return super.dispatchKeyEvent(event); } }