i am creating a simple application using fragment activity.
it is running well. now, everytime i press the back button of my phone with the running application it is always terminating.
so i decide to add a custom dialog which will run as verification with "YES" or "NO" button if the user want to close the application.
my code::
MainActivity.java
//NOTE: I want to call the custom dialog at the backpressed event
@Override
public void onBackPressed() {
super.onBackPressed();
Fragment fragment = null;
fragment = new ConfirmClose();
}
close_dialog.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/layout_root"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:padding="10dp" >
<TextView
android:id="@+id/confirmToPrint"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:gravity="center"
android:text="@string/confirm_to_close" <!-- Do you really want to close? --->
android:textAppearance="?android:attr/textAppearanceLarge" />
</LinearLayout>
ConfirmClose.java
import android.app.AlertDialog;
import android.app.Fragment;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class ConfirmClose extends Fragment{
public ConfirmClose(){
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View promptView = inflater.inflate(R.layout.close_dialog, container);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(getActivity().getApplicationContext());
alertDialogBuilder.setView(promptView);
// setup a dialog window
alertDialogBuilder
.setCancelable(false)
.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {;
System.exit(0);
//this.finish();
}
})
.setNegativeButton("No",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
dialog.cancel();
}
});
// create an alert dialog
AlertDialog alertD = alertDialogBuilder.create();
alertD.show();
return promptView;
}
}
Now, nothings error, nothings problem, i assume that it will work but, when i pressed the back button of my phone with the running application,
nothings happen, it is just closing like normal close, the custom dialog is not showing. anyone can help me solve this?
thank you very much!
note: i am using my old android phone to test the application.