Created
April 27, 2014 13:03
-
-
Save yaraki/11345093 to your computer and use it in GitHub Desktop.
How to create a dialog using DialogFragment and AlertDialog.
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
package yaraki.dialogdemo.app; | |
import android.app.AlertDialog; | |
import android.app.Dialog; | |
import android.content.DialogInterface; | |
import android.support.v4.app.DialogFragment; | |
import android.support.v4.app.Fragment; | |
import android.support.v7.app.ActionBarActivity; | |
import android.os.Bundle; | |
import android.view.LayoutInflater; | |
import android.view.Menu; | |
import android.view.MenuItem; | |
import android.view.View; | |
import android.view.ViewGroup; | |
import android.widget.Toast; | |
public class DialogDemoActivity extends ActionBarActivity { | |
@Override | |
protected void onCreate(Bundle savedInstanceState) { | |
super.onCreate(savedInstanceState); | |
setContentView(R.layout.activity_main); | |
if (null == savedInstanceState) { | |
getSupportFragmentManager().beginTransaction() | |
.replace(R.id.container, new MainFragment()) | |
.commit(); | |
} | |
} | |
public static class MainFragment extends Fragment implements View.OnClickListener { | |
private static final String FRAGMENT_YES_NO_DIALOG = "dialog"; | |
@Override | |
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { | |
return inflater.inflate(R.layout.fragment_main, container, false); | |
} | |
@Override | |
public void onViewCreated(View view, Bundle savedInstanceState) { | |
view.findViewById(R.id.show_dialog).setOnClickListener(this); | |
} | |
@Override | |
public void onClick(View view) { | |
switch (view.getId()) { | |
case R.id.show_dialog: { | |
new YesNoDialogFragment().show(getFragmentManager(), FRAGMENT_YES_NO_DIALOG); | |
break; | |
} | |
} | |
} | |
} | |
public static class YesNoDialogFragment extends DialogFragment implements DialogInterface.OnClickListener { | |
@Override | |
public Dialog onCreateDialog(Bundle savedInstanceState) { | |
return new AlertDialog.Builder(getActivity()) | |
.setMessage("Feeling lucky?") | |
.setPositiveButton("Yes", this) | |
.setNegativeButton("No", this) | |
.create(); | |
} | |
@Override | |
public void onClick(DialogInterface dialogInterface, int which) { | |
switch (which) { | |
case DialogInterface.BUTTON_POSITIVE: { | |
Toast.makeText(getActivity(), "Great!", Toast.LENGTH_SHORT).show(); | |
break; | |
} | |
case DialogInterface.BUTTON_NEGATIVE: { | |
Toast.makeText(getActivity(), "Maybe next time...", Toast.LENGTH_SHORT).show(); | |
break; | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment