底部弹窗使用应该很多吧,最近在项目中频繁用到,索性就封装分享出来,像抖音的评论、分享,应用还是挺多的。
open class BaseBottomDialogFragment : BottomSheetDialogFragment() {
override fun onStart() {
super.onStart()
val dialogHeight = getDialogHeight(context!!)
// 点击外面允许取消
dialog.setCanceledOnTouchOutside(true)
dialog.window!!.setGravity(Gravity.BOTTOM)
val bottomSheetDialog = dialog as BottomSheetDialog
val view = bottomSheetDialog.window!!.findViewById<View>(android.support.design.R.id.design_bottom_sheet)
val layoutParams = view.layoutParams
layoutParams.height = dialogHeight
view.layoutParams = layoutParams
view.setBackgroundResource(R.color.transparent)
BottomSheetBehavior.from(view).peekHeight = getPeekHeight()
}
/**
* 得到屏幕的高
*
* @param context
* @return
*/
protected fun getScreenHeight(context: Context): Int {
val wm = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager
return (wm.defaultDisplay.height)
}
/**
* 底部弹窗的高度
* 子类可以自己实现,定义高度
*/
open fun getDialogHeight(context: Context) = (context.resources.displayMetrics.heightPixels * 0.6).toInt()
/**
* 底部弹窗弹出时的高度,需要注意的是如果PeekHeight大于tDialogHeight时,弹窗会显示不全
*/
open fun getPeekHeight() = (getScreenHeight(context!!) * 0.7).toInt()
}
这是我在项目中使用的底部弹窗list表:
abstract class BaseListBottomDialogFragment : BaseBottomDialogFragment() {
var headView: View? = null
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val rootView: View = inflater.inflate(getLayoutId(), container, false)
val llContent = rootView.findViewById<View>(R.id.ll_content) as LinearLayout
headView = setHeader(llContent)
if (headView != null) {
llContent.addView(headView, 0, headView!!.layoutParams)
}
val recyclerView = rootView.findViewById<View>(R.id.recyclerView) as RecyclerView
recyclerView.layoutManager = getLayoutManager(recyclerView)
recyclerView.adapter = getAdapter(recyclerView)
return rootView
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
}
override fun getPeekHeight(): Int {
return super.getPeekHeight()
}
open fun getLayoutId() = if (canHeadScroll()) {
R.layout.dialog_base_bottom_list_scroll
} else {
R.layout.dialog_base_bottom_list_unscroll
}
protected fun canHeadScroll() = false
protected abstract fun getLayoutManager(recyclerView: RecyclerView): RecyclerView.LayoutManager
/**
* 自定义Adapter
*
* @param recyclerView
* @return
*/
protected abstract fun getAdapter(recyclerView: RecyclerView): RecyclerView.Adapter<*>?
/**
* 添加头布局
*
* @param container
* @return
*/
open fun setHeader(container: ViewGroup): View? {
return null
}
}
当然不只是RecyclerView,也可以是ViewPager,但是ViewPager会影响弹窗的滑动闭关,暂时还有找到解决方案。