您的位置:首页 > 移动开发 > Android开发

Android Dialog I-创建一个dialog

2015-12-10 19:07 627 查看

概述:

Dialog是一个让用户做出选择或者填写信息的小窗口, 通常dialog都不会占据整个屏幕, 但是需要用户必须做出选择. 关于如何设计Dialog, 可以参考这里.



Dialog类是dialog的基类, 但是我们应该避免直接使用这个类, 官方推荐我们使用以下两个子类:

AlertDialog: 一个Dialog, 可以设置title, 最多可以设置3个按键, 一个可以选择的列表, 或者一个用户自定义的layout.

DatePickerDialog或者TimePickerDialog:一个自带UI的可以选择时间或者日期的对话框.

这些子类为dialog定义了样式和结构, 但是我们应该使用DialogFragment作为dialog的容器. DialogFragment类提供了所有我们需要的创建和管理dialog行为的接口. 使用DialogFragment可以确保我们的dialog可以正确的处理生命周期事件, 比如用户点击了返回键或者旋转了屏幕等. DialogFragment还可以让我们方便的重用dialog的UI, 就好像一个普通的Fragment那样.

该文档中的DialogFragment都是android.support.v4.app.DialogFragment, 而不是android.app.DialogFragment.

 

创建一个DialogFragment:

通过DialogFragment我们可以创建多种dialog, 比如这是一个DialogFragment管理的AlertDialog:

public
class FireMissilesDialogFragment
extends DialogFragment
{

    @Override

    public Dialog onCreateDialog(Bundle savedInstanceState)
{

        // Use the Builder class for convenient dialog construction

        AlertDialog.Builder builder
= new
AlertDialog.Builder(getActivity());

        builder.setMessage(R.string.dialog_fire_missiles)

               .setPositiveButton(R.string.fire,
new DialogInterface.OnClickListener()
{

                   public
void onClick(DialogInterface dialog,
int id)
{

                      // FIRE ZEMISSILES!

                   }

               })

               .setNegativeButton(R.string.cancel,
new DialogInterface.OnClickListener()
{

                   public
void onClick(DialogInterface dialog,
int id)
{

                      // Usercancelled the dialog

                   }

               });

        // Create the AlertDialog object and return it

        return builder.create();

    }
}



包含一个message和两个button的dialog. 当我们创建这样的一个类的实例并且调用show()方法的时候, 就会显示出这样的一个dialog.

根据我们的dialog的复杂程度, 我们可以实现DialogFragment的其它回调方法.

 

创建一个AlertDialog:

通过AlertDialog我们可以创建多种dialog, 它如此牛X以至于很可能使我们唯一需要的dialog类. 如下图, 一个alert dialog中有三个区域:



1.      Title: 该项是可选的, 应该在区域2被详细信息占据的时候使用.如果我们仅仅需要一个简单的消息或者提一个问题, 则不应该使用title.

2.      Content area: 用于显示一条信息, 一个列表或者自定义的layout.

3.      Action buttons: 按钮, 一个dialog中不应该超过3个按钮.

AlertDialog.Builder类为我们提供了可以设置上述三项的API, 还包括一个layout, 栗子:

// 1. Instantiate an AlertDialog.Builder
with its constructor

AlertDialog.Builder builder
= new
AlertDialog.Builder(getActivity());

// 2. Chaintogether various setter methods to set the dialog characteristics

builder.setMessage(R.string.dialog_message)

       .setTitle(R.string.dialog_title);

// 3. Get the AlertDialog from
create()
AlertDialog dialog
= builder.create();

如何增加一个button:

想要增加button的话, 我们需要使用setPositiveButton()和setNegativeButton()方法: 

AlertDialog.Builder builder
= new
AlertDialog.Builder(getActivity());
// Add thebuttons

builder.setPositiveButton(R.string.ok,
new DialogInterface.OnClickListener()
{

           public
void onClick(DialogInterface dialog,
int id)
{

               // User clicked OK button

           }

       });

builder.setNegativeButton(R.string.cancel,
new DialogInterface.OnClickListener()
{

           public
void onClick(DialogInterface dialog,
int id)
{

               // User cancelled the dialog

           }

       });
// Set otherdialog properties
...

// Create theAlertDialog
AlertDialog dialog
= builder.create();

set…Button()方法需要一个指定title的参数和一个DialogInterface.OnClickListener以监听按键事件. 我们可以为dialog增加三种button:

Positive: 应该使用这个表示”接受”和”继续”操作, 就是肯定的意思.

Negative: 表示取消操作.

Neutral: “中性的”, 既不是肯定也不是否定的时候使用, 比如”稍后提醒”这种功能.

上述每种button我们在一个dialog中只能加一个, 比如不能同时出现两个Positive按钮.

如何增加一个list:

这是一个包含title和list的dialog:



我们可以在AlertDialog中使用3种list:

典型的单选list(如上图).

持久性单项选择列表(就是radio button).

持久性多项选择列表(就是checkbox).

如果想要创建如上图的单选list, 要使用setItems()方法:

@Override
public Dialog onCreateDialog(Bundle savedInstanceState)
{

    AlertDialog.Builder builder
= new
AlertDialog.Builder(getActivity());

    builder.setTitle(R.string.pick_color)

           .setItems(R.array.colors_array,
new DialogInterface.OnClickListener()
{

               public
void onClick(DialogInterface dialog,
int which)
{

               // The 'which' argument contains the indexposition

               // of the selected item

           }

    });

    return builder.create();
}

