Created
August 6, 2012 21:31
-
-
Save aleksi-niiranen/3278603 to your computer and use it in GitHub Desktop.
Android confirm dialog
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import android.support.v4.app.DialogFragment; | |
import android.support.v4.app.FragmentActivity; | |
// omitted irrelevant imports | |
public class MainActivity extends FragmentActivity { | |
private static final String TAG = "ConfirmDialogSample.MainActivity"; | |
private static final int DELETE_DIALOG = 0; | |
@Override | |
public void onCreate(Bundle savedInstanceState) { | |
super.onCreate(savedInstanceState); | |
setContentView(R.layout.activity_main); | |
Button deleteButton = (Button) findViewById(R.id.deleteDialog); | |
deleteButton.setOnClickListener(new View.OnClickListener() { | |
public void onClick(View v) { | |
createDialog(DELETE_DIALOG); | |
} | |
}); | |
} | |
private void createDialog(int dialog) { | |
DialogFragment newFragment = null; | |
switch (dialog) { | |
case DELETE_DIALOG: | |
newFragment = ConfirmDialogFragment.newInstance(R.string.alert_dialog_delete_title); | |
break; | |
} | |
newFragment.show(getSupportFragmentManager(), "dialog"); | |
} | |
public void doPositiveClick() { | |
Log.d(TAG, "clicked Yes"); | |
} | |
public void doNegativeClick() { | |
Log.d(TAG, "clicked No"); | |
} | |
public static class ConfirmDialogFragment extends DialogFragment { | |
public static ConfirmDialogFragment newInstance(int title) { | |
ConfirmDialogFragment frag = new ConfirmDialogFragment(); | |
Bundle args = new Bundle(); | |
args.putInt("title", title); | |
frag.setArguments(args); | |
return frag; | |
} | |
@Override | |
public Dialog onCreateDialog(Bundle savedInstanceState) { | |
int title = getArguments().getInt("title"); | |
return new AlertDialog.Builder(getActivity()) | |
.setIcon(R.drawable.ic_launcher) | |
.setTitle(title) | |
.setPositiveButton(R.string.alert_dialog_ok, new DialogInterface.OnClickListener() { | |
public void onClick(DialogInterface dialog, int which) { | |
((MainActivity) getActivity()).doPositiveClick(); | |
} | |
}) | |
.setNegativeButton(R.string.alert_dialog_cancel, new DialogInterface.OnClickListener() { | |
public void onClick(DialogInterface dialog, int which) { | |
((MainActivity) getActivity()).doNegativeClick(); | |
} | |
}) | |
.create(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment