UI组件-对话框

简介: 前言不要嫌前进的慢,只要一直在前进就好。AlertDialog组件AlertDialog的功能很强大,它生成的对话框可分为如下4个区域。图标区标题区内容区按钮区从上面这个结构来看创建对话框需要以下几步。

前言

不要嫌前进的慢,只要一直在前进就好。

AlertDialog组件

AlertDialog的功能很强大,它生成的对话框可分为如下4个区域。
  • 图标区
  • 标题区
  • 内容区
  • 按钮区
从上面这个结构来看创建对话框需要以下几步。
  1. 创建AlertDialog.Builder对象

  2. 调用AlertDialog.Builder的setTitle()或setCustomTitle()方法设置标题。

  3. 调用AlertDialog.Builder的setIcon()方法设置图标。

  4. 调用AlertDialog.Builder的相关设置方法设置对话框内容。

  5. 调用AlertDialog.Builder的setPositiveButton()、setNegativeButton()或setNeutralButton()方法添加多个按钮。

  6. 调用AlertDialog.Builder的create()方法创建AlertDialog对象,再调用AlertDialog对象的show()方法将该对话框显示出来。

其中第4步设置对话框的内容有如下6种方法来指定。
  1. setMessage():设置对话框内容为简单文本。

  2. setItems():设置对话框内容为简单列表项。

  3. setSingleChoiceItems():设置对话框内容为单选列表项。

  4. setMultiChoiceItems():设置对话框内容为多选列表项。

  5. setAdapter():设置对话框内容为自定义列表项。

  6. setView():设置对话框内容为自定义View。

代码示例

alertdialog.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="match_parent"
    android:orientation="vertical" >

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/show"
        android:textSize="20dp"
        />
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="简单对话框"
        android:onClick="simple"
        />
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="简单列表项对话框"
        android:onClick="simpleList"
        />
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="单选列表项对话框"
        android:onClick="singleChoice"
        />
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="多选列表项对话框"
        android:onClick="multiChoice"
        />
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="自定义列表项对话框"
        android:onClick="customList"
        />
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="自定义View对话框"
        android:onClick="customView"
        />

</LinearLayout>
MainActivity.java
private AlertDialog.Builder setPositiveButton(AlertDialog.Builder builder)
    {
        //调用setPositiveButton方法添加“确定”按钮
        return builder.setPositiveButton("确定", new OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // TODO Auto-generated method stub
                show.setText("单击了【确定】按钮!");
            }
        });
    }
    private AlertDialog.Builder setNegativeButton(AlertDialog.Builder builder)
    {
        //调用setPositiveButton方法添加“确定”按钮
        return builder.setNegativeButton("取消", new OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // TODO Auto-generated method stub
                show.setText("单击了【取消】按钮!");
            }
        });
    }
提示消息的对话框
public void simple(View v)
    {
        AlertDialog.Builder builder = new AlertDialog.Builder(this)
                .setTitle("简单对话框")          //设置标题
                .setIcon(R.drawable.ic_launcher) //设置图标
                .setMessage("对话框测试内容\n第二行内容");
        //AlertDialog.Builder添加确定按钮
        setPositiveButton(builder);
        //AlertDialog.Builder添加取消按钮
        setNegativeButton(builder)
        .create()
        .show();
    }
简单列表项对话框
public void simpleList(View v)
    {
        final String items[] = {"西游记","三国演义","水浒传","红楼梦"};
        AlertDialog.Builder builder = new AlertDialog.Builder(this)
                //设置对话框标题
                .setTitle("简单列表项对话框")
                //设置图标
                .setIcon(R.drawable.ic_launcher)
                //设置内容
                .setItems(items, new OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                        show.setText("您选中了《" +  items[which] + "》");

                    }
                });
        //为AlertDialog。Builder添加“确定”按钮
        setPositiveButton(builder);
        //为AlertDialog。Builder添加“取消”按钮
        setNegativeButton(builder)
        .create()
        .show();
    }
