Skip to content

Instantly share code, notes, and snippets.

@antew
antew / LogoutDialogListener.java
Last active December 12, 2015 02:58
Alert Dialogs - Part 1 - Communicating with the Activity
/**
* Interface for Activities to implement to receive the result
*/
public interface LogoutDialogListener {
public void performLogout();
public void cancelLogout();
}
@antew
antew / LogoutDialogFragment.java
Last active December 12, 2015 02:58
Alert Dialogs - Part 1 - Communicating with the Activity #2
public class LogoutDialogFragment extends DialogFragment implements
OnClickListener {
// Used to communicate the result back to the Activity
private LogoutDialogListener listener;
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
if (activity instanceof LogoutDialogListener) {
listener = (LogoutDialogListener) activity;
} else {
throw new RuntimeException("The Activity must " +
"implement the LogoutDialogListener interface!");
}
}
@antew
antew / LogoutDialogFragment.java
Created February 10, 2013 06:18
No args constructor
public LogoutDialogFragment() {};
private static final String USERNAME = "Username";
...
public static LogoutDialogFragment newInstance(String username) {
LogoutDialogFragment fragment = new LogoutDialogFragment();
// Add the username to the bundle of arguments for the fragment
Bundle args = new Bundle();
args.putString(USERNAME, username);
fragment.setArguments(args);
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Get the username from the arguments, if one isn't passed
// we use a blank string so it still looks OK
String username = "";
if (getArguments().containsKey(USERNAME))
username = ", " + getArguments().getString(USERNAME);
// "Are you sure you want to log out, <username>?"
String message
@Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case DialogInterface.BUTTON_POSITIVE:
listener.performLogout();
break;
case DialogInterface.BUTTON_NEGATIVE:
listener.cancelLogout();
break;
@Override
public void performLogout() {
Toast.makeText(this,
"Received log out request!",
Toast.LENGTH_SHORT
).show();
}
@Override
Button logout = (Button) findViewById(R.id.logout);
logout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
LogoutDialogFragment logoutFragment = LogoutDialogFragment
.newInstance();
logoutFragment.show(getSupportFragmentManager(), "logout");
}
/**
* Interface for Activities to implement to receive the result (the
* username and password in this case)
*
*/
public interface LoginDialogListener {
void onFinishLoginDialog(String username, String password);
}