UiUtils.kt 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. package im.angry.openeuicc.util
  2. import android.content.res.Resources
  3. import android.graphics.Rect
  4. import android.view.View
  5. import android.view.ViewGroup
  6. import androidx.appcompat.app.AppCompatActivity
  7. import androidx.appcompat.widget.Toolbar
  8. import androidx.core.view.ViewCompat
  9. import androidx.core.view.WindowInsetsCompat
  10. import androidx.core.view.updateLayoutParams
  11. import androidx.core.view.updatePadding
  12. import androidx.fragment.app.DialogFragment
  13. import im.angry.openeuicc.common.R
  14. // Source: <https://stackoverflow.com/questions/12478520/how-to-set-dialogfragments-width-and-height>
  15. /**
  16. * Call this method (in onActivityCreated or later) to set
  17. * the width of the dialog to a percentage of the current
  18. * screen width.
  19. */
  20. fun DialogFragment.setWidthPercent(percentage: Int) {
  21. val percent = percentage.toFloat() / 100
  22. val dm = Resources.getSystem().displayMetrics
  23. val rect = dm.run { Rect(0, 0, widthPixels, heightPixels) }
  24. val percentWidth = rect.width() * percent
  25. dialog?.window?.setLayout(percentWidth.toInt(), ViewGroup.LayoutParams.WRAP_CONTENT)
  26. }
  27. /**
  28. * Call this method (in onActivityCreated or later)
  29. * to make the dialog near-full screen.
  30. */
  31. fun DialogFragment.setFullScreen() {
  32. dialog?.window?.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)
  33. }
  34. fun AppCompatActivity.setupToolbarInsets() {
  35. val spacer = requireViewById<View>(R.id.toolbar_spacer)
  36. ViewCompat.setOnApplyWindowInsetsListener(requireViewById(R.id.toolbar)) { v, insets ->
  37. val bars = insets.getInsets(
  38. WindowInsetsCompat.Type.systemBars()
  39. or WindowInsetsCompat.Type.displayCutout()
  40. )
  41. v.updateLayoutParams<ViewGroup.MarginLayoutParams> {
  42. topMargin = bars.top
  43. }
  44. v.updatePadding(bars.left, v.paddingTop, bars.right, v.paddingBottom)
  45. spacer.updateLayoutParams {
  46. height = v.top
  47. }
  48. WindowInsetsCompat.CONSUMED
  49. }
  50. }
  51. fun setupRootViewInsets(view: View) {
  52. ViewCompat.setOnApplyWindowInsetsListener(view) { v, insets ->
  53. val bars = insets.getInsets(
  54. WindowInsetsCompat.Type.systemBars()
  55. or WindowInsetsCompat.Type.displayCutout()
  56. )
  57. // Don't set padding bottom because we do want scrolling root views to extend into nav bar
  58. v.updatePadding(bars.left, v.paddingTop, bars.right, v.paddingBottom)
  59. WindowInsetsCompat.CONSUMED
  60. }
  61. }