How to build your own PresenterShape using UIPresenter ๐Ÿ’ป

ยท

1 min read

How to build your own PresenterShape using UIPresenter ๐Ÿ’ป

To create our own PresenterShape, let's start with a simple example, where we make our Presenter the same size as our LifecyclerOwner's (Activity or Fragment) decorView. We'll call it DecorViewShape :

/**
 * This [PresenterShape] has the shape of a shadowed Rectangle, with the same size as
 * the decorView
 * @author Kevin Germain
 * */
class DecorViewShape : PresenterShape() {

    override fun shapeContains(x: Float, y: Float): Boolean {
        // Made to return true in this simple case, so that any click events
        // on the [Presenter] be considered as : Presenter.STATE_FOCAL_PRESSED
        return true
    }

    override fun buildSelfWith(builder: UIPresenter) {

        val decorView = builder.resourceFinder.getDecorView()

        hasShadowedWindow = builder.hasShadowedWindow

        if (hasShadowedWindow) {
            viewToPresentBounds.inset(-4f, -4f)
            decorView.getGlobalVisibleRect(decorViewCoordinates)
            shadowedWindow.set(decorViewCoordinates)
        }

        builder.viewToPresent!!.getGlobalVisibleRect(vTPCoordinates)
        viewToPresentBounds.set(vTPCoordinates)

        if (builder.hasShadowLayer) {
            builder.shadowLayer.apply {
                shapeBackgroundPaint.setShadowLayer(radius, dx, dy, shadowColor)
            }
        }
    }

    override fun onDrawInPresenterWith(canvas: Canvas?) {
        canvas?.apply {
            save()
            if (hasShadowedWindow) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) clipOutRect(viewToPresentBounds)
                else clipRect(viewToPresentBounds, Region.Op.DIFFERENCE)
                drawRect(shadowedWindow, shadowedWindowPaint)
            }
            restore()
        }
    }
}

Now all you have to do to apply this PresenterShape is:

    private fun presentAnimalsText() {
        UIPresenter(activity = this).set(
            presenterShape = DecorViewShape(),
            viewToPresentId = R.id.animalsText,
            descriptionText = "",
            presenterStateChangeListener = { _, _ -> }
        )
    }

Here's how the Presenter looks with the DecorViewShape() :

Screenshot_1641334818.png

ย