Android-Dialogs(一) AlterDialog基本使用

本文深入探讨Android中的DialogFragment,讲解如何创建简单的DialogFragment,构建AlertDialog,包括添加按钮、列表以及自定义布局。建议使用DialogFragment作为对话框容器,以方便管理和设计各种对话效果。同时,文章介绍了如何将事件传递回Dialog's Host,以及如何解除对话框。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Dialog类是所有对话框的基类,不应该实例化Dialog而是采用如下子类进行实例化:

  • AlertDialog: 可以显示标题、最多三个按钮、可选项列表或者自定义布局
  • DatePickerDialog和**TimePickerDialog:**这是预定义的对话框可以选择日期或者时间
  • ProgressDialog:带有进度条的对话框,但是不推荐使用,它会阻止用户与应用程序进行交互。

谷歌官方推荐使用DialogFragment作为对话框的容器,DialogFragment类提供了创建对话框和管理器外观所需的所有控件

创建一个简单的DialogFragment

可以继承DialogFragment并重写onCreateDialog(),在回调方法中创建AlertDialog来完成各种对话框设计-包括自定义布局。

例如:

public class FireMissilesDialogFragment extends DialogFragment {
    @NonNull
    @Override
    public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setMessage("Fire missiles?")
                .setPositiveButton("FIRE", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        // todo...
                    }
                })
                .setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        // todo...
                    }
                });
        // 创建并返回AlertDialog实例
        return builder.create();
    }
}

使用FireMissilesDialogFragment

FireMissilesDialogFragment fireMissilesDialogFragment = new FireMissilesDialogFragment();
        fireMissilesDialogFragment.show(getSupportFragmentManager(),"dialog");

e0dd26e7030a098ade1dd69062149aab.png

Tips:第二个参数“dialog”是一个唯一的标记名称,系统在必要时可以用它来保存和回复片段状态。还可以调用findFragmentByTag来获取片段的句柄。

构建AlertDialog

使用AlertDialog类可以构建设计各种dialog
在构建AlertDialog时谷歌官方推荐使用AlertDialog.Builder,它可以创建包括自定义对话框在内的各种内容的Dialogs

AlerDialog.Builder builder = new AlertDialog.Builder(getActivity());
// 通过链式调用各种setter方法完成Dialog的设置
builder.setMessage("Message")
      .setTitle("Tittle");
AlterDialog dialog = builder.create();

Android 将Dialog分为三个区域
f5ff6e4c231a5e9822a5fbf731781132.png

  1. Title
  2. Content area 用于展示message,一个列表,其他自定义布局
  3. Action buttons 最多支持三个按钮
添加按钮

如果不使用自定义布局那么AlterDialog上面最多可以存在三个Button:Positive、Negative

      builder.setPositiveButton("FIRE", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        // todo...
                    }
                })
              .setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        // todo...
                    }
                })
              .setNeutralButton("Neutral", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        
                    }
                })
类型作用
Positive用于确定某个动作
Negative用于取消某个动作
Neutral当用户可能不想继续操作时,应该使用此功能,但不一定要取消。它出现在正负按钮之间。例如,行动可能是“稍后提醒我”。
添加列表

AlertDialog的列表有三种

  • 传统的单选列表
  • 带有单选按钮的单选列表
  • 带有复选框的多选列表
    builder.setTitle(R.string.pick_color)
           .setItems(R.array.colors_array, new DialogInterface.OnClickListener() {
               public void onClick(DialogInterface dialog, int which) {
               // which代表所有位置
           }

使用列表只有就不能显示消息(message)了
使用setItems来指定项目,可以传递一个数组,也可以使用setAdapter()

public AlertDialog.Builder setAdapter(ListAdapter adapter, OnClickListener listener) {
      throw new RuntimeException("Stub!");
}

使用setAdapter就可以使用ListAdapter使用动态数据。

如果要设置单选和多选可以使用

  • setSingleChoiceItems()
  • setMultiChoiceItems()
自定义布局
创建一个布局文件

res/layout/dialog_correcting.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">
    <EditText
        android:id="@+id/correctEdittext"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="10dp"
        android:layout_margin="20dp"/>
</LinearLayout>
创建DialogFragment子类

使用DialogFragment作为容器

public class CorrectingDialogFragment extends DialogFragment {

    @NonNull
    @Override
    public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {
        AlertDialog.Builder builder=new AlertDialog.Builder(getActivity());
        // 得到布局服务
        LayoutInflater inflater = requireActivity().getLayoutInflater();
        builder.setTitle("校正编码")
                .setView(inflater.inflate(R.layout.dialog_correcting,null))
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        // todo...
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        CorrectingDialogFragment.this.getDialog().cancel();
                    }
                });
        return builder.create();
    }
}

5bb1053fe8445af09739c76823eb570a.png

Tip:对于自定义Dialog可以将一个Activity作为一个dialog,操作方法就是改变Activity的主题,使其主题为Theme.Holo.Dialog
<activity android:theme="@android:style/Theme.Holo.Dialog" >

将事件传递回Dialog’s Host

在以上的代码中按钮的click事件逻辑处理只能写死在CorrectingDialogFragment中,如果要复用CorrectingDialogFragment显然十分不方便,因此需要将click的点击事件拿出来处理,每个CorrectingDialogFragment实例可以有自己的处理逻辑。

public class CorrectingDialogFragment extends DialogFragment {
    public interface CorrectingDialogListener{
        public void onDialogPositiveClick(DialogFragment dialog);
        public void onDialogNegativeClick(DialogFragment dialog);
    }

    CorrectingDialogListener listener;

    public void setListener(CorrectingDialogListener listener) {
        this.listener = listener;
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        try{
            listener = (CorrectingDialogListener) context;
        }catch (ClassCastException e){
            throw new ClassCastException(getActivity().toString()+("must implement NoticeDialogListener"));
        }
    }

    @NonNull
    @Override
    public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {
        AlertDialog.Builder builder=new AlertDialog.Builder(getActivity());
        // 得到布局服务
        final LayoutInflater inflater = requireActivity().getLayoutInflater();
        builder.setTitle("校正编码")
                .setView(inflater.inflate(R.layout.dialog_correcting,null))
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        listener.onDialogPositiveClick(CorrectingDialogFragment.this);
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                       listener.onDialogNegativeClick(CorrectingDialogFragment.this);
                    }
                });
        return builder.create();
    }
}

以上代码定义了一个接口,通过该接口将事件传递回host activity

有两种实现方法:

public class ResultActivity extends AppCompatActivity{
    ...
    CorrectingDialogFragment dialogFragment = new CorrectingDialogFragment();

    public void calibrationButtonClick(View view){
        dialogFragment.setListener(listener);
        dialogFragment.show(getSupportFragmentManager(),"dialogFragment");
        
    }

   CorrectingDialogFragment.CorrectingDialogListener listener = new CorrectingDialogFragment.CorrectingDialogListener() {
       @Override
       public void onDialogPositiveClick(DialogFragment dialog) {
           
       }
       @Override
       public void onDialogNegativeClick(DialogFragment dialog) {

       }
   };
    
}

public class ResultActivity extends AppCompatActivity implements CorrectingDialogFragment.CorrectingDialogListener {
    ...
    @Override
    public void onDialogPositiveClick(DialogFragment dialog) {
        
    }

    @Override
    public void onDialogNegativeClick(DialogFragment dialog) {

    }
解除对话框

点击AlterDialog.Builder的任何一个按钮,系统都会默认调用dismiss()方法。
如果需要在对话框消失时执行某些操作,可以在DialogFragment中实现onDismiss()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值