本节内容

1. Building an Alert Dialog

2. Adding buttons

3. Adding a list

4. Adding a persistent multiple-choice or single-choice list

5. Creating a Custom Layout

Building an Alert Dialog


The AlertDialog class allows you to build a variety of dialog designs and is often the only dialog class you'll need. As shown in figure 2, there are three regions of an alert dialog:

Figure 2. The layout of a dialog.

  1. Title

    This is optional and should be used only when the content area is occupied by a detailed message, a list, or custom layout. If you need to state a simple message or question (such as the dialog in figure 1), you don't need a title.

  2. Content area

    This can display a message, a list, or other custom layout.

  3. Action buttons

    There should be no more than three action buttons in a dialog.

The AlertDialog.Builder class provides APIs that allow you to create an AlertDialog with these kinds of content, including a custom layout.

To build an AlertDialog:

// 1. Instantiate an AlertDialog.Builder with its constructor
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); // 2. Chain together 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();

The following topics show how to define various dialog attributes using the AlertDialog.Builder class.

Adding buttons

To add action buttons like those in figure 2, call the setPositiveButton() and setNegativeButton()methods:

AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
// Add the buttons
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 other dialog properties
... // Create the AlertDialog
AlertDialog dialog = builder.create();

The set...Button() methods require a title for the button (supplied by a string resource) and aDialogInterface.OnClickListener that defines the action to take when the user presses the button.

There are three different action buttons you can add:

Positive
You should use this to accept and continue with the action (the "OK" action).
Negative
You should use this to cancel the action.
Neutral
You should use this when the user may not want to proceed with the action, but doesn't necessarily want to cancel. It appears between the positive and negative buttons. For example, the action might be "Remind me later."

You can add only one of each button type to an AlertDialog. That is, you cannot have more than one "positive" button.

 

Adding a list

There are three kinds of lists available with theAlertDialog APIs:

  • A traditional single-choice list
  • A persistent single-choice list (radio buttons)
  • A persistent multiple-choice list (checkboxes)

Figure 3. A dialog with a title and list.

To create a single-choice list like the one in figure 3, use the setItems() method:

@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 index position
// of the selected item
}
});
return builder.create();
}

Because the list appears in the dialog's content area, the dialog cannot show both a message and a list and you should set a title for the dialog with setTitle(). To specify the items for the list, call setItems(), passing an array. Alternatively, you can specify a list using setAdapter(). This allows you to back the list with dynamic data (such as from a database) using a ListAdapter.

If you choose to back your list with a ListAdapter, always use a Loader so that the content loads asynchronously. This is described further in Building Layouts with an Adapter and the Loaders guide.

Note: By default, touching a list item dismisses the dialog, unless you're using one of the following persistent choice lists.

 

Adding a persistent multiple-choice or single-choice list

To add a list of multiple-choice items (checkboxes) or single-choice items (radio buttons), use thesetMultiChoiceItems() orsetSingleChoiceItems() methods, respectively.

Figure 4. A list of multiple-choice items.

For example, here's how you can create a multiple-choice list like the one shown in figure 4 that saves the selected items in an ArrayList:

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
mSelectedItems = new ArrayList(); // Where we track the selected items
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
// Set the dialog title
builder.setTitle(R.string.pick_toppings)
// Specify the list array, the items to be selected by default (null for none),
// and the listener 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 user checked the item, add it to the selected items
mSelectedItems.add(which);
} else if (mSelectedItems.contains(which)) {
// Else, if the item is already in the array, remove it
mSelectedItems.remove(Integer.valueOf(which));
}
}
})
// Set the action buttons
.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
// User clicked OK, so save the mSelectedItems results somewhere
// or return them to the component that opened the dialog
...
}
})
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
...
}
}); return builder.create();
}

Although both a traditional list and a list with radio buttons provide a "single choice" action, you should usesetSingleChoiceItems() if you want to persist the user's choice. That is, if opening the dialog again later should indicate what the user's current choice is, then you create a list with radio buttons.

Creating a Custom Layout

Figure 5. A custom dialog layout.

If you want a custom layout in a dialog, create a layout and add it to an AlertDialog by calling setView() on your AlertDialog.Builder object.

By default, the custom layout fills the dialog window, but you can still use AlertDialog.Builder methods to add buttons and a title.

For example, here's the layout file for the dialog in Figure 5:

res/layout/dialog_signin.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="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>

Tip: By default, when you set an EditText element to use the "textPassword" input type, the font family is set to monospace, so you should change its font family to "sans-serif" so that both text fields use a matching font style.

To inflate the layout in your DialogFragment, get a LayoutInflater with getLayoutInflater() and callinflate(), where the first parameter is the layout resource ID and the second parameter is a parent view for the layout. You can then call setView() to place the layout in the dialog.

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
// Get the layout inflater
LayoutInflater inflater = getActivity().getLayoutInflater(); // Inflate and set the layout for the dialog
// Pass null as the parent view because its going in the dialog layout
builder.setView(inflater.inflate(R.layout.dialog_signin, null))
// Add action buttons
.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();
}

Tip: If you want a custom dialog, you can instead display an Activity as a dialog instead of using the DialogAPIs. Simply create an activity and set its theme to Theme.Holo.Dialog in the <activity> manifest element:

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

That's it. The activity now displays in a dialog window instead of fullscreen.

