Android开发-Dialog对话框

 

1.分类

1.1 定义

         对话框一种消息提示机制,通用的方法有:setTitle,setMessage,create,show

        注意:其中对话框的下标是从0开始的。

1.2 分类

AlertDialog

普通对话框

列表对话框

单选对话框

多选对话框

输入对话框

ProgressDialog

等待对话框

进度条对话框

Dialog自定义对话框

 

2.AlertDialog

2.1 普通对话框

       1)普通对话框创建方式一:

       利用AlertDialog中的内部类构建器(Builder)来完成,涉及到的方法:

setPositiveButton
setNegativeButton
setNeutralButton
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.dialog_layout);
    findViewById(R.id.btn1).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            switch (view.getId()){
                case R.id.btn1:
                    showNormalDialog1();
                    break;
            }
        }
    });
}
//普通对话框创建方式一
public void showNormalDialog1(){
    //AlertDialog的构造方法被修饰为protected,一次包外是无法使用的,所以需要构建器
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    //设置对话框标题
    builder.setTitle("这是标题");
    //设置内容
    builder.setMessage("是否确定退出?");
    //设置按钮
    builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
       @Override
       public void onClick(DialogInterface dialogInterface, int i) {
       }
    });
    builder.setNegativeButton("取消",null);
    builder.setNeutralButton("不取消",null);
    //不需要写了,show()包含create()
    //builder.create();
    builder.show();
}

      效果图如下所示:

      

     2)普通对话框创建方式二

      直接用AlertDialog来创建,

        涉及的方法:

setButton

        涉及的常量:DialogInterface.BUTTON_POSITIVE,DialogInterface.BUTTON_NEGATIVE

//普通对话框创建方式二
public void showNormalDialog2(){
    //create()方法返回AlertDialog对象
    AlertDialog alertDialog = new AlertDialog.Builder(this).create();
    alertDialog.setTitle("提示");
    alertDialog.setMessage("请打分");
    alertDialog.setButton(DialogInterface.BUTTON_POSITIVE,"10分", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialogInterface, int i) {
            Toast.makeText(DialogActivity.this,"你选择了10分",Toast.LENGTH_SHORT);
        }
    });
     alertDialog.setButton(DialogInterface.BUTTON_NEGATIVE,"2分", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialogInterface, int i) {
            Toast.makeText(DialogActivity.this,"你选择了2分",Toast.LENGTH_SHORT);
        }
    });
      alertDialog.setButton(DialogInterface.BUTTON_NEUTRAL,"1分", new DialogInterface.OnClickListener() {
         @Override
         public void onClick(DialogInterface dialogInterface, int i) {
            Toast.makeText(DialogActivity.this,"你选择了1分",Toast.LENGTH_SHORT);
         }
     });
    alertDialog.show();
}

      效果图如下所示:

      注意两种创建普通对话框方式的区别。

2.2 列表对话框

         利用AlertDialog创建一个含有列表的对话框,涉及的方法:

setItems

         点击某个选项后,列表对话框默认会消失

//列表对话框创建方式
public void showListDialog(){
    final String[] items = {"我是1号","我是2号","我是3号","我是4号"};
    AlertDialog.Builder builder = new AlertDialog.Builder(this)
        .setTitle("请选择")
        //如果setMessage(),则列表会失效,setButton()不会
        //.setMessage("这是内容")
        //设置列表项
        .setItems(items, new DialogInterface.OnClickListener() {
        //i代表被点击项的索引
        @Override
        public void onClick(DialogInterface dialogInterface, int i) {
             Toast.makeText(DialogActivity.this, "你选择了"+items[i], Toast.LENGTH_SHORT).show();
        }
     });
    builder.show();
}

       如果setMessage(),则列表会失效

       效果图如下所示:

 

2.3 单选对话框

          利用AlertDialog创建一个单选按钮列表的对话框,涉及的方法:

setSingleChoiceItems

          点击某个选项后,列表对话框默认不会消失

//单选对话框创建方式
int index;
public void showSingleDialog(){
    final String[] language = {"Java","Android","Python","C"};
    AlertDialog.Builder builder = new AlertDialog.Builder(this)
        .setTitle("请选择语言")
        .setSingleChoiceItems(language, 2, new DialogInterface.OnClickListener() {
             @Override
             public void onClick(DialogInterface dialogInterface, int i) {
                 //这里的i会随着点击选项的不同发生改变
                 index = i;
              }
          })
          .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                     Toast.makeText(DialogActivity.this,"你选择了"+language[index],Toast.LENGTH_SHORT).show();
                }
          });
    builder.show();
}

       注意:其中对话框的下标是从0开始的。

       效果图如下所示:

2.4 多选对话框

        利用AlertDialog创建一个含有多选按钮列表的对话框,涉及的方法:

