android开发步步为营之33:玩转对话框AlertDialog

        开发的时候,我们经常的使用js的alert弹出提示框,android里面也有AlertDialog,当然它的功能可比js的强大多了,它可以实现多种的效果。本文就要学习使用实现各种效果的对话框。先学习下理论知识。
public class
AlertDialog
extends Dialog
implementsDialogInterface
 
java.lang.Object
   ↳ android.app.Dialog
     ↳android.app.AlertDialog
Known DirectSubclasses
DatePickerDialog,ProgressDialog, TimePickerDialog
DatePickerDialogA simple dialog containing an DatePicker.
ProgressDialogA dialog showing a progress indicator and an optional text message or view.
 
TimePickerDialogA dialog that prompts the user for the time of day using a TimePicker.
 
 
Class Overview
A subclass ofDialog that can display one, two or three buttons. If you only want to displaya String in this dialog box, use the setMessage() method. If you want todisplay a more complex view, look up the FrameLayout called "custom"and add your view to it:
 
 FrameLayout fl = (FrameLayout)findViewById(android.R.id.custom); fl.addView(myView, newLayoutParams(MATCH_PARENT, WRAP_CONTENT));
从参考文档我们可以看到,这个类,我们可以显示1-3个按钮,而且可以实现自定义更复杂提示界面。好,开始我们的练习。

第一步、设计界面
主界面dialogview.xml
<?xml version="1.0"encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <ScrollView android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <RelativeLayout android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <Button android:layout_height="wrap_content"

android:text="确定取消对话框"

android:id="@+id/btnNormal"  android:layout_width="fill_parent" android:layout_alignParentTop="true"android:layout_alignParentLeft="true"></Button>
    <Button android:layout_height="wrap_content"android:text="肯定否定中立对话框"

android:id="@+id/btnThreeButtons" android:layout_width="fill_parent" android:layout_below="@+id/btnNormal" android:layout_alignParentLeft="true"android:layout_marginTop="21dp"></Button>
    <Button android:layout_height="wrap_content"android:text="简单view对话框" android:id="@+id/btnSimpleView"android:layout_width="fill_parent" android:layout_below="@+id/btnThreeButtons" android:layout_alignParentLeft="true"android:layout_marginTop="20dp"></Button>
    <Button android:layout_height="wrap_content"android:text="单选框对话框" android:id="@+id/btnSingleItem"android:layout_width="fill_parent" android:layout_below="@+id/btnSimpleView" android:layout_alignParentLeft="true"android:layout_marginTop="19dp"></Button>
    <Button android:layout_height="wrap_content"android:text="复选框对话框" android:id="@+id/btnMutilItems"android:layout_width="fill_parent" android:layout_below="@+id/btnSingleItem" android:layout_alignParentLeft="true"android:layout_marginTop="26dp"></Button>
    <Button android:layout_height="wrap_content"android:text="简单列表对话框" android:id="@+id/btnList"android:layout_width="fill_parent" android:layout_below="@+id/btnMutilItems" android:layout_alignParentLeft="true"android:layout_marginTop="19dp"></Button>
    <Button android:layout_height="wrap_content"android:text="自定义对话框" android:id="@+id/btnCustom"android:layout_width="fill_parent" android:layout_below="@+id/btnList" android:layout_alignParentLeft="true"android:layout_marginTop="19dp"></Button>
    </RelativeLayout>
    </ScrollView>
</RelativeLayout>
 
 自定义对话框customdialog.xml
<?xml version="1.0"encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:layout_height="wrap_content" android:layout_width="wrap_content"
 android:background="#ffffffff" android:orientation="horizontal"
 android:id="@+id/dialog">
 <TextView android:layout_height="wrap_content"
   android:layout_width="wrap_content"
  android:id="@+id/tvname" android:text="姓名:" />
 <EditText android:layout_height="wrap_content"
  android:layout_width="wrap_content" android:id="@+id/etname" android:minWidth="100dip"/>
 
</LinearLayout>
 

 
第二步、设计ActivityDialogActivity.java
 
/**
 *
 */
packagecom.figo.helloworld;
 
import android.app.Activity;
importandroid.app.AlertDialog;
importandroid.app.AlertDialog.Builder;
importandroid.app.Dialog;
importandroid.content.DialogInterface;
importandroid.content.DialogInterface.OnClickListener;
importandroid.content.DialogInterface.OnMultiChoiceClickListener;
importandroid.os.Bundle;
importandroid.view.KeyEvent;
importandroid.view.LayoutInflater;
importandroid.view.View;
importandroid.view.ViewGroup;
importandroid.widget.Button;
importandroid.widget.EditText;
importandroid.widget.Toast;
 
