android使用webview时按后退退出的问题

使用webview打包html5游戏,代码都好了,具体如下

public class MainActivity extends ActionBarActivity {

    @Override
protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
         WebView webView=new WebView(this);
        webView.getSettings().setJavaScriptEnabled(true);//支持js
webView.loadUrl("http://www.gg4493.com/");
        webView.setWebViewClient(new MyWebViewClient());


    }


    @Override
public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();

        //noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

一切貌似很完美,玩游戏,被电脑打败了,点击“更多游戏”去查看其他游戏,然后点返回键,问题来了,不是挖掘技术哪家强,是webview没有后退功能,没法退回首页,而是直接退出,android开发问题还真多啊,还好哥机灵,找资料呗!

终于找到问题了,

只需要重写activity的onKeyDown方法,在onKeyDown里后退即可

public boolean onKeyDown(int keyCode ,KeyEvent keyEvent){
if(keyCode==keyEvent.KEYCODE_BACK){//监听返回键,如果可以后退就后退
if(webView.canGoBack()){
webView.goBack();
return true;
}
}
return super.onKeyDown(keyCode, keyEvent);

}

全部代码贴出,免得以后忘记

import android.app.Activity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Menu;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;


public class MainActivity extends Activity {
private WebView webView;


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
init();
}


@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}


private void init() {
webView = new WebView(this);
 webView.loadUrl("http://www.mm4493.cn/");
 WebSettings settings = webView.getSettings();
 settings.setJavaScriptEnabled(true);
 webView.setWebViewClient(new WebViewClient() {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
  view.loadUrl(url);
return true;
}

});
setContentView(webView);

public boolean onKeyDown(int keyCode ,KeyEvent keyEvent){
if(keyCode==keyEvent.KEYCODE_BACK){
if(webView.canGoBack()){
webView.goBack();
return true;
}
}
return super.onKeyDown(keyCode, keyEvent);

}
}

相关推荐