預覽文章: android使用webview時按後退退出的問題

使用webview打包美女圖片站點http://www.gg4493.cn,代碼都好了,具體以下android

 

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/");
        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開發問題還真多啊,還好哥機靈,找資料唄!web

終於找到問題了,app

只須要重寫activity的onKeyDown方法,在onKeyDown裏後退便可ide

public boolean onKeyDown(int keyCode ,KeyEvent keyEvent){
if(keyCode==keyEvent.KEYCODE_BACK){//監聽返回鍵,若是能夠後退就後退
if(webView.canGoBack()){
webView.goBack();
return true;
}
}
return super.onKeyDown(keyCode, keyEvent);

}this

 

所有代碼貼出,省得之後忘記url

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

}
}spa

相關文章
相關標籤/搜索