DialogFragment在android 3.0时被引入。是一种特殊的Fragment,用于在Activity的内容之上展示一个模态的对话框。典型的用于:展示警告框,输入框,确认框等等。
在DialogFragment产生之前,我们创建对话框:一般采用AlertDialog和Dialog。注:官方不推荐直接使用Dialog创建对话框。
先来看个DialogFragment的定义
1 public class MyDialogFragment extends DialogFragment { 2 @Nullable 3 @Override 4 public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { 5 getDialog().requestWindowFeature(Window.FEATURE_NO_TITLE);//取消标题栏 6 return inflater.inflate(R.layout.dialog_layout,null); 7 } 8 9 @NonNull 10 @Override 11 public Dialog onCreateDialog(Bundle savedInstanceState) { 12 return new AlertDialog.Builder(getActivity()).setIcon(R.mipmap.ic_launcher).setTitle("标题").setMessage("hhhhhhhhhhhhhhhh").setPositiveButton("确认", new DialogInterface.OnClickListener() { 13 @Override 14 public void onClick(DialogInterface dialog, int which) { 15 16 } 17 }).setNegativeButton("取消", new DialogInterface.OnClickListener() { 18 @Override 19 public void onClick(DialogInterface dialog, int which) { 20 21 } 22 }).create(); 23 } 24 }
onCreateView:解析一个布局文件到Dialog中 onCreateDialog:添加一个AlertDialog到Dialog中
两个方法重写一个即可,正常人一般都不会两个都重写吧?貌似会报错。。。。。
Dialog与Activity交互
自定义一个接口,Activity实现该接口,将getActivity()强转成该接口即可。
public Dialog onCreateDialog(Bundle savedInstanceState) { View v=LayoutInflater.from(getActivity()).inflate(R.layout.dialog_layout,null); final EditText username= (EditText) v.findViewById(R.id.username); final EditText password= (EditText) v.findViewById(R.id.password); return new AlertDialog.Builder(getActivity()).setView(v).setIcon(R.mipmap.ic_launcher).setTitle("标题").setPositiveButton("确认", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Log.i("com.alger","po+"+which); ((ILoginListener)getActivity()).Login(username.getText().toString(),password.getText().toString()); } }).setNegativeButton("取消", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Log.i("com.alger","ne+"+which); } }).create(); }
http://blog.csdn.net/huangyabin001/article/details/30053835
Dialog位置动画等参考 :http://blog.csdn.net/maxwell0401/article/details/52336893