最近学习安卓的时候有个作业需要用到自定义对话框,所以写出来记录一下,常规的对话框使用就不写了,这里主要说下自定义的对话框,分为半自定义和完全自定义。
半自定义对话框
半自定义对话框的调用方法和普通对话框的相同,只需要给对话框设置一个View
即可。
![半自定义对话框]()
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| View view = getLayoutInflater().inflate(R.layout.activity_custom_dialog, null); final EditText etName = view.findViewById(R.id.et_name); final EditText etPassword = view.findViewById(R.id.et_password); AlertDialog dialog = new AlertDialog.Builder(this) .setIcon(R.mipmap.ic_launcher) .setTitle("半自定义对话框") .setView(view) .setNegativeButton("取消", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }) .setPositiveButton("确定", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }) .create(); dialog.show();
|
注意,需要先写一个XML布局文件,然后在代码第一行处调用,定义Dialog时使用setView()
方法传入一个view即可。
完全自定义对话框
完全自定义对话框即不使用系统定义的对话框,根据需要自己写一个对话框样式。
![完全自定义对话框]()
完全自定义对话框原理是继承Dialog
类,然后在代码中直接调用自定义的类即可。
自定义一个类继承Dialog
类:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
| public class CustomDialog extends Dialog {
private EditText etName; private EditText etPassword; private Button btnCancel; private Button btnOk;
public CustomDialog(@NonNull Context context) { super(context); }
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.activity_custom_dialog);
etName = findViewById(R.id.et_name); etPassword = findViewById(R.id.et_password); btnCancel = findViewById(R.id.btn_cancel); btnOk = findViewById(R.id.btn_ok);
btnCancel.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { dismiss(); } }); btnOk.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) {
} }); } }
|
在主界面中调用该类:
1 2
| CustomDialog customDialog = new CustomDialog(this); customDialog.show();
|
总结
半自定义对话框就是在常规的对话框中调用setView()
方法传入一个自定义的布局文件,而完全自定义对话框则是直接继承Dialog
类来实现。