Android控件大全(一)——DialogFragment创建对话框

时间:2021-07-15 13:58:36

DialogFragment在android 3.0时被引入。是一种特殊的Fragment,用于在Activity的内容之上展示一个模态的对话框。典型的用于:展示警告框,输入框,确认框等等。

在DialogFragment产生之前,我们创建对话框:一般采用AlertDialog和Dialog。注:官方不推荐直接使用Dialog创建对话框。

先来看个DialogFragment的定义

 public class MyDialogFragment extends DialogFragment {
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
getDialog().requestWindowFeature(Window.FEATURE_NO_TITLE);//取消标题栏
return inflater.inflate(R.layout.dialog_layout,null);
} @NonNull
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
return new AlertDialog.Builder(getActivity()).setIcon(R.mipmap.ic_launcher).setTitle("标题").setMessage("hhhhhhhhhhhhhhhh").setPositiveButton("确认", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) { }
}).setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) { }
}).create();
}
}

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