建立Dialog的兩種方式:ui
1. 使用Dialog類或其子類,包括DialogFragmentthis
2. 在Activity中使用Dialog主題(theme)spa
下面是使用Dialog類的一個例子:code
// Create the new Dialog.
Dialog dialog = new Dialog(MyActivity.this); // Set the title. dialog.setTitle(「Dialog Title」); // Inflate the layout. dialog.setContentView(R.layout.dialog_view); // Update the Dialog’s contents.
TextView text = (TextView)dialog.findViewById(R.id.dialog_text_view);
text.setText(「This is the text in my dialog」); // Display the Dialog. dialog.show();
也能夠使用Dialog的子類,例如經常使用的AlertDialog:blog
Context context = MyActivity.this;
String title = 「It is Pitch Black」;
String message = 「You are likely to be eaten by a Grue.」;
String button1String = 「Go Back」;
String button2String = 「Move Forward」; AlertDialog.Builder ad = new AlertDialog.Builder(context);
ad.setTitle(title);ad.setMessage(message); ad.setPositiveButton(button1String, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int arg1) { eatenByGrue(); } }); ad.setNegativeButton(button2String, new DialogInterface.OnClickListener(){ public void onClick(DialogInterface dialog, int arg1) { //do nothing } });
還能夠設置是否顯示Cancel按鈕:生命週期
ad.setCancelable(true); ad.setOnCancelListener(new DialogInterface.OnCancelListener() { public void onCancel(DialogInterface dialog) {
eatenByGrue(); }
});
Android中提供了這些現成的Dialog供咱們使用:ci
1. CharacterPickerDialog it
2. DatePickerDialog class
3. TimePickerDialog date
4. ProgressDialog
Android中幾乎全部的可見部分均可以放到Fragment中,我認爲Fragment相對於View的一大優勢是能夠控制本身的生命週期。
public class MyDialogFragment extends DialogFragment { private static String CURRENT_TIME = 「CURRENT_TIME」; public static MyDialogFragment newInstance(String currentTime) { // Create a new Fragment instance with the specified parameters.
MyDialogFragment fragment = new MyDialogFragment(); Bundle args = new Bundle(); args.putString(CURRENT_TIME, currentTime); fragment.setArguments(args); return fragment; } }