android使用webview時按後退退出的問題
最近將要把美女圖片打包成安卓
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.cn/");//這裏的就會加載網址:http://www.gg4493/到webview中 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 SimplifiableIfStatementif (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.gg4493.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);
}
}
android使用webview時按後退退出的問題