我有一个活动,其中有一个webview。当webview转到几页并且我点击设备上的后退按钮运行正常,但如果我单击操作栏中的后退按钮然后返回错误。 我可以在操作栏中设置功能返回按钮,如设备中的后退按钮吗?
这是我的代码:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tes_backbutton);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
view = (WebView)findViewById(R.id.wv_tes);
progressBar = (ProgressBar)findViewById(R.id.prgbarhome);
view.setWebViewClient(new WebViewClient());
view.loadUrl(URL);
view.setWebChromeClient(new WebChromeClient() {
@Override
public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
//Required functionality here
return super.onJsAlert(view, url, message, result);
}
});
view.setWebViewClient(new WebViewClient() {
ProgressDialog progressDialog;
//Show loader on url load
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
if (progressDialog == null) {
// in standard case YourActivity.this
progressDialog = new ProgressDialog(tes_backbutton.this);
progressDialog.setMessage("Loading...");
progressDialog.show();
}
}
public void onPageFinished(WebView view, String url) {
try {
progressDialog.dismiss();
progressDialog = null;
} catch (Exception exception) {
exception.printStackTrace();
}
}
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
Intent myIntent = new Intent(tes_backbutton.this, main_noconnect.class);
tes_backbutton.this.startActivity(myIntent);
}
});
view.canGoBack();
view.setOnKeyListener(new View.OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK
&& event.getAction() == MotionEvent.ACTION_UP
&& view.canGoBack()) {
view.goBack();
return true;
}
return false;
}
});
}
@Override
public boolean onSupportNavigateUp() {
onBackPressed();
return true;
}
答案 0 :(得分:0)
如果您想在操作栏中点击后退箭头后执行任何操作,则需要覆盖onOptionsItemSelected
方法
@Override
public boolean onOptionsItemSelected(MenuItem menuItem) {
switch (menuItem.getItemId()) {
case android.R.id.home:
onBackPressed(); //finishes the activity
return true;
}
return super.onOptionsItemSelected(menuItem);
}
答案 1 :(得分:0)
操作栏中的“后退”按钮应与设备的后退按钮不同。你不希望他们两个都做同样的事情。操作栏中的按钮应该用作“向上”按钮而不是“后退”按钮。请详细了解Providing Up Navigation。
我希望这会对你有所帮助。
答案 2 :(得分:0)
你可以使用onBackPressed();方法
答案 3 :(得分:0)
@覆盖 public boolean onOptionsItemSelected(MenuItem menuItem){
switch (menuItem.getItemId()) {
case android.R.id.home:
if(mWebView.canGoBack() == true){
mWebView.goBack();
}else{
onBackPressed(); //finishes the activity
}
return true;
}
return super.onOptionsItemSelected(menuItem);
}
答案 4 :(得分:0)
you can use webview.cangoback() method for navigating between different web pages in webview
@Override
public boolean onOptionsItemSelected(MenuItem menuItem) {
switch (menuItem.getItemId()) {
case android.R.id.home:
if(view.cangoback()){
view.goback();
}
else{
finish();
}
break;
}
return super.onOptionsItemSelected(menuItem);
}