单选列表项对话框
public void singleChoice(View v) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this)
                // 设置对话框标题
                .setTitle("单选列表项对话框")
                // 设置图标
                .setIcon(R.drawable.ic_launcher)
                // 设置单选列表项,默认选中第二项
                .setSingleChoiceItems(items, 1, new OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        show.setText("您选中了《" + items[which] + "》");
                    }
                });
        // 为AlertDialog。Builder添加“确定”按钮
        setPositiveButton(builder);
        // 为AlertDialog。Builder添加“取消”按钮
        setNegativeButton(builder)
        .create()
        .show();
    }
多选列表项对话框
public void multiChoice(View v) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this)
                // 设置对话框标题
                .setTitle("多选列表项对话框")
                // 设置图标
                .setIcon(R.drawable.ic_launcher)
                // 设置多选列表项,默认勾选第三项
                .setMultiChoiceItems(items, new boolean[]{false, false, true, false},null);
        // 为AlertDialog。Builder添加“确定”按钮
        setPositiveButton(builder);
        // 为AlertDialog。Builder添加“取消”按钮
        setNegativeButton(builder)
        .create()
        .show();
    }
自定义列表项对话框
public void customList(View v) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this)
                // 设置对话框标题
                .setTitle("自定义列表项对话框")
                // 设置图标
                .setIcon(R.drawable.ic_launcher)
                // 设置自定义列表项
                .setAdapter(new ArrayAdapter<String>(this, R.layout.array_item, items), null);
        // 为AlertDialog。Builder添加“确定”按钮
        setPositiveButton(builder);
        // 为AlertDialog。Builder添加“取消”按钮
        setNegativeButton(builder)
        .create()
        .show();
    }

自定义View对话框
public void customView(View v) {

        TableLayout loginForm = (TableLayout) getLayoutInflater().inflate(R.layout.login, null);

        new AlertDialog.Builder(this)
        .setIcon(R.drawable.ic_launcher)
        .setTitle("自定义View对话框")
        .setView(loginForm)
        .setPositiveButton("登陆", null)
        .setNegativeButton("取消", null)
        .create()
        .show();
    }

效果

提示消息的对话框
img_186fd94215134b515b19e9c82d45f004.png
Screenshot_20171024-093905.png
简单列表项对话框
img_4ed903c1f8f95b8f87be123cc5814798.png
Screenshot_20171024-094839.png
单选列表项对话框
img_bff4204c2656afcc1dabf4f49e932139.png
Screenshot_20171024-095730.png
多选列表项对话框
img_6492ebea3c4c90a3f6686842c6013cc6.png
Screenshot_20171024-100031.png
自定义列表项对话框
img_90772c92865e0d0f0e68347fed1f94d8.png
Screenshot_20171024-100446.png
自定义View对话框
img_ca919ffd580559711f8f6f9432038fed.png
Screenshot_20171024-101745.png

提示

不仅setAdapter()方法可以接受Adapter作为参数,setSingleChoice方法也可以接受Adapter作为参数,也可以传入Cursor(相当于数据库查询结果集)作为参数。

PopupWindow组件

PopupWindow组件与AlertDialog功能相似,主要的区别就是AlertDialog不能指定显示位置,只能默认显示在屏幕中间。而PopupWindow组件更加灵活,任意位置都可以显示。
使用PoppupWindow创建对话框只要如下两步。
  • 调用PopupWindow的构造器创建PopupWindow对象。

  • 调用PopupWindow的showAsDropDown(View v)方法将PopupWindow作为v组件的下拉组件显示;或调用PopupWindow的showAtLocation()方法将PopupWindow在指定位置显示出来。

代码示例

使用showAtLocation()方法显示
popup_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/ll"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center_horizontal"
  >
    <Button
        android:id="@+id/bn"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="弹出POPUP窗口"
        />
</LinearLayout>