setMultiChoiceItems
//多选对话框创建方式
public void showMultiDialog(){
    String[] sports = {"篮球","足球","羽毛球","乒乓球"};
    final boolean[] isChecked = {true,false,false,false};
    AlertDialog.Builder builder = new AlertDialog.Builder(this)
        .setTitle("请选择你喜欢的运动")
        //参数1:选项
        //参数2:默认被选中项(true:选中,false:未被选中)
        //参数3:被点击时触发的事件
        .setMultiChoiceItems(sports,isChecked, new DialogInterface.OnMultiChoiceClickListener() {
               //参数1:对话框本身
               //参数2:索引值
               //参数3:标志选项是否被选中
               @Override
               public void onClick(DialogInterface dialogInterface, int i, boolean b) {
                    //无论选中选项还是取消选中选项都会触发onClick,得到当前选项是否被选中
                    isChecked[i] = b;
                }
         })
         .setPositiveButton("确定", new DialogInterface.OnClickListener() {
              @Override
              public void onClick(DialogInterface dialogInterface, int i) {

              }
         });
   builder.show();
}

       注:即使不进行:isChecked[i] = b,也没有影响,onClick()方法里会自动默认对选项进行选中或不选中进行赋值操作(前提是OnClick方法必须有)。

     效果图如下所示:

2.5 输入对话框

            利用AlertDialog创建一个输入框的对话框,涉及方法:

setView
//输入对话框创建方式
public void showInputDialog(){
    EditText editText = new EditText(this);
    AlertDialog.Builder builder = new AlertDialog.Builder(this)
        .setTitle("输入对话框")
        .setView(editText)
        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
             @Override
             public void onClick(DialogInterface dialogInterface, int i) {

             }
        });
    builder.show();
}

      效果图如下所示:

 

3.ProgressDialog

3.1 等待对话框

         利用ProgressDialog创建一个含有等待效果的对话框,涉及的方法:

setCancelable
//等待对话框创建方式
public void showWaitingDialog(){
    //进度条对话框。默认样式为转圈
    ProgressDialog dialog = new ProgressDialog(this);
    dialog.setTitle("等待对话框");
    dialog.setMessage("请等待...");
    //默认为true,表示可以点击让对话框消失,为false时,对话框不会消失
    dialog.setCancelable(true);
    dialog.show();
    //设置对话框消失,实现控制对话框消失
    //dialog.dismiss();
}

       效果如下所示:

3.2 进度条对话框

        利用ProgressDialog创建一个含有等待效果的对话框,涉及的方法:

setIndeterminate
setProgressStyle(ProgressDialog.STYLE_HORIZONTAL)
//进度条对话框创建方式
public void showProgressDialog(){
    final ProgressDialog dialog = new ProgressDialog(this);
    dialog.setTitle("进度条对话框");
    dialog.setMessage("请等待...");
    //设置对话框水平样式
    dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
    //设置进度条进度不模糊
    dialog.setIndeterminate(false);
    //设置进度条进度值
    //dialog.setProgress(20);
    dialog.show();
    //线程控制进度条的进度值改变
    new Thread(){
        @Override
        public void run() {
            super.run();
            for(int i = 1;i<=100;i++){
                //设置进度条的进度值
                dialog.setProgress(i);
                try {
                     //线程休眠
                     Thread.sleep(100);
                } catch (InterruptedException e) {
                        e.printStackTrace();
                }
            }
          //控制进度条对话框消失
          dialog.dismiss();
        }
    }.start();
}

      效果如下所示:

 

4.Dialog

4.1 自定义对话框

第一步:定义对话框的布局,customdialog_layout.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:gravity="center_horizontal"
    android:background="#ffb36b">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="自定义对话框"
        android:textSize="25sp"
        android:textColor="#f91090"
        android:textStyle="bold"
        android:layout_marginTop="20dp"/>
    <View
        android:layout_width="match_parent"
        android:layout_height="3dp"
        android:background="#FFFFFF"
        android:layout_marginTop="20sp" />
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="你确定要退出当前程序吗?"
        android:textSize="18sp"
        android:textColor="#f91090"
        android:layout_marginTop="20dp"/>
    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:layout_marginTop="10dp"
        android:layout_marginBottom="10dp">
        <Button
            android:id="@+id/customdialog_surebtn"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="确定"/>
        <Button
            android:id="@+id/customdialog_cancelbtn"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="取消"/>
    </LinearLayout>
</LinearLayout>

第二步:自定义一个类,继承自Dialog类,在构造方法中调用 setContentView。

//自定义一个类,继承自Dialog类,在构造方法中调用 setContentView
public class CustomDialog extends Dialog{
    public CustomDialog(@NonNull Context context) {
        //传入样式
        super(context,R.style.customdialog);
        setContentView(R.layout.customdialog_layout);
        Button sureBtn = findViewById(R.id.customdialog_surebtn);
        Button cancelBtn = findViewById(R.id.customdialog_cancelbtn);
        //对自定义对话框中的控件添加事件
        cancelBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dismiss();   //直接调用,对话框消失
            }
        });
        sureBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                System.exit(0);  //退出程序
            }
        });
    }
}

