AlertDialog对话框

前端之家收集整理的这篇文章主要介绍了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 theDialogFragmentclass was originally added with Android 3.0 (API level 11),this document describes how to use theclass that's provided with theSupport Library. By adding this library to your app,you can useand a variety of other APIs on devices running Android 1.6 or higher. If the minimum version your app supports is API level 11 or higher,then you can use the framework version of,but be aware that the links in this document are for the support library APIs. When using the support library,be sure that you importandroid.support.v4.app.DialogFragmentclass andnotandroid.app.DialogFragment.

注意:因为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 the@L_404_2@design guide—by extendingand creating a@L_404_3@in theonCreateDialog()callback method.

你能完成各种对话框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对话框。

.弹出一个警告框,并有三个按钮可选择


button.setOnClickListener(new OnClickListener()

{ @Override public void onClick(View v) { // 通过AlertDialog.Builder这个类来实例化我们的一个AlertDialog的对象 AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this); // 设置Title的图标 builder.setIcon(R.drawable.ic_launcher); // 设置Title的内容 builder.setTitle("弹出警告框"); // 设置Content来显示一个信息 builder.setMessage("确定删除吗?"); // 设置一个PositiveButton builder.setPositiveButton("确定",new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog,int which) { Toast.makeText(MainActivity.this,"positive: " + which,Toast.LENGTH_SHORT).show(); } }); // 设置一个NegativeButton builder.setNegativeButton("取消","negative: " + which,Toast.LENGTH_SHORT).show(); } }); // 设置一个NeutralButton builder.setNeutralButton("忽略","neutral: " + which,Toast.LENGTH_SHORT).show(); } }); // 显示出该对话框 builder.show(); } });


四、下拉列表弹出框:


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 withsetTitle(). To specify the items for the list,callsetItems()setAdapter(). This allows you to back the list with dynamic data (such as from a database) using aListAdapter.

If you choose to back your list with aLoaderso that the content loads asynchronously. This is described further inBuilding Layouts with an Adapterand theLoadersguide.

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 anArrayList:



  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 anAlertDialogby callingsetView()on yourAlertDialog.Builderobject.

By default,the custom layout fills the dialog window,but you can still useAlertDialog.Buildermethods to add buttons and a title.


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>

button5.setOnClickListener(new OnClickListener()

{ @Override public void onClick(View v) { AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this); builder.setIcon(R.drawable.ic_launcher); builder.setTitle("请输入用户名和密码"); // 通过LayoutInflater来加载一个xml的布局文件作为一个View对象 View view = LayoutInflater.from(MainActivity.this).inflate(R.layout.dialog,null); // 设置我们自己定义的布局文件作为弹出框的Content builder.setView(view); final EditText username = (EditText)view.findViewById(R.id.username); final EditText password = (EditText)view.findViewById(R.id.password); builder.setPositiveButton("确定",int which) { String a = username.getText().toString().trim(); String b = password.getText().toString().trim(); // 将输入的用户名和密码打印出来 Toast.makeText(MainActivity.this,"用户名: " + a + ",密码: " + b,Toast.LENGTH_SHORT).show(); } }); builder.setNegativeButton("取消",int which) { } }); builder.show(); } });


我们看到,通过自定义弹出框,我们首先需要写一个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

猜你在找的XML相关文章