popup.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="200dp"
    android:orientation="vertical"
     >
    <ImageView
        android:layout_width="500dp"
        android:layout_height="wrap_content"
        android:src="@drawable/kaola"
        />
    <Button
        android:layout_gravity="center_horizontal"
        android:id="@+id/close"
        android:text="关闭"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        />
</LinearLayout>
MainActivity.java
public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.popup_main);

        //加载R.layout.popup对应的界面布局文件
        View root = LayoutInflater.from(MainActivity.this).inflate(R.layout.popup, null);
        //创建PopupWindow对象
        final PopupWindow popup = new PopupWindow(root,LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT,true);
        Button button = (Button) findViewById(R.id.bn);
        button.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                View rootView = LayoutInflater.from(MainActivity.this).inflate(R.layout.popup_main, null);
                //将PopupWindow显示在指定位置
                popup.showAtLocation(rootView, Gravity.BOTTOM, 0, 0);
            }
        });
        //获取PopupWindow中的“关闭”按钮
        root.findViewById(R.id.close).setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                //关闭PopupWindow
                popup.dismiss();
            }
        });
    }
}
使用showAsDropDown()方法显示
main.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="match_parent"
    android:orientation="vertical">
    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#ffffff"
        >
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:textColor="#50484b"
            android:padding="10dp"
            android:text="返回"
            />
        <TextView
            android:id="@+id/menu"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:textColor="#50484b"
            android:padding="10dp"
            android:text="菜单"
            />

    </RelativeLayout>


</LinearLayout>

popup_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:paddingBottom="2dp" >

    <View
        android:layout_width="match_parent"
        android:layout_height="2.25dp"
        android:background="#fa7829" />

    <TextView
        android:id="@+id/tv1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="halo" />

    <View
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:background="#f00" />

    <TextView
        android:id="@+id/tv2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="halo1" />

</LinearLayout>
MainActivity.java
public class MainActivity extends Activity {

    private PopupWindow popup;
    private TextView tv;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

         tv = (TextView) findViewById(R.id.menu);
         tv.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                showPopupWindow();

            }
        });
    }
    private void showPopupWindow() {
        View contentView = LayoutInflater.from(MainActivity.this).inflate(R.layout.popup_layout, null);
        popup = new PopupWindow(contentView);
        popup.setWidth(ViewGroup.LayoutParams.WRAP_CONTENT);
        popup.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        TextView tv1 = (TextView) contentView.findViewById(R.id.tv1);
        TextView tv2 = (TextView) contentView.findViewById(R.id.tv2);

        tv1.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(MainActivity.this, "tv1", Toast.LENGTH_SHORT).show();
                popup.dismiss();
            }
        });
        tv2.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(MainActivity.this, "tv2", Toast.LENGTH_SHORT).show();
                popup.dismiss();
            }
        });

        popup.showAsDropDown(tv);

    }
}

效果

使用showAtLocation()方法显示
img_5cbde2ab1c9f5a24f1b204f78b5ab8f5.png
Screenshot_20171024-132525.png
使用showAsDropDown()方法显示
img_179477a3db906dbb582a1965a668ffc5.png
Screenshot_20171024-135937.png

提示

PopupWindow最基本的三个条件是一定要设置contentView,width,height,不然PopupWindow不显示。

DatePickerDialog和TimerPickerDialog组件

这两个组件的功能和用法非常简单,只要如下两步即可。
  • 通过new关键字创建DatePickerDialog、TimerPickerDialog实例,调用它们的show()方法即可将日期选择对话框、时间选择对话框显示出来。

  • 为DatePickerDialog、TimePickerDialog绑定监听器,这样可以保证用户设置事件时触发监听器。

代码示例

pickerdialog.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="match_parent"
    android:orientation="vertical" >
    <EditText
        android:id="@+id/show"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        />
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="bt_datepicker"
        android:text="日期选择对话框"
        />
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="bt_timepicker"
        android:text="时间选择对话框"
        />

</LinearLayout>