Android Dialogs(3)警示Dialog教程[创建,单选,复选,自定义]等等的更多相关文章

  1. 【三石jQuery视频教程】02.创建 FontAwesome 复选框和单选框

    视频地址:http://v.qq.com/page/m/8/c/m0150izlt8c.html 大家好,欢迎来到[三石jQuery视频教程],我是您的老朋友 - 三生石上. 今天,我们要通过基本的H ...

  2. 个人永久性免费-Excel催化剂功能第58波-批量生成单选复选框

    插件的最大威力莫过于可以把简单重复的事情批量完全,对日常数据采集或打印报表排版过程中,弄个单选.复选框和用户交互,美观的同时,也能保证到数据采集的准确性,一般来说用原生的方式插入单选.复选框,操作繁琐 ...

  3. [SAP ABAP开发技术总结]选择屏幕——按钮、单选复选框

    声明:原创作品,转载时请注明文章来自SAP师太技术博客( 博/客/园www.cnblogs.com):www.cnblogs.com/jiangzhengjun,并以超链接形式标明文章原始出处,否则将 ...

  4. 雷林鹏分享:jQuery EasyUI 树形菜单 - 创建带复选框的树形菜单

    jQuery EasyUI 树形菜单 - 创建带复选框的树形菜单 easyui 的树(Tree)插件允许您创建一个复选框树.如果您点击一个节点的复选框,这个点击的节点信息将向上和向下继承.例如:点击 ...

  5. 微信小程序 修改(自定义) 单选/复选按钮样式 checkbox/radio样式自定义

    参考文章: 微信小程序 修改(自定义) 单选/复选按钮样式 checkbox/radio样式自定义

  6. SpinnerViewPop【PopWindow样式(单选)、Dialog样式(单选+多选)的下拉菜单】

    版权声明:本文为HaiyuKing原创文章,转载请注明出处! 前言 对下拉菜单的文本区域和列表区域进行了封装.包括两种展现方式:popwindow(单选).dialog(单选+多选) 因为该封装需要在 ...

  7. Asp.net自定义单选复选框控件

    将常用的jquery插件封装成控件也是个不错的选择 下面是效果的简单颜色,由于博客系统的限制没法完整演示最终效果,请下载示例查看 Asp.netWeb APIC#Javascript   1.新建类库 ...

  8. 单选复选按钮以及Toast学习笔记

    1:单选按钮是以组的形式呈现,xml布局文件中需要定义一个RadioGroup,然后在这个组内再定义RadioButton.在java代码中为该按钮添加监听时,需要用组名来引用对应的方法setOnCh ...

  9. jQuery 与js判断是否单选复选选中

    js判断复选:这段代码昨天网上查看的资料没保存出处,抱歉 var obj=document.getElementsByName("diseaseSet"); //选择所有name= ...

随机推荐

  1. elasticsarch5.4集群安装

    越来越多的企业已经采用ELK解决方案来对其公司产生的日志进行分析,笔者最近着手在生产环境部署自己的ELK stack,本文介绍ELK中elasticsearch5.2集群的实现. 一.环境准备 1.系 ...

  2. Material UI:很强大的CSS框架

    Material UI 是一款功能很强大,界面却十分清新简洁的CSS框架.Material UI利用了Google的Material Design 全新设计语言.而且让每个UI组件都变得很独立.因此开 ...

  3. ASP.NET没有魔法——ASP.NET MVC Razor与View渲染 ASP.NET没有魔法——ASP.NET MVC界面美化及使用Bundle完成静态资源管理

    ASP.NET没有魔法——ASP.NET MVC Razor与View渲染   对于Web应用来说,它的界面是由浏览器根据HTML代码及其引用的相关资源进行渲染后展示给用户的结果,换句话说Web应用的 ...

  4. HDU 2896 病毒侵袭 (AC自己主动机)

    pid=2896">http://acm.hdu.edu.cn/showproblem.php?pid=2896 病毒侵袭 Time Limit: 2000/1000 MS (Java ...

  5. MyEclipse搭建SSH(Struts2+Spring2+Hibernate3)框架项目教程

    对Struts.spring.hibernate大体上了解一遍后,就是针对这个几个框架的整合了. 怎样整合,请看以下: 第一:Struts2的jar和xml配置文件: jar包: commons-fi ...

  6. C++语言笔记系列之二十——模版

    1.随意输入两个数x和y,输出最大值max. int max(int x, int y) {return x>y? x:y;} 2.函数模版 (1)用一种或者多种通用类型去表示函数--函数模版. ...

  7. 李洪强iOS开发之录音和播放实现

    李洪强iOS开发之录音和播放实现 //首先导入框架后,导入头文件.以下内容为托控件,在storyboard中拖出两个按钮为录音和播放按钮 //创建一个UIViewController在.h文件中写 # ...

  8. 6 JobApp默认视图开发

    第一步:引入angularjs 添加app模块 现在我们正式进入开发,下面是我们在上一节建立的目录结构: 我们需要再src路径下,新建index.html文件,先引入angularjs文件: < ...

  9. url加密并计算时间

    将URL地址参数进行加密传输提高网站安全性 加密算法,直接调用就好 function keyED($txt,$encrypt_key){ $encrypt_key = md5($encrypt_key ...

  10. 2016/05/05 smarty ① 登录 ②主页面 ③删除 ④让缩略信息显示完整 (补:增加 修改 )

    共  八个页面 ①login.php <?php include("init.inc.php"); $smarty->display("login.html& ...