AlertDialog对话框
在Android程序中 ,我们可能用到,在一个界面中弹出一个dialog 提示一些信息或执行操作。 -一、Dialog:在官方文档中A dialog is a small window that prompts the user to make a decision or enter additional information. A dialog does not fill the screen and is normally used for modal events that require users to take an action before they can proceed. 一个对话框是一个小窗口,提示用户做出决定或输入额外的信息。对话框不填满屏幕,通常用于模态事件,要求用户采取行动才能进行。 DialogFragment:Note:Because the 注意:因为DialogFragment类最初添加与Android 3.0(API级别11),本文档描述了如何使用DialogFragment类提供的支持库。通过将这个库添加到您的应用程序,您可以使用DialogFragment和各种其他api的设备上运行Android 1.6或更高版本。如果最低版本应用程序支持API级别11或更高版本,那么您可以使用这个框架版本ofDialogFragment,但是请注意,本文档中的链接支持库的API。当使用支持库,确保您导入android.support.v4.app。DialogFragment类和notandroid.app.DialogFragment。 二、创建一个dialog的fragment You can accomplish a wide variety of dialog designs—including custom layouts and those described in theDialogsdesign guide—by extending 你能完成各种对话框designs-including theDialogs中描述的自定义布局和设计guide-by扩展DialogFragment和创建一个AlertDialog onCreateDialog()回调方法。
public class FireMissilesDialogFragmentextendsDialogFragment { @Override Dialog onCreateDialog(Bundle savedInstanceState) // Use the Builder class for convenient dialog construction AlertDialog.Builder builder =newBuilder(getActivity()); builder.setMessageR.stringdialog_fire_missiles setPositiveButtonfire,DialogInterfaceOnClickListener() void onClickDialogInterface dialogint id // FIRE ZE MISSILES! }})setNegativeButtoncancel // User cancelled the dialog}); // Create the AlertDialog object and return it return buildercreate(); }
三、alertdialog 组成:AlertDialog类允许您构建各种对话框的设计,往往是你唯一需要的对话框类。如图2所示,有三个地区的一个警告对话框
①区域1那里就是定义弹出框的头部信息,包括标题名或者是一个图标。 ②区域2那里是AlertDialog对话框的content部分,在这里我们可以设置一些message信息,或者是定义一组选择框,还可以定义我们自己的布局弹出框。 ③区域3那里使我们的Action Buttons部分,这里我们可以定义我们的操作按钮
// 1. Instantiate an with its constructor // 2. Chain together various setter methods to set the dialog characteristics builderdialog_message setTitledialog_title); // 3. Get the from AlertDialog dialog ();AlertDialog.BuilderAlertDialogcreate() 增加两个按钮:添加操作按钮一样在上图中,调用setPositiveButton()和setNegativeButton()方法
// Add the buttonsok // User clicked OK button // User cancelled the dialog // Set other dialog properties... // Create the AlertDialog(); 在alertdialog中 ,自定义的按钮都是setxxxButton()方法来完成的
1.setPositiveButton(CharSequence text,DialogInterface.OnClickListener listener) 这是一个相当于OK、确定操作的按钮, 2.setNegativeButton (CharSequence text,DialogInterface.OnClickListener listener) 这是一个相当于取消操作的按钮。 3. setNeutralButton (CharSequence text,DialogInterface.OnClickListener listener) 这个是相当于一个忽略操作的按钮。 我们每一种action buttons最多只能出现一个,即弹出对话框最多只能出现一个PositiveButton。 接下来我们通过一个一个的具体实例来看看我们常用的几种AlertDialog对话框。 .弹出一个警告框,并有三个按钮可选择
四、下拉列表弹出框:
button2.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this); builder.setIcon(R.drawable.ic_launcher); builder.setTitle("选择一个城市"); // 指定下拉列表的显示数据 final String[] cities = {"广州","上海","北京","香港","澳门"}; // 设置一个下拉的列表选择项 builder.setItems(cities,"选择的城市为:" + cities[which],Toast.LENGTH_SHORT).show(); } }); builder.show(); } });
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 If you choose to back your list with a 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 the
setMultiChoiceItems()
or
setSingleChoiceItems()
methods,respectively.
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 :
mSelectedItems ArrayList // Where we track the selected items // Set the dialog title builderpick_toppings // Specify the list array,the items to be selected by default (null for none),0)"> // and the listener through which to receive callbacks when items are selectedsetMultiChoiceItemsarraytoppingsnull OnMultiChoiceClickListener whichboolean isCheckedifisChecked // If the user checked the item,add it to the selected items mSelectedItemsaddwhichelsemSelectedItemscontains)) // Else,if the item is already in the array,remove it removeIntegervalueOf)); // Set the action buttons // User clicked OK,so save the mSelectedItems results somewhere // or return them to the component that opened the dialog }note: Although both a traditional list and a list with radio buttons provide a "single choice" action,you should use setSingleChoiceItems()
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.
六、.自定义弹出对话框
If you want a custom layout in a dialog,create a layout and add it to an By default,the custom layout fills the dialog window,but you can still use
dialog.xml
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" > <EditText android:id="@+id/username" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="username"/> <EditText android:id="@+id/password" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@id/username" android:hint="password" android:inputType="textPassword"/> </RelativeLayout>
我们看到,通过自定义弹出框,我们首先需要写一个xml的布局文件,然后在里面定义我们的布局,我们不需要在布局文件里定义Button按钮,可以通过 AlertDialog.Builder 来设置 action buttons。 通过 View view = LayoutInflater.from(MainActivity.this).inflate(R.layout.dialog,null); 我们可以将我们的布局文件加载进来,得到一个View对象,然后通过 AlertDialog.Builder 的setView方法来设置我们的自定义弹出框. Prompt User Input Dialog main.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <Button android:id="@+id/button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/button_label" /> <EditText android:id="@+id/editTextResult" android:layout_width="match_parent" android:inputType="text" android:layout_height="wrap_content" > </EditText> </LinearLayout> prompts.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/layout_root" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" android:padding="10dp" > <TextView android:id="@+id/textView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/tv_label" android:textAppearance="?android:attr/textAppearanceLarge" /> <EditText android:id="@+id/userInput" android:layout_width="match_parent" android:inputType="text" android:layout_height="wrap_content" > <requestFocus /> </EditText> </LinearLayout> MainActivity.class.
public class MainActivity extends Activity { private Button button; private EditText editTextMainScreen; final Context context = this; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); // components from main.xml button = (Button) findViewById(R.id.button); editTextMainScreen = (EditText) findViewById(R.id.editTextResult); button.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { // get prompts.xml view LayoutInflater layoutInflater = LayoutInflater.from(context); View promptView = layoutInflater.inflate(R.layout.prompts,null); AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context); // set prompts.xml to be the layout file of the alertdialog builder alertDialogBuilder.setView(promptView); final EditText input = (EditText) promptView.findViewById(R.id.userInput); // setup a dialog window alertDialogBuilder .setCancelable(false) .setPositiveButton("OK",new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog,int id) { // get user input and set it to result editTextMainScreen.setText(input.getText()); } }) .setNegativeButton("Cancel",int id) { dialog.cancel(); } }); // create an alert dialog AlertDialog alertD = alertDialogBuilder.create(); alertD.show(); } }); } } 官方文档:http://developer.android.com/guide/topics/ui/dialogs.html#AlertDialog android用户界面之PopupWindow教程实例汇总: http://www.apkbus.com/forum.php?mod=viewthread&tid=50999&extra=page%3D1&page=1 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |