Dialog是對話框的基類,在使用中應該避免直接實例化Dialog,可以用其子類AlertDialog。
官方規定使用 DialogFragment作爲Dialog的容器,好處在於,當屏幕旋轉或者用戶點擊返回鍵時,它可以幫助你管理生命週期,並且它可以根據屏幕尺寸大小和你的需要幫助你創建一個Dialog或者是一個全屏的Fragment。、
1.創建一個最簡單的 AlertDialog
標準的AlertDialog包含3個部分:
1.標題Title
2.內容Content area
3.動作按鈕Action buttons(Positive,Negative,Neutral)
public class AlertDialogFragment extends DialogFragment
implements DialogInterface.OnClickListener
{
public static AlertDialogFragment newInstance(String message)
{
AlertDialogFragment adf = new AlertDialogFragment();
Bundle bundle = new Bundle();
bundle.putString("alert-message", message);
adf.setArguments(bundle);
return adf;
}
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
this.setCancelable(true);
int style = DialogFragment.STYLE_NORMAL, theme = 0;
setStyle(style,theme);
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState)
{
AlertDialog.Builder b =
new AlertDialog.Builder(getActivity())
.setTitle("Alert!!")
.setPositiveButton("Ok", this)
.setNegativeButton("Cancel", this)
.setMessage(this.getArguments().getString("alert-message"));
return b.create();
}
public void onClick(DialogInterface dialog, int which)
{
}
}
顯示對話框:
FragmentTransaction ft =
getFragmentManager().beginTransaction();
AlertDialogFragment adf =
AlertDialogFragment.newInstance(
"Alert Message");
adf.show(ft, "ALERT_DIALOG_TAG");
2.創建列表Dialog
@Override
public Dialog onCreateDialog(Bundle savedInstanceState)
{
AlertDialog.Builder b =
new AlertDialog.Builder(getActivity())
.setTitle("Alert!!")
.setPositiveButton("Ok", this)
.setNegativeButton("Cancel", this)
.setItems(new String[] {"a", "b", "c"}, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(getActivity(), "點擊了第"+ (which+1) +"項", Toast.LENGTH_SHORT).show();
}
});
return b.create();
}
如果需要將動態數據作爲列表項,可以使用setAdapter (ListAdapter adapter, DialogInterface.OnClickListener listener)
3.創建單選/多選Dialog單選:
@Override
public Dialog onCreateDialog(Bundle savedInstanceState)
{
AlertDialog.Builder b =
new AlertDialog.Builder(getActivity())
.setTitle("Alert!!")
.setPositiveButton("Ok", this)
.setNegativeButton("Cancel", this)
.setSingleChoiceItems(new String[] {"a", "b", "c"}, -1, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
});
return b.create();
}
多選:
@Override
public Dialog onCreateDialog(Bundle savedInstanceState)
{
AlertDialog.Builder b =
new AlertDialog.Builder(getActivity())
.setTitle("Alert!!")
.setPositiveButton("Ok", this)
.setNegativeButton("Cancel", this)
.setMultiChoiceItems(new String[] {"a", "b", "c"}, null, new DialogInterface.OnMultiChoiceClickListener() {
@Override
public void onClick(DialogInterface dialog, int which,
boolean isChecked) {
}
});
return b.create();
}
4.自定義佈局的Dialog
需要在onCreateView中加載自定義佈局,再調用show顯示。
public class HelpDialogFragment extends DialogFragment implements
View.OnClickListener {
public static HelpDialogFragment newInstance(int helpResId) {
HelpDialogFragment hdf = new HelpDialogFragment();
Bundle bundle = new Bundle();
bundle.putInt("help_resource", helpResId);
hdf.setArguments(bundle);
return hdf;
}
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
this.setCancelable(true);
int style = DialogFragment.STYLE_NORMAL, theme = 0;
setStyle(style, theme);
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle icicle) {
View v = inflater.inflate(R.layout.help_dialog, container, false);
TextView tv = (TextView) v.findViewById(R.id.helpmessage);
tv.setText(getActivity().getResources().getText(
getArguments().getInt("help_resource")));
Button closeBtn = (Button) v.findViewById(R.id.btn_close);
closeBtn.setOnClickListener(this);
return v;
}
public void onClick(View v) {
dismiss();
}
}
佈局:help_dialog:
<?xml version="1.0" encoding="utf-8"?>
<!-- /res/layout/help_dialog.xml -->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:padding="4dip"
android:layout_width="match_parent" android:layout_height="match_parent">
<TextView
android:id="@+id/helpmessage"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:layout_marginLeft="20dip"
android:layout_marginRight="20dip"
android:text="Help Text"
android:layout_weight="1"
android:layout_gravity="center_vertical|center_horizontal"
android:textAppearance="?android:attr/textAppearanceMedium"
android:gravity="top|center_horizontal" />
<Button android:id="@+id/btn_close"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:layout_weight="0"
android:text="Close">
</Button>
</LinearLayout>
顯示:
FragmentTransaction ft =
getFragmentManager().beginTransaction();
HelpDialogFragment hdf =
HelpDialogFragment.newInstance(
R.string.help_text);
hdf.show(ft, "HELP_DIALOG_TAG");
5.對話框的關聯
可以通過Fragment的回退棧設置2個前後關聯的Dialog:第一個Dialog點擊按鈕打開第二個Dialog,第二個Dialog按返回鍵重新顯示第一個Dialog,這種邏輯在屏幕旋轉時依然有效。
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.remove(this);
//加入回退棧
ft.addToBackStack(null);
HelpDialogFragment hdf =
HelpDialogFragment.newInstance(R.string.help1);
hdf.show(ft, MainActivity.HELP_DIALOG_TAG);
以上代碼寫在一個DIalog的Button中,點擊Button,顯示上面的HelpDialogFragment,再按返回鍵,退出HelpDialogFragment,顯示剛纔的Dialog。6.對話框回調。
如果希望在點擊Dialog後通知創建它的activity或者 fragment ,一種方法是直接在OnclickListener裏面寫邏輯,更通用的方法是,在DialogFragment內定義一個接口,爲每個按鈕的點擊事件設置回調方法。這樣一來,所有實現接口的activity或者 fragment都能在回調方法中處理按鈕邏輯。
DialogFragment:
public class AlertDialogFragment extends DialogFragment {
private NoticeDialogListener mListener;
public interface NoticeDialogListener {
public void onDialogPositiveClick(DialogFragment dialog);
public void onDialogNegativeClick(DialogFragment dialog);
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setCancelable(true);
int style = DialogFragment.STYLE_NORMAL, theme = 0;
setStyle(style, theme);
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
if (activity instanceof NoticeDialogListener) {
mListener = (NoticeDialogListener) activity;
}
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setPositiveButton("ok", new DialogInterface.OnClickListener(){
@Override
public void onClick(DialogInterface dialog, int which) {
if (mListener != null) {
mListener.onDialogPositiveClick(AlertDialogFragment.this);
}
}
}).setNegativeButton("cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
mListener.onDialogNegativeClick(AlertDialogFragment.this);
}
});;
return builder.create();
}
}
Activity:
public class MainActivity extends Activity implements NoticeDialogListener
{
……
private void testAlertDialog()
{
FragmentTransaction ft =
getFragmentManager().beginTransaction();
AlertDialogFragment adf = new AlertDialogFragment();
adf.show(ft, ALERT_DIALOG_TAG);
}
@Override
public void onDialogPositiveClick(DialogFragment dialog) {
Toast.makeText(this, "點擊了ok按鈕", Toast.LENGTH_SHORT).show();
}
@Override
public void onDialogNegativeClick(DialogFragment dialog) {
Toast.makeText(this, "點擊了cancel按鈕", Toast.LENGTH_SHORT).show();
}
……
}
這是使用了設計模式中的觀察者模式
7.onCancel,onDismiss
以下情況會調用DialogFragment的onCancel回調方法:
Dialog顯示時,按返回鍵,回調方法調用過程:
onCancel-》onDismiss-》onDestroy
除了以上情況,以下情況會調用DialogFragment的onDismiss回調方法:
旋轉屏幕,回調方法調用過程:onDestroy-》onDismiss
注:橫豎屏切換時,DialogFragment會處理Dialog的生命週期,使其仍然顯示在前臺。