如何让后退按钮返回上一页/链接历史记录而不是关闭应用程序?
这是我的代码:
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK){
if(WebView.canGoBack()){
WebView.goBack();
return true;
}
}
return super.onKeyDown(keyCode, event);
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dsaif);
runDialog(5);
WebView engine = (WebView) findViewById(R.id.web_engine);
engine.loadUrl("http://android.dsaif.tk/store/");
engine.setWebViewClient( new HelloWebViewClient() );
}
private class HelloWebViewClient extends WebViewClient {
@Override
public boolean shouldOverrideUrlLoading( WebView view, String url ) {
return false;
}
}
对不起,我是Android开发的新手,对Java一无所知。请提供完整代码:)
答案 0 :(得分:1)
如Kostas所述,您在xml中创建一个按钮,然后在回调中调用webview.goBack();
的xml:
<Button
android:id="@+id/backBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Back />
活性:
Button backButton = (Button) findViewById(R.id.backBtn);
backButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
engine.goBack();
}
});
修改强>
如果有历史记录,这将使手机返回按钮返回历史记录。
public class someNameHere extends Activity{
private WebView engine;
@Override
public void onCreate(...){
...
engine = (WebView) findViewById(R.id.web_engine);
...
}
@Override
public boolean onKeyDown(...){
if((keyCode == KeyEvent.KEYCODE_BACK) && engine.canGoBack()){
engine.goBack();
return true;
}
...
}