MainActivity.java
public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.pickerdialog);

    }

    public void bt_timepicker(View v)
    {
        Calendar c = Calendar.getInstance();
        //创建一个DatePickerDialog对话框实例
        new DatePickerDialog(MainActivity.this,
                new OnDateSetListener() {
                    @Override
                    public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                        EditText show = (EditText) findViewById(R.id.show);
                        show.setText("您选择了:" + year + "年" + (monthOfYear + 1) + "月" + dayOfMonth + "日");
                    }
                },
                c.get(Calendar.YEAR),
                c.get(Calendar.MONTH),
                c.get(Calendar.DAY_OF_MONTH)).show();
    }


    public void bt_datepicker(View v)
    {
        Calendar c = Calendar.getInstance();

        new TimePickerDialog(MainActivity.this, new OnTimeSetListener() {

            @Override
            public void onTimeSet(TimePicker view, int hourOfDay, int minute) {

                EditText show = (EditText) findViewById(R.id.show);
                show.setText("您选择了:" + hourOfDay + "时" + minute + "分");
            }
        }
        ,c.get(Calendar.HOUR_OF_DAY)
        ,c.get(Calendar.MINUTE)
        , true).show();//true表示24小时制
    }
}

效果

img_36f574410764ef2d5a56330cf4efd3d2.png
Screenshot_20171024-142038.png
img_35069f848ceb376d3cb1dd9ea851043e.png
Screenshot_20171024-142044.png

ProgressDialog组件

ProgressDialog代表了进度对话框。使用ProgressDialog创建进度对话框有如下两种方式。
  • 如果只是创建简单的进度对话框,那么调用ProgressDialog提供的静态show()方法显示对话框即可。

  • 创建ProgressDialog,然后调用方法对对话框里的进度条进行设置,设置完成后将对话框显示出来即可。

对进度对话框进行设置的方法如下。
  • setIndeterminate(boolean indeterminate):设置对话框里的进度条不显示进度值。

  • setMax(int max):设置对话框里进度条的最大值。

  • setMessage(CharSequence message):设置对话框里的提示消息。

  • setProgress(int value);设置对话框里进度条的进度值。

  • setProgressStyle(int style):设置对话框里进度条的风格。

代码示例

progressdialog.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="match_parent"
    android:orientation="vertical" >

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="show_Progress1"
        android:text="环形进度条"
        />
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="show_Progress2"
        android:text="不显示进度的进度条"
        />
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="show_Progress3"
        android:text="显示进度的进度条"
        />

</LinearLayout>

MainActivity.java
public class MainActivity extends Activity {

    final static int MAX_PROGRESS = 100;
    //该程序模拟填充长度为100的数组
    private int[] data = new int[50];
    //记录进度对话框的完成百分比
    int progressStatus = 0;
    int hasData = 0;
    ProgressDialog pd1,pd2;
    //定义一个负责更新进度的Handler
    Handler handler = new Handler()
    {
        @Override
        public void handleMessage(Message msg) {

            //表明该消息是由该程序发送的
            if(msg.what == 1)
            {
                pd2.setProgress(progressStatus);
            }
        }

    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.progressdialog);

    }

    public void show_Progress1(View v)
    {
        //调用静态方法显示环形进度条
        ProgressDialog.show(this, "任务执行中", "任务执行中,请等待",false,true);
    }
    public void show_Progress2(View v)
    {
        pd1 = new ProgressDialog(MainActivity.this);
        //设置对话框标题
        pd1.setTitle("任务执行中");
        //设置对话框显示的内容
        pd1.setMessage("任务正在执行中,请等待。。。");
        //设置对话框能用"取消"按钮关闭
        pd1.setCancelable(true);
        //设置对话框的进度条风格
        pd1.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        //设置对话框的进度条是否显示进度
        pd1.setIndeterminate(false);
        pd1.show();
    }
    public void show_Progress3(View v)
    {
        //将进度条的完成进度重设为0
        progressStatus = 0;
        //重新开始填充数组
        hasData = 0;
        pd2 = new ProgressDialog(MainActivity.this);
        //设置对话框的标题
        pd2.setTitle("任务完成百分比");
        //设置对话框的显示内容
        pd2.setMessage("耗时任务的完成百分比");
        //设置对话框不能用"取消"按钮关闭
        pd2.setCancelable(false);
        //设置对话框的进度条风格
        pd2.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        //设置对话框的进度条是否显示进度条
        pd2.setIndeterminate(false);
        pd2.show();
        new Thread()
        {
            public void run()
            {
                while(progressStatus < MAX_PROGRESS)
                {
                    //获取耗时操作的完成百分比
                    progressStatus = MAX_PROGRESS * doWork() / data.length;
                    //发送空消息到Handler
                    handler.sendEmptyMessage(1);
                }
                //如果任务已完成
                if(progressStatus >= MAX_PROGRESS)
                {
                    //关闭对话框
                    pd2.dismiss();
                }
            }
        }.start();
    }

    public int doWork() {

        //为数组元素赋值
        data[hasData++] = (int)(Math.random() * 100);
        try
        {
            Thread.sleep(1000);
        }
        catch (InterruptedException e)
        {
            e.printStackTrace();
        }
        return hasData;
    }
}

