前言
DialogFragment什么鬼?什么DialogFragment,不就是Dialog和Fragment配合的使用么?哎,还真像那回事!!!
我们进入正题:Android 官方推荐使用 DialogFragment 来代替 Dialog ,可以让它具有更高的可复用性(降低耦合)和更好的便利性(很好的处理屏幕翻转的情况)。
用法以及优缺点
创建 DialogFragment 有两种方式:
覆写其 onCreateDialog 方法 — ① 利用AlertDialog或者Dialog创建出Dialog。
覆写其 onCreateView 方法 — ② 使用定义的xml布局文件展示Dialog。
虽然这两种方式都能实现相同的效果,但是它们各有自己适合的应用场景:
方法 ①,一般用于创建替代传统的 Dialog 对话框的场景,UI 简单,功能单一。
方法 ②,一般用于创建复杂内容弹窗或全屏展示效果的场景,UI 复杂,功能复杂,一般有网络请求等异步操作。
另外它又是Fragment,所以当旋转屏幕和按下后退键时可以更好的管理其声明周期,它和Fragment有着基本一致的声明周期。
详细的使用分析
1.覆写其 onCreateDialog 方法
我们来创建一个最简单的AlertDialog来完成这里的操作。写一个MyAlertDialogFragment
实现都在这个里面。
public class MyAlertDialogFragment extends DialogFragment {
public MyAlertDialogFragment() {
}
public static MyAlertDialogFragment newInstance(String tittle) {
MyAlertDialogFragment fragment = new MyAlertDialogFragment();
Bundle bundle = new Bundle();
bundle.putString("tittle", tittle);
fragment.setArguments(bundle);
return fragment;
}
@NonNull
@Override
public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {
String tittle = getArguments().getString("tittle");
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle(tittle);
builder.setMessage("删除歌曲?");
builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
Toast.makeText(getContext(), "确定", Toast.LENGTH_SHORT).show();
}
});
builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
Toast.makeText(getContext(), "取消", Toast.LENGTH_SHORT).show();
}
});
return builder.create();
}
}
然后在MainActivity
里面进行相应的操作,代码如下:
MyAlertDialogFragment fragment = MyAlertDialogFragment.newInstance("你的样子");
fragment.show(getSupportFragmentManager(), "myAlert");
实现效果如下:
onCreateDialog的实现
2.覆写其 onCreateView 方法
首先新建一个布局文件res/layout/fragment_edit_name.xml
,详细布局如下:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="@+id/lbl_your_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Your name" />
<EditText
android:id="@+id/txt_your_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:imeOptions="actionDone"
android:inputType="text" />
</LinearLayout>
用EditNameDialogFragment
实现相应的代码。
public class EditNameDialogFragment extends DialogFragment {
public EditNameDialogFragment() {
}
public static EditNameDialogFragment newInstance(String tittle) {
EditNameDialogFragment fragment = new EditNameDialogFragment();
Bundle bundle = new Bundle();
bundle.putString("tittle", tittle);
fragment.setArguments(bundle);
fragment.setArguments(bundle);
return fragment;
}
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
@Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_edit_name, container, false);
return view;
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
String tittle = getArguments().getString("tittle");
((EditText) view.findViewById(R.id.txt_your_name)).setText(tittle);
super.onViewCreated(view, savedInstanceState);
}
}
然后在MainActivity
里面进行相应的操作,代码如下:
EditNameDialogFragment editNameDialogFragment = EditNameDialogFragment.newInstance("名字");
editNameDialogFragment.show(getSupportFragmentManager(), "edit");
实现效果如下:
onCreateView 的实现效果
这个效果让我不太满意啊!!
3.全屏效果
我说了上面的效果我不太满意。那怎么办??
首先在onResume
里面处理
@Override
public void onResume() {
ViewGroup.LayoutParams params = getDialog().getWindow().getAttributes();
params.width = WindowManager.LayoutParams.MATCH_PARENT;
params.height = WindowManager.LayoutParams.MATCH_PARENT;
getDialog().getWindow().setAttributes((WindowManager.LayoutParams) params);
super.onResume();
}
然后运行APP得到下面的样子,没有全屏啊!
我们继续处理:我们处理一下
padding
和background
,在文件res\values\styles.xml
中添加下面的代码:
<style name="Dialog.FullScreen" parent="Theme.AppCompat.Dialog">
<item name="android:padding">0dp</item>
<item name="android:windowBackground">@android:color/transparent</item>
</style>
然后在MainActivity
里面进行相应的操作,代码如下:
EditNameDialogFragment editNameDialogFragment = EditNameDialogFragment.newInstance("名字");
editNameDialogFragment.setStyle(DialogFragment.STYLE_NORMAL, R.style.Dialog_FullScreen);
editNameDialogFragment.show(getSupportFragmentManager(), "edit");
得到的结果如下图:
下面我们来修改一下
MyAlertDialogFragment
里面的代码,实现对话框在下面并且是宽度全屏的效果,代码如下:
@NonNull
@Override
public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {
String tittle = getArguments().getString("tittle");
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle(tittle);
builder.setMessage("删除歌曲?");
builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
Toast.makeText(getContext(), "确定", Toast.LENGTH_SHORT).show();
}
});
builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
Toast.makeText(getContext(), "取消", Toast.LENGTH_SHORT).show();
}
});
AlertDialog alertDialog = builder.create();
// 设置宽度为屏宽、位置在屏幕底部
Window window = alertDialog.getWindow();
window.setBackgroundDrawableResource(android.R.color.white);
window.getDecorView().setPadding(0, 0, 0, 0);
WindowManager.LayoutParams wlp = window.getAttributes();
wlp.gravity = Gravity.BOTTOM;
wlp.width = WindowManager.LayoutParams.MATCH_PARENT;
wlp.height = WindowManager.LayoutParams.WRAP_CONTENT;
window.setAttributes(wlp);
return alertDialog ;
}
我们只需要修改onCreateDialog
里面的方法就能满足需求。得到的结果如下图所示:
除了上面的全屏之外,我们还可以指定对话框的大小,代码如下:
int width = getResources().getDimensionPixelSize(R.dimen.popup_width);
int height = getResources().getDimensionPixelSize(R.dimen.popup_height);
getDialog().getWindow().setLayout(width, height);
//最主要的就是 setLayout(width, height),在合适的时机处理相应的大小。
4.传递数据给Activity
我们使用接口的方式进行传值。我们在MyAlertDialogFragment
进行相应的处理,具体的代码如下:
public class MyAlertDialogFragment extends DialogFragment {
public MyAlertDialogFragment() {
}
public interface ConfirmListener {
void onClickComplete(String tittle);
}
public static MyAlertDialogFragment newInstance(String tittle) {
MyAlertDialogFragment fragment = new MyAlertDialogFragment();
Bundle bundle = new Bundle();
bundle.putString("tittle", tittle);
fragment.setArguments(bundle);
return fragment;
}
@NonNull
@Override
public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {
final String tittle = getArguments().getString("tittle");
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle(tittle);
builder.setMessage("删除歌曲?");
builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
ConfirmListener confirmListener = (ConfirmListener) getActivity();
confirmListener.onClickComplete(tittle);
}
});
builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
}
});
AlertDialog alertDialog = builder.create();
// 设置宽度为屏宽、位置靠近屏幕底部
Window window = alertDialog.getWindow();
window.setBackgroundDrawableResource(android.R.color.white);
window.getDecorView().setPadding(0, 0, 0, 0);
WindowManager.LayoutParams wlp = window.getAttributes();
wlp.gravity = Gravity.BOTTOM;
wlp.width = WindowManager.LayoutParams.MATCH_PARENT;
wlp.height = WindowManager.LayoutParams.WRAP_CONTENT;
window.setAttributes(wlp);
return alertDialog;
}
}
在MianActivity
要实现ConfirmListener
接口,部分代码如下:
public class MainActivity extends AppCompatActivity implements MyAlertDialogFragment.ConfirmListener {
..............
@Override
public void onClickComplete(String tittle) {
Toast.makeText(this, "标题:" + tittle, Toast.LENGTH_SHORT).show();
}
}
上面的代码就可以把值传递给Activity。
5.屏幕旋转的问题
屏幕旋转前屏幕旋转后
上面的图就可以解答所有的疑惑,我们没有做任何的特殊处理,上面的tittle,就是我们从Activity传过来的。
6.Styling Dialogs 样式对话框
Styling Custom Dialog 下面的来自android_guides,感兴趣的可以去看这一篇文章。写的非一般的感觉!!!
<style name="AppThemeDialog" parent="Theme.AppCompat.Light">
<!-- Apply default style for dialogs -->
<item name="android:dialogTheme">@style/AppDialogTheme</item>
<!-- Apply default style for alert dialogs -->
<item name="android:alertDialogTheme">@style/AppAlertTheme</item>
</style>
<!-- Define your custom dialog theme here extending from base -->
<style name="AppDialogTheme" parent="Theme.AppCompat.Light.Dialog">
<!-- Define color properties as desired -->
<item name="colorPrimary">@color/dark_blue</item>
<item name="colorAccent">@color/dark_blue</item>
<item name="colorPrimaryDark">#000</item>
<item name="colorControlNormal">@color/dark_blue</item>
<item name="android:textColorHighlight">@color/light_blue</item>
<!-- Define window properties as desired -->
<!--是否显示title-->
<item name="android:windowNoTitle">false</item>
<!--是否是全屏-->
<item name="android:windowFullscreen">false</item>
<!--背景颜色-->
<item name="android:windowBackground">@color/medium_green</item>
<!--是否浮现在activity之上-->
<item name="android:windowIsFloating">true</item>
<!--点击空白是否消失-->
<item name="android:windowCloseOnTouchOutside">true</item>
</style>
<!-- Define your custom alert theme here extending from base -->
<style name="AppAlertTheme" parent="Theme.AppCompat.Light.Dialog.Alert">
<item name="colorPrimary">@color/dark_blue</item>
<item name="colorAccent">@color/dark_blue</item>
<item name="colorPrimaryDark">#000</item>
<item name="colorControlNormal">@color/dark_blue</item>
<item name="android:textColorHighlight">@color/light_blue</item>
</style>
对话框中Titlebar
的样式使用"android:windowTitleStyle"
属性,代码如下:
<style name="AppTheme" parent="Theme.AppCompat.Light">
<!-- Apply default style for dialogs -->
<item name="android:dialogTheme">@style/AppDialogTheme</item>
<!-- Apply default style for alert dialogs -->
<item name="android:alertDialogTheme">@style/AppAlertTheme</item>
</style>
<style name="AppDialogTheme" parent="Theme.AppCompat.Light.Dialog">
<item name="android:windowTitleStyle">@style/DialogWindowTitle</item>
<!-- ...other stuff here... -->
</style>
<style name="AppAlertTheme" parent="Theme.AppCompat.Light.Dialog.Alert">
<item name="android:windowTitleStyle">@style/DialogWindowTitle</item>
<!-- ...other stuff here... -->
</style>
<!--下面是详细的使用-->
<style name="DialogWindowTitle" parent="Base.DialogWindowTitle.AppCompat">
<item name="android:background">@color/light_green</item>
<item name="android:gravity">center</item>
<item name="android:textAppearance">@style/DialogWindowTitleText</item>
</style>
<style name="DialogWindowTitleText" parent="@android:style/TextAppearance.DialogWindowTitle">
<item name="android:textSize">24sp</item>
</style>
移除标题栏:
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
Dialog dialog = super.onCreateDialog(savedInstanceState);
// request a window without the title
dialog.getWindow().requestFeature(Window.FEATURE_NO_TITLE);
return dialog;
}
//或者如下的代码:
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setStyle(DialogFragment.STYLE_NO_TITLE,R.style.AppTheme);
}
6.软键盘尺寸的调整
首先在AndroidManifest.xml
进行处理,代码如下:
<activity android:name=".MainActivity"
android:windowSoftInputMode="adjustResize">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
接下来是Fragment
里面的操作:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle bundle) {
// Set to adjust screen height automatically, when soft keyboard appears on screen
getDialog().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
return inflater.inflate(R.layout.fragment_edit_name, container);
}
//或者是下面的代码
@NonNull
@Override
public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {
......
AlertDialog alertDialog = builder.create();
alertDialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
return alertDialog;
}
总结
上面的文章写的我认为一般般,但是基本可以满足相应的需求。
参考文章:
https://github.com/codepath/android_guides/wiki/Using-DialogFragment
https://likfe.com/2016/10/27/dialog-fragment/
https://blog.csdn.net/lmj623565791/article/details/37815413
网友评论