android 在片段中实现bottomSheet行为

vjhs03f7  于 2024-01-04  发布在  Android
关注(0)|答案(2)|浏览(227)

我试图实现底部工作表行为的片段.这两点是需要implents i)调用一个片段到另一个按钮时被点击. ii)应用底部工作表行为的片段B,所以当我向下拖动片段可以隐藏/解散.目前我有两个片段A,B.我调用片段B在片段A的容器当按钮被点击.
但是当我试图实现第二点时,我得到了错误。在FrgmentB上,我只扩展了Fragment而不是Fragmentdialog。主要原因是我无法访问后台UI。

u4vypkhs

u4vypkhs1#

我以前也有同样的问题,我所做的是将片段更改为BottomSheetDialogFragment并做了一些更改。

piah890a

piah890a2#

我通过扩展DialogFragment()创建了一个服装BottomeSheetFragement。由于Jetpack Compose和BottomSheetDialogFragment()的一些问题,我没有像前面的评论中提到的那样使用BottomSheetDialogFragment。但是如果你根本没有使用Jetpack Compose或者没有遇到任何问题,我绝对推荐在我的解决方案之前使用BottomSheetDialogFragment()

  1. open class BottomSheetFragment : DialogFragment() {
  2. private lateinit var binding: BottomSheetFragmentBinding
  3. private var initialTouchY: Float = 0f
  4. private var currentOffset: Int = 0
  5. private var prevY: Int = 0
  6. private var initialHeight: Int = 0
  7. override fun onCreateView(
  8. inflater: LayoutInflater,
  9. container: ViewGroup?,
  10. savedInstanceState: Bundle?
  11. ): View? {
  12. binding = BottomSheetFragmentBinding.inflate(inflater, container, false)
  13. return binding.root
  14. }
  15. override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
  16. super.onViewCreated(view, savedInstanceState)
  17. dialog?.window?.setBackgroundDrawableResource(android.R.color.transparent)
  18. view.post {
  19. initialHeight = view.height
  20. }
  21. dialog?.window?.decorView?.setOnTouchListener(object : View.OnTouchListener {
  22. override fun onTouch(v: View?, event: MotionEvent): Boolean {
  23. when (event.action) {
  24. MotionEvent.ACTION_DOWN -> {
  25. initialTouchY = event.rawY
  26. return true
  27. }
  28. MotionEvent.ACTION_MOVE -> {
  29. dialog?.window?.attributes?.gravity = Gravity.BOTTOM
  30. val deltaY = (event.rawY - initialTouchY).toInt()
  31. val offsetBy = deltaY - prevY
  32. dialog?.window?.attributes?.dimAmount = (1 - (currentOffset.toFloat().div(initialHeight.toFloat()))) * 0.6f
  33. dialog?.window?.setLayout(
  34. WindowManager.LayoutParams.MATCH_PARENT,
  35. initialHeight
  36. )
  37. view.offsetTopAndBottom(offsetBy)
  38. currentOffset += offsetBy
  39. prevY = deltaY
  40. return true
  41. }
  42. MotionEvent.ACTION_UP -> {
  43. if (currentOffset < initialHeight * 0.4) {
  44. val resetValue = -currentOffset
  45. view.offsetTopAndBottom(resetValue)
  46. dialog?.window?.attributes?.dimAmount = 0.6f
  47. dialog?.window?.setLayout(
  48. WindowManager.LayoutParams.MATCH_PARENT,
  49. initialHeight
  50. )
  51. currentOffset = 0
  52. prevY = 0
  53. } else {
  54. dismiss()
  55. }
  56. v?.performClick()
  57. return true
  58. }
  59. }
  60. return false
  61. }
  62. })
  63. }
  64. override fun onStart() {
  65. super.onStart()
  66. val window: Window? = dialog?.window
  67. window?.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)
  68. window?.setGravity(Gravity.BOTTOM)
  69. }
  70. }

个字符

展开查看全部

相关问题