因为dialog中的list占用了content area, 所以我们不能一起使用message和list, 这时候我们应该使用title来做说明, 设置title使用方法setTitle(). 指定list则需要使用setItem()并且传入一个数组作为参数. 另外如果我们需要动态指定一个list, 那么需要使用setAdapter()方法设置一个ListAdapter. 默认情况下, 点击一个list中的条目会使dialog消失, 如果不想这样的情况发生, 则应该使用持久化单项选择列表.

为AlertDialog指定一个持久化的多选或者单选list:



上图是一个带有多选list的AlertDialog. 想要增加这样的一个多选list或者单选list, 我们需要使用setMultiChoiceItems()或者setSingleChoiceItems()方法. 比如这是上图中多选list的代码:

@Override
public Dialog onCreateDialog(Bundle savedInstanceState)
{

    mSelectedItems =
new ArrayList();  // Where we track the selected items

    AlertDialog.Builder builder
= new
AlertDialog.Builder(getActivity());

    // Set thedialog title

    builder.setTitle(R.string.pick_toppings)

    // Specify thelist array, the items to be selected by default (null for none),

    // and thelistener through which to receive callbacks when items are selected

           .setMultiChoiceItems(R.array.toppings,
null,

                      new
DialogInterface.OnMultiChoiceClickListener()
{

               @Override

               public
void onClick(DialogInterface dialog,
int which,

                      boolean isChecked)
{

                   if
(isChecked)
{

                      // If the userchecked the item, add it to the selected items

                      mSelectedItems.add(which);

                   }
else if (mSelectedItems.contains(which))
{

                      // Else, if theitem is already in the array, remove it

                      mSelectedItems.remove(Integer.valueOf(which));

                   }

               }

           })

    // Set theaction buttons

           .setPositiveButton(R.string.ok,
new DialogInterface.OnClickListener()
{

               @Override

               public
void onClick(DialogInterface dialog,
int id)
{

                   // User clicked OK, so save themSelectedItems results somewhere

                   // or return them to the component thatopened the dialog

                   ...

               }

           })

           .setNegativeButton(R.string.cancel,
new DialogInterface.OnClickListener()
{

               @Override

               public
void onClick(DialogInterface dialog,
int id)
{

                   ...

               }

           });

    return builder.create();
}

如果想要用户再次打开dialog的时候还能看到上次的选择, 那么我们应该使用持久化单项选择列表.

创建一个自定义的layout:



如果我们想让dialog显示我们自定义的layout, 那么就得自定义一个layout然后将其加入到AlertDialog中,  通过AlertDialog的setView()方法就可以做到这一点. 默认情况下自定义的layout会填满整个dialog窗口, 但是我们还是可以通过AlertDialog.Builder向其添加按钮和主题. 这是实现上图效果的layout的代码:

<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"

    android:orie
cab5
ntation="vertical"

    android:layout_width="wrap_content"

    android:layout_height="wrap_content">

    <ImageView

        android:src="@drawable/header_logo"

        android:layout_width="match_parent"

        android:layout_height="64dp"

        android:scaleType="center"

        android:background="#FFFFBB33"

        android:contentDescription="@string/app_name"
/>

    <EditText

        android:id="@+id/username"

        android:inputType="textEmailAddress"

        android:layout_width="match_parent"

        android:layout_height="wrap_content"

        android:layout_marginTop="16dp"

        android:layout_marginLeft="4dp"

        android:layout_marginRight="4dp"

        android:layout_marginBottom="4dp"

        android:hint="@string/username"
/>

    <EditText

        android:id="@+id/password"

        android:inputType="textPassword"

        android:layout_width="match_parent"

        android:layout_height="wrap_content"

        android:layout_marginTop="4dp"

        android:layout_marginLeft="4dp"

        android:layout_marginRight="4dp"

        android:layout_marginBottom="16dp"

        android:fontFamily="sans-serif"

        android:hint="@string/password"/>
</LinearLayout>

为了在DialogFragment中加载layout, 需要通过getLayoutInflater()方法获取LayoutInflater, 然后调用inflate()方法, 该方法的第一个参数是layout的资源ID, 第二个参数是layout的父View. 然后通过setView()将layout放入dialog.

@Override
public Dialog onCreateDialog(Bundle savedInstanceState)
{

    AlertDialog.Builder builder
= new
AlertDialog.Builder(getActivity());

    // Get thelayout inflater

    LayoutInflater inflater
= getActivity().getLayoutInflater();

    // Inflate andset the layout for the dialog

    // Pass null asthe parent view because its going in the dialog layout

    builder.setView(inflater.inflate(R.layout.dialog_signin,
null))

    // Add actionbuttons

           .setPositiveButton(R.string.signin,
new DialogInterface.OnClickListener()
{

               @Override

               public
void onClick(DialogInterface dialog,
int id)
{

                   // sign in the user ...

               }

           })

           .setNegativeButton(R.string.cancel,
new DialogInterface.OnClickListener()
{

               public
void onClick(DialogInterface dialog,
int id)
{

                   LoginDialogFragment.this.getDialog().cancel();

               }

           });      

    return builder.create();
}

如果我们想要自定义一个dialog, 我们可以使用Activity作为dialog而不使用Dialog类, 使用方法也很简单只需要将activity的主题设置为Theme.Hologram.Dialog即可, 栗子:

<activity
android:theme="@android:style/Theme.Holo.Dialog"
>

这样设置之后Activity就不会再全屏显示, 而是变成了一个dialog.

 

参考:  http://developer.android.com/guide/topics/ui/dialogs.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  android dialog alertdialog