I've got 2 activities Activity A & Activity B (webview) What i'm trying to do is, when the webview can't go back anymore, it will display Activity A and on press again prompt for exit
Here is Activity A :
import com.jeumont.app.R;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.View;
public class frontpage extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.frontpage);
}
}
The webview which contains the backpress function :
public class webview extends Activity {
private WebView webView;
@SuppressLint("SetJavaScriptEnabled") @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Init Barre de chargement
final ProgressDialog pd = ProgressDialog.show(this, "", "Chargement en cours", true);
setContentView(R.layout.activity_webapp);
webView = (WebView) findViewById(R.id.webView_web_app);
webView.getSettings().setJavaScriptEnabled(true);
String url = getIntent().getStringExtra("url");
webView.loadUrl(url);
webView.setWebViewClient(new WebViewClient()
{
//On enleve le progress quand la page est chargée
public void onPageFinished(WebView view, String url)
{
pd.dismiss();
super.onPageFinished(view, url);
}
So i've tried several things to make this work.
public void onBackPressed (){
if (webView.isFocused() && webView.canGoBack()) {
webView.goBack();
}
super.onBackPressed();
works as expected, the webview goes back and when it can't anymore switch back to activity A and if you press again leaves the app
i'm actually using :
public void onBackPressed (){
if (webView.isFocused() && webView.canGoBack()) {
webView.goBack();
}
else
{
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Voulez vous quitter ?")
.setCancelable(false)
.setPositiveButton("Oui", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
finish();
}
})
.setNegativeButton("Non", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
}
the prompts works fine, but it pops out when the webview can't go back anymore, if yes pressed you go back to activity A
how can i make this prompt pop when the current activity is A and not the webview? i don't really know how to do this, i've heard about fragments, is that the way to do it ?
hope this is clear.
You should override onBackPressed() in both the activity.
In Activity A:
@Override
public void onBackPressed (){
//AlertDialog to exit the app.
}
In Activity B:
@Override
public void onBackPressed (){
if (webView.isFocused() && webView.canGoBack()) {
webView.goBack();
}else{
super.onBackPressed();
}
}