前言
在开发过程中,我们会经常使用对话框,为了提高开发效率,于是我使用DialogFragment封装了一个通过的对话框。
为什么使用DialogFragment
首先在使用 DialogFragment之前,我们创建对话框一般都会采用Dialog的形式,并且从编写代码的角度来看,Dialog使用起来也较为简单,但Android 官方推荐使用 DialogFragment 来代替 Dialog。
DialogFragment 有着Dialog 所没有的特性在手机配置变化,导致Activity需要重新创建时,例如旋屏,基于DialogFragment的对话框将会由FragmentManager自动重建,然而基于Dialog实现的对话框则没有这样的能力),可以让它具有更高的可复用性(降低耦合)和更好的便利性。
通用DialogFragment代码:
class CommonDialog: DialogFragment() {
private var mLayoutResId = 0
private var mDimAmount = 0.5f //背景昏暗度
private var mShowBottomEnable= false //是否底部显示
private var mMargin = 0 //左右边距
private var mAnimStyle = 0 //进入退出动画
private var mOutCancel = true //点击外部取消
var mContext: Context? = null
private var mWidth = 0
private var mHeight = 0
private var convertListener:ViewConvertListener?=null
override fun onAttach(context: Context) {
super.onAttach(context)
mContext = context
}
override fun onCreate(@Nullable savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setStyle(STYLE_NO_TITLE, setDialogStyle())
}
@Nullable
override fun onCreateView(inflater: LayoutInflater, @Nullable container: ViewGroup?, @Nullable savedInstanceState: Bundle?): View? {
if (mLayoutResId>0){
val view: View = inflater.inflate(mLayoutResId, container, false)
convertListener?.convertView(DialogViewHolder.create(view), this)
return view
}
return null
}
override fun onStart() {
super.onStart()
initParams()
}