Use a DialogFragment
Description
A dialog fragment floats on top of an activity and is displayed modally.
To create a dialog fragment, you need to extend the DialogFragment base class.
Example
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.DialogInterface;
import android.os.Bundle;
/*from w w w . ja v a 2 s .c o m*/
public class Fragment1 extends DialogFragment {
static Fragment1 newInstance(String title) {
Fragment1 fragment = new Fragment1();
Bundle args = new Bundle();
args.putString("title", title);
fragment.setArguments(args);
return fragment;
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
String title = getArguments().getString("title");
return new AlertDialog.Builder(getActivity())
.setIcon(R.drawable.ic_launcher)
.setTitle(title)
.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton) {
((DialogFragmentExampleActivity)
getActivity()).doPositiveClick();
}
})
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton) {
((DialogFragmentExampleActivity)
getActivity()).doNegativeClick();
}
}).create();
}
}
Populate the MainActivity.java file as shown here:
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
/*w w w. java 2s . c om*/
public class MainActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Fragment1 dialogFragment = Fragment1.newInstance (
"Are you sure you want to do this?");
dialogFragment.show(getFragmentManager(), "dialog");
}
public void doPositiveClick() {
//---perform steps when user clicks on OK---
Log.d("DialogFragmentExample", "User clicks on OK");
}
public void doNegativeClick() {
//---perform steps when user clicks on Cancel---
Log.d("DialogFragmentExample", "User clicks on Cancel");
}
}