效果

img_e4b6a91d4e31839a550da48e9c8e68c0.png
progress1.PNG
img_a9b848b65f3b4795e03fe3cdb695d2da.png
Screenshot_20171024-145850.png
img_1fc4f68a52e77ebb696ce4983c011035.png
Screenshot_20171024-145327.png

目录
相关文章
|
19天前
|
JavaScript 前端开发
如何优雅的只在当前页面中覆盖ui库中组件的样式(vue的问题)
如何优雅的只在当前页面中覆盖ui库中组件的样式(vue的问题)
14 0
如何优雅的只在当前页面中覆盖ui库中组件的样式(vue的问题)
|
1月前
|
搜索推荐 BI 开发者
sap.ui.comp.smarttable.SmartTable 组件 beforeRebindTable 事件的用法
sap.ui.comp.smarttable.SmartTable 组件 beforeRebindTable 事件的用法
22 0
|
3月前
|
开发框架 前端开发 .NET
七天.NET 8操作SQLite入门到实战 - (1)第七天BootstrapBlazor UI组件库引入
七天.NET 8操作SQLite入门到实战 - (1)第七天BootstrapBlazor UI组件库引入
|
3月前
|
JavaScript 前端开发 API
面试官:ui组件可以自动加载,那么业务组件可以吗?
面试官:ui组件可以自动加载,那么业务组件可以吗?
|
3月前
|
设计模式 前端开发 数据可视化
【第4期】一文了解React UI 组件库
【第4期】一文了解React UI 组件库
85 0
|
2月前
|
资源调度 JavaScript
Vue + Element-ui组件上传图片报错问题解决方案
Vue + Element-ui组件上传图片报错问题解决方案
|
4月前
|
移动开发
【实用】一组原创原生样式的基础控件、UI组件样式(偏向移动端H5页面的样式)
【实用】一组原创原生样式的基础控件、UI组件样式(偏向移动端H5页面的样式)
【实用】一组原创原生样式的基础控件、UI组件样式(偏向移动端H5页面的样式)
|
3月前
|
前端开发
element-ui组件DatePicker日期选择器移动端兼容
element-ui组件DatePicker日期选择器移动端兼容
element-ui组件DatePicker日期选择器移动端兼容
|
3月前
|
JSON Java 数据库
基于uniapp原生组件uni-ui 做一个登录注册与个人中心(后端篇)
基于uniapp原生组件uni-ui 做一个登录注册与个人中心(后端篇)
100 2
|
3月前
|
搜索推荐 C# 开发者
3个值得推荐的WPF UI组件库
3个值得推荐的WPF UI组件库
151 0