6

I know it's possible to use a custom view instead of a basic map marker in Google Maps doing what's described in this answer. I was curious if it was possible to achieve a similar affect with Compose?

Since ComposeView is a final class, couldn't extend that directly so I was thinking of having a FrameLayout that could add it as a child. Although this seems to be causing a race condition since composables draw slightly differently from normal android Views.

class MapMarkerView : FrameLayout {

    constructor(context: Context) : super(context) {
        initView()
    }

    constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) {
        initView()
    }

    private fun initView() {
        val composeView = ComposeView(context).apply {
            layoutParams = LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)
        }
        composeView.setContent {
            // this runs asynchronously making the the bitmap generation not include composable at runtime?
            Text(text = "2345", modifier = Modifier.background(Color.Green, RoundedCornerShape(4.dp)))
        }
        addView(composeView)
    }

}

Most articles I have read have some callback function for generating a bitmap like this which wouldn't necessarily work in this use case where each view is generated dynamically and needed to be converted to a bitmap right away for the map.

Andrew Steinmetz
  • 1,010
  • 8
  • 16

1 Answers1

0

The MapMarkerView you are attempting to create is an indirect child of ViewGroup. ComposeView is also an indirect child of ViewGroup which means you can directly substitute a ComposeView in places where you intend to use this class. The ComposeView class is not meant to be subclassed. The only thing you really need to be concerned with as a developer is its setContent method.

val composeView: View = ComposeView(context).apply{
   setContent {
       Text(text = "2345", modifier = Modifier.background(Color.Green, RoundedCornerShape(4.dp)))
   }
}
 

Now you can replace the MapMarkerView with this composeView in your code or even use it at any location where a View or any of it's subclasses is required.

Rafsanjani
  • 4,352
  • 1
  • 14
  • 21
  • 1
    This is a good point as far as not needing to have a wrapper FrameLayout, although this still won't solve the async nature of compose when trying to generate a bitmap when making a custom google map marker. – Andrew Steinmetz Jan 12 '22 at 17:46
  • hey @AndrewSteinmetz were you able to find a way to use Composable func and turn it into a MapMarker? – M.Baraka Aug 02 '23 at 14:41