AlertDialog
Android中最常用的对话框是AlertDialog,它可以完成常见的交互操作,如提示、确认、选择等等,然后就是进度对话框ProgressDialog(参见《 Android开发笔记(四十九)异步任务处理AsyncTask》)。AlertDialog没有公开的构造函数,必须借助于AlertDialog.Builder才能完成参数设置。Builder的常用方法如下:
setIcon : 设置标题的图标。
setTitle : 设置标题的文本。
setCustomTitle : 设置自定义的标题视图。
--以上方法用于设置标题部分。注意setTitle和setCustomTitle只能设置其一,不能重复设置。
setMessage : 设置内容的文本。
setView : 设置自定义的内容视图。
setAdapter : 设置List方式的内容视图。使用较麻烦,一般不用。
setItems : 设置Spinner方式的内容视图。窗口显示与对话框模式的Spinner极为相似,没有底部的按钮,一旦选中某项就立即关闭对话框。
setSingleChoiceItems : 设置单选列表的内容视图。与setItems的区别在于有显示底部的交互按钮,并且每项右边有单选按钮。
setMultiChoiceItems : 设置多选列表的内容视图。底部有交互按钮,并且每项右边有复选按钮。
--以上方法用于设置内容部分。注意这些方法互相冲突,同时只能设置其一。
setPositiveButton : 设置肯定按钮的信息,如文本、点击监听器。
setNegativeButton : 设置否定按钮的信息,如文本、点击监听器。
setNeutralButton : 设置中性按钮的信息,如文本、点击监听器。
--以上方法用于设置交互按钮。
通过Builder设置完参数,还需调用create方法才能生成AlertDialog对象。不过要想在页面上显示AlertDialog,还得调用该对象的show方法。
Dialog
实际开发中,AlertDialog往往还是无法满足个性化的要求,比如布局不够灵活、按钮的样式无法定制等等,所以常常得自己自定义对话框。查看AlertDialog源码,发现它继承自Dialog,所以自定义对话框的思路就是基于Dialog进行拓展。下面是Dialog的常用方法:Dialog构造函数 : 可定义对话框的主题样式(样式在styles.xml中定义)。如是否有标题、是否为半透明、对话框的背景等等。
isShowing : 判断对话框是否显示。
show : 显示对话框。
hide : 隐藏对话框。
dismiss : 关闭对话框。
setCancelable : 设置对话框是否可取消。
setCanceledOnTouchOutside : 点击对话框外部区域,是否自动关闭对话框。默认会自动关闭
getWindow : 获取对话框的界面对象。
其中getWindow方法是自定义对话框的关键,首先获取到对话框所在的界面对象,才能往这个界面上添加定制视图。废话少说,直接上个自定义对话框的代码例子作为说明:
import com.example.exmdialog.R;
import android.app.Dialog;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.TextView;
public class CustomDialog implements OnClickListener {
private final static String TAG = "CustomDialog";
private Dialog dialog;
private View view;
private TextView tv_title;
private TextView tv_message;
private Button btn_ok;
private OnCustomListener mOnCustomListener;
public CustomDialog(Context context) {
view = LayoutInflater.from(context).inflate(R.layout.dialog_custom, null);
dialog = new Dialog(context, R.style.CustomDialog);
tv_title = (TextView) view.findViewById(R.id.tv_title);
tv_message = (TextView) view.findViewById(R.id.tv_message);
btn_ok = (Button) view.findViewById(R.id.btn_ok);
btn_ok.setOnClickListener(this);
}
public void setTitle(String title) {
tv_title.setText(title);
}
public void setMessage(String message) {
tv_message.setText(message);
}
public void setOnCustomListener(OnCustomListener listener) {
mOnCustomListener = listener;
}
public interface OnCustomListener {
public void onClick();
}
public void show() {
dialog.getWindow().setContentView(view);
dialog.getWindow().setLayout(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);