/**
 * @author Administrator
 *
 */
public classDialogActivity extends Activity implements
              android.view.View.OnClickListener{
       //定义按钮
       private Button btnNormal;
       private Button btnThreeButtons;
       private Button btnSimpleView;
       private Button btnSingleItem;
       private Button btnMutilItems;
       private Button btnList;
       private Button btnCustom;
       EditText txt;//简单视图对话框使用
       String[] strs=new String[] {"Item1", "Item2", "Item3", "Item4"};;//单选框对话框使用
       StringBuffer buffer=new StringBuffer();//多选框对话框使用
       View layout;//自定义对话框使用
       @Override
       protected void onCreate(BundlesavedInstanceState) {
              // TODO Auto-generated method stub
              super.onCreate(savedInstanceState);
              //设置页面
              setContentView(R.layout.dialogview);
              //找到页面按钮
              btnNormal = (Button) findViewById(R.id.btnNormal);
              btnThreeButtons = (Button)findViewById(R.id.btnThreeButtons);
              btnSimpleView = (Button)findViewById(R.id.btnSimpleView);
              btnSingleItem = (Button)findViewById(R.id.btnSingleItem);
              btnMutilItems = (Button)findViewById(R.id.btnMutilItems);
              btnList = (Button)findViewById(R.id.btnList);
              btnCustom = (Button)findViewById(R.id.btnCustom);
              //设置按钮事件
              btnNormal.setOnClickListener(this);
              btnThreeButtons.setOnClickListener(this);
              btnSimpleView.setOnClickListener(this);
              btnSingleItem.setOnClickListener(this);
              btnMutilItems.setOnClickListener(this);
              btnList.setOnClickListener(this);
              btnCustom.setOnClickListener(this);
 
       }
    //按键触发事件
       @Override
       public boolean onKeyDown(int keyCode,KeyEvent event) {
              // TODO Auto-generated method stub
              // 点回退键触发
              if (keyCode ==KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
                     dialog();
              }
              return false;
 
       }
 
       // 常见的确认和取消对话框
       protected void dialog() {
              AlertDialog.Builder builder = new Builder(DialogActivity.this);
              builder.setMessage("确认退出吗?");
 
              builder.setTitle("提示");
 
              builder.setPositiveButton("确认", new OnClickListener() {
 
                     @Override
                     public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
 
                            DialogActivity.this.finish();
                     }
              });
 
              builder.setNegativeButton("取消", new OnClickListener() {
 
                     @Override
                     public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                     }
              });
 
              builder.create().show();
       }
    //按钮事件
       @Override
       public void onClick(View v) {
              // TODO Auto-generated method stub
              switch (v.getId()) {
              case R.id.btnNormal://确定取消
                     dialog();
                     break;
              case R.id.btnThreeButtons://肯定否定中立
                     Dialog dialog = new AlertDialog.Builder(this)
                                   .setIcon(android.R.drawable.btn_star).setTitle("喜好调查")
                                   .setMessage("你喜欢周星驰的电影吗?")
                                   .setPositiveButton("很喜欢", new OnClickListener() {
 
                                          @Override
                                          public void onClick(DialogInterface dialog, int which) {
                                                 //TODO Auto-generated method stub
                                                 Toast.makeText(DialogActivity.this,"我很喜欢他的电影。",
                                                               Toast.LENGTH_LONG).show();
                                          }
                                   }).setNegativeButton("不喜欢", new OnClickListener() {
 
                                          @Override
                                          public void onClick(DialogInterface dialog, int which) {
                                                 //TODO Auto-generated method stub
                                                 Toast.makeText(DialogActivity.this,"我不喜欢他的电影。",
                                                               Toast.LENGTH_LONG).show();
                                          }
                                   }).setNeutralButton("一般", new OnClickListener() {
 
                                          @Override
                                          public void onClick(DialogInterface dialog, int which) {
                                                 //TODO Auto-generated method stub
                                                 Toast.makeText(DialogActivity.this,"谈不上喜欢不喜欢。",
                                                               Toast.LENGTH_LONG).show();
                                          }
                                   }).create();
 
                     dialog.show();
 
                     break;
              case R.id.btnSimpleView://简单视图
                     AlertDialog.Builder builder= new AlertDialog.Builder(this);
                     builder.setTitle("请输入");
                     builder.setIcon(android.R.drawable.ic_dialog_info);
                     txt=new EditText(this);
                     builder.setView(txt);
                     builder.setPositiveButton("确认", new OnClickListener() {
 
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                   Toast.makeText(getApplicationContext(),"您输入的是"+txt.getText().toString(),Toast.LENGTH_LONG).show();
                                   dialog.dismiss();
 
                          
                            }
                     });
 
                     builder.setNegativeButton("取消", new OnClickListener() {
 
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                   dialog.dismiss();
                            }
                     });
                     builder.create().show();
                     //builder.show();和上面效果一样
                     break;
              case R.id.btnSingleItem://单选
              
                     new AlertDialog.Builder(this)
                                   .setTitle("单选框")
                                   .setIcon(android.R.drawable.ic_dialog_info)
                                   .setSingleChoiceItems(strs,0,
                                                 newDialogInterface.OnClickListener() {
                                                        public void onClick(DialogInterface dialog,
                                                                      int which) {
                                                               String item=strs[which].toString();
                                                               Toast.makeText(getApplicationContext(),"您选择的是"+item,Toast.LENGTH_LONG).show();
                                                               dialog.dismiss();
                                                        }
                                                 }).setNegativeButton("取消", null).show();
                     break;
              case R.id.btnMutilItems://多选
                     AlertDialog.Builder mutilbuilder = new AlertDialog.Builder(this);
 
                     mutilbuilder.setTitle("复选框");
                     mutilbuilder.setMultiChoiceItems(strs,
                                                 null,new OnMultiChoiceClickListener()
                     {
 
                            @Override
                            public void onClick(DialogInterface dialog, int which,
                                          booleanisChecked) {
                                   // TODOAuto-generated method stub
                                   buffer.append(strs[which]).append("");
                                 
                            }
                          
                     }
                                               
                   
                     );
                     mutilbuilder.setPositiveButton("确定",new OnClickListener()
                     {
 
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                   // TODOAuto-generated method stub
                                   Toast.makeText(getApplicationContext(),"您选择的是:"+buffer.toString(),Toast.LENGTH_LONG).show();
                                   buffer=null;//重新清空
                            }}
                     );
                     mutilbuilder.setNegativeButton("取消", null);
                     mutilbuilder.show();
                     break;
              case R.id.btnList://列表
                     AlertDialog.Builder listbuilder = new AlertDialog.Builder(this);
                     listbuilder.setTitle("列表框");
                     listbuilder.setItems(strs,new OnClickListener(){
 
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                   // TODOAuto-generated method stub
                                   Toast.makeText(getApplicationContext(),"您选择的是:"+strs[which],Toast.LENGTH_LONG).show();
                            }});
                     listbuilder.setNegativeButton("确定", null);
                     listbuilder.show();
                     break;
              case R.id.btnCustom://自定义

                     Dialog dialog=null;
                     LayoutInflater inflater =getLayoutInflater();
                     layout =inflater.inflate(R.layout.customdialog,
                                   (ViewGroup)findViewById(R.id.dialog));

                     AlertDialog.Builder custombuilder = new AlertDialog.Builder(this);
                     custombuilder.setTitle("自定义布局");
                     custombuilder.setView(layout);
                     custombuilder.setPositiveButton("确定", new OnClickListener(){
 
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                   // TODOAuto-generated method stub
                                   //layout.findViewById(R.id.tvname).toString();
                                   Toast.makeText(getApplicationContext(),"您输入的是:"+((EditText)layout.findViewById(R.id.etname)).getText().toString(),Toast.LENGTH_LONG).show();

                                   dialog.dismiss();
                                 
                            }});
                     custombuilder.setNegativeButton("取消", null);

                     dialog=custombuilder.create();
                     dialog.show();
 
                     break;
              }
       }
 
}
 
 
 
第三步、AndroidManifest.xml注册Activity
    <activity android:name=".DialogActivity" android:label="@string/app_name">
           <intent-filter>
              <action android:name="android.intent.action.MAIN"/>
              <category android:name="android.intent.category.LAUNCHER"/>
           </intent-filter>
</activity>
 
第四步、运行效果
 
确认和取消



肯定否定中立
 

简单视图
 

单选框
 

 多选框

 简单列表

 自定义布局

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值