googleads / googleads-mobile-android-examples

googleads-mobile-android
Apache License 2.0
1.68k stars 1.86k forks source link

Native advanced with Jetpack Compose (Example Request) #450

Open OleksandrGrument opened 2 years ago

OleksandrGrument commented 2 years ago

Hello, can you please provide us an example how to use Native advanced add with Jetpack compose. Right now it is totally unclear about how to migrate existing code to compose. Thanks https://developers.google.com/admob/android/native/advanced

OleksandrGrument commented 2 years ago

Hello, to use Template view with compose you have to add aditional constructor to TemplateView. Where templateType is layout for add.

   // Custom workaround for compose
    public TemplateView(Context context, int templateType) {
        super(context);

        this.templateType =  templateType;

        LayoutInflater inflater =
                (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        inflater.inflate(templateType, this);

        nativeAdView = findViewById(R.id.native_ad_view);
        primaryView = findViewById(R.id.primary);
        secondaryView = findViewById(R.id.secondary);
        tertiaryView = findViewById(R.id.body);

        ratingBar = findViewById(R.id.rating_bar);
        ratingBar.setEnabled(false);

        callToActionView = findViewById(R.id.cta);
        iconView = findViewById(R.id.icon);
        mediaView = findViewById(R.id.media_view);
        background = findViewById(R.id.background);
    }

And call template view as AndroidView

              AndroidView(
                            modifier = Modifier
                                .padding(1.dp)
                                .fillMaxWidth(),
                            factory = { context ->

                                val nativeAddStyleBuilder = NativeTemplateStyle
                                    .Builder()

                                val layout =
                                    com.google.android.ads.nativetemplates.R.layout.gnt_medium_template_view
                                TemplateView(context, layout).apply {
                                    setStyles(nativeAddStyleBuilder.build())
                                }
                            },
                            update = { view ->

                                nativeAd?.let {
                                    view.setNativeAd(it)
                                }
                            }
                        )

I hope it will be helpfull to someone. Anyway it will be great to have official example!