第三步:设定对话框的风格(去掉默认的标题栏和背景),style.xml

<resources>
    <style name="customdialog" parent="android:style/Theme.Dialog">
        <item name="android:windowNoTitle">true</item>
        <item name="android:windowBackground">@android:color/transparent</item>
    </style>
</resources>

第四步:实例化自定义的对话框,让其显示出来。

//自定义对话框的创建方式
public void showCustomDialog(){
    //设定自定义对话框的风格(不显示标题栏,背景)
    //调用含设定对话框风格参数的构造方法
    //对自定义对话框中的控件添加事件
    //实例化自定义对话框,让其显示出来
    CustomDialog dialog = new CustomDialog(this);
    dialog.show();
}

     效果图如下所示:

4.2 DialogActivity

4.2.1 定义

     将Activity伪装成Dialog弹出框,这样既显示了界面,又可以在Activity里面编写控制代码,这就是DialogActivity。

4.2.2 原理

      默认情况下,Activity是占据充满整个屏幕的。但是可以为一个Activity设置一个对话框主题,这样Activity就能像一个浮动的对话框显示出来了,如下所示:

android:theme="@android:style/Theme.Dialog"

4.2.3 一般步骤

      如下所示:

1.定义要变成Dialog的Activity类,继承自Activity,同时编写其layout布局
2.在自定义的Activity类中设置风格,样式,监听事件等等。
3.在MainActivity中创建实例并调用show()方法
 
 

4.2.4 案例

      1)

 

 

对话框中应用ArrayAdapter

            ArrayAdapter(数组适配器),只能用来显示单一的文本,构造方法:

ArrayAdapter(Context context,int resource,int textviewId,List<T> objects)

第一步:设置对话框选项的布局文件:array_item_layout.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:gravity="center_vertical|center_horizontal"
    android:padding="5dp"
    android:background="#eeaffb">
    
    <ImageView
        android:layout_width="40dp"
        android:layout_height="40dp"
        android:src="@mipmap/music"/>
    <TextView
        android:id="@+id/array_item"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="测试"
        android:textSize="17sp"
        android:layout_marginLeft="80dp"/>
</LinearLayout>

第二步:显示

 //数组适配器案例
public void showArrayAdapter(){
    final String[] musics = {"暖暖","喜欢你","阳光彩虹小白马","你不是真正的快乐","Time Machine"};
    //参数1:环境
    //参数2:布局资源索引,指的是每一项数据所呈现的样式android.R.layout.xxx
    //参数3:指定文本需要放在布局中对应ID的文本控件
    //参数4:数据源
    ArrayAdapter adapter = new ArrayAdapter(this,R.layout.array_item_layout,R.id.array_item,musics);
    AlertDialog.Builder builder = new AlertDialog.Builder(this)
        .setTitle("请选择喜欢的歌曲")
        //参数1:适配器对象
        //参数2:监听器
        .setAdapter(adapter, new DialogInterface.OnClickListener() {
             @Override
             public void onClick(DialogInterface dialogInterface, int i) {
                  Toast.makeText(DialogActivity.this,"你选择了"+musics[i],Toast.LENGTH_SHORT).show();
                  //点击某个选项后,对话框消失
                  dialogInterface.dismiss();
             }
         })
         .setPositiveButton("确定",null)
         .setNegativeButton("取消",null);
   builder.show();
}

 

DatePickerDialog(日期选择对话框)

      效果:

 

   改变样式方法一:

DatePickerDialog.THEME_HOLO_LIGHT

改变样式方法二:

<resources>
    <style name="dateDialog" parent="android:Theme.Holo.Light.NoActionBar">
        <item name="android:windowFrame">@null</item>
        <item name="android:windowIsFloating">true</item>
        <item name="android:windowIsTranslucent">false</item>
        <item name="android:windowNoTitle">false</item>
        <item name="android:windowContentOverlay">@null</item>
        <item name="android:backgroundDimEnabled">false</item>
        <item name="android:textColor">#f61212</item>
    </style>
</resources>

 

public class MainActivity extends AppCompatActivity {
    private int year,month,day;
    private Calendar calendar;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        getDate();
        findViewById(R.id.date_choose_btn).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                datePickerDialog();
            }
        });
    }
    private void getDate(){
        calendar = Calendar.getInstance();
        year = calendar.get(Calendar.YEAR);
        month = calendar.get(Calendar.MONTH);
        day = calendar.get(Calendar.DAY_OF_MONTH);
    }
    public void datePickerDialog(){
         String str;
         DatePickerDialog dialog = new DatePickerDialog(this,DatePickerDialog.THEME_HOLO_LIGHT,new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker datePicker, int i1, int i2, int i3) {
            }
        },year,month,day);
        dialog.setTitle(year+","+month+","+day);
        dialog.show();
    }
}

 

 

 

 

 

 

 

  • 2
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

luckyliuqs

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值