Flutter 页面嵌入原生AndroidView.

Posted 安果移不动

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Flutter 页面嵌入原生AndroidView.相关的知识,希望对你有一定的参考价值。

Flutter页面

代码如下

  final String viewType = 'banner_ad_exit_page';
      // Pass parameters to the platform side.
      final Map<String, dynamic> creationParams = <String, dynamic>{};
      var screenWidth = MediaQuery.of(context).size.width - 16;
      creationParams["banner_id"] =
          AGparams.networkParamsData!.pangolinBannerId;
      return [
        Container(
          width: screenWidth,
          height: screenWidth / 2,
          child: androidView(
            viewType: viewType,
            layoutDirection: TextDirection.ltr,
            creationParams: creationParams,
            creationParamsCodec: const StandardMessageCodec(),
          ),
        ),
        Divider()
      ];

 

 这段代码在...buildBanner中。

 

这里使用了SingleChildScrollView并写死了宽高。最后卸载了ShowModlalBottomSheet中。

看Android的代码

 

写到了两个类

NativeView 

这个用于加载穿山甲广告 并返回了这个FrameLayout

package dev.flutter.example

import android.content.Context
import android.graphics.Color
import android.view.View
import android.widget.FrameLayout
import android.widget.TextView
import com.anguomob.total.utils.ScreenUtil
import com.bytedance.sdk.openadsdk.AdSlot
import com.bytedance.sdk.openadsdk.TTAdNative
import com.bytedance.sdk.openadsdk.TTAdSdk
import com.bytedance.sdk.openadsdk.TTNativeExpressAd
import com.scwang.smartrefresh.layout.util.DensityUtil
import io.flutter.plugin.platform.PlatformView

internal class NativeView(context: Context, id: Int, creationParams: Map<String?, Any?>?) : PlatformView {
    private val frameLayout: FrameLayout

    override fun getView(): View {
        return frameLayout
    }

    override fun dispose() {}

    init {

        frameLayout= FrameLayout(context)
        val screenWidth= ScreenUtil.getScreenWidth(context)-DensityUtil.dp2px(16F);
        val banner_id:String = creationParams?.get("banner_id") as String;
        val adSlot = AdSlot.Builder()
            .setCodeId(banner_id) //广告位id
            .setSupportDeepLink(true)
            .setAdCount(3) //请求广告数量为1到3条
            .setExpressViewAcceptedSize(
                screenWidth.toFloat(),
                screenWidth/2.toFloat()
            ) //期望模板广告view的size,单位dp
            .build()


        //step3:可选,强烈建议在合适的时机调用):申请部分权限,如read_phone_state,防止获取不了imei时候,下载类广告没有填充的问题。
        val mTTAdNative = TTAdSdk.getAdManager().createAdNative(context)
        //step5:请求广告,对请求回调的广告作渲染处理
        //step5:请求广告,对请求回调的广告作渲染处理
        mTTAdNative.loadBannerExpressAd(adSlot, object : TTAdNative.NativeExpressAdListener {
            override fun onError(code: Int, message: String) {
                frameLayout.removeAllViews()
            }

            override fun onNativeExpressAdLoad(ads: List<TTNativeExpressAd>) {
                if (ads.isEmpty()) {
//                    Log.e(TAG, "null????")
                    return
                }
                val mTTAd = ads[0]
                mTTAd.setSlideIntervalTime(30 * 1000)
                mTTAd.render()
                mTTAd.setExpressInteractionListener(object :
                    TTNativeExpressAd.ExpressAdInteractionListener {
                    //广告点击回调
                    override fun onAdClicked(view: View?, type: Int) {
//                        Log.e(TAG, "onAdClicked")
                    }

                    //广告展示回调
                    override fun onAdShow(view: View?, type: Int) {
//                        Log.e(TAG, "onAdShow")
                    }

                    //广告渲染失败回调
                    override fun onRenderFail(view: View?, msg: String?, code: Int) {
//                        Log.e(TAG, "onRenderFail")
//                        Log.e(TAG, "onRenderFail msg:$msg code $code")
                    }

                    //广告渲染成功回调
                    override fun onRenderSuccess(view: View?, width: Float, height: Float) {
//                        Log.e(TAG, " onRenderSuccess.-code=")
                        frameLayout.removeAllViews()
                        frameLayout.addView(view)
                    }
                })

            }
        })
    }
}

NativeViewFactory

这个是个工厂类实现较为简单

package dev.flutter.example

import android.content.Context
import android.view.View
import io.flutter.plugin.common.StandardMessageCodec
import io.flutter.plugin.platform.PlatformView
import io.flutter.plugin.platform.PlatformViewFactory

class NativeViewFactory : PlatformViewFactory(StandardMessageCodec.INSTANCE) {
    override fun create(context: Context, viewId: Int, args: Any?): PlatformView {
        val creationParams = args as Map<String?, Any?>?
        return NativeView(context, viewId, creationParams)
    }
}

在对应的Flutter页面的  

configureFlutterEngine 

新增如下代码

    override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
        super.configureFlutterEngine(flutterEngine)

        flutterEngine
            .platformViewsController
            .registry
            .registerViewFactory("banner_ad_exit_page", NativeViewFactory())

    }

然后就可以调用到了。如果觉得没有广告但是又想试下 可以替换成TextView 并setText 然后看效果。

 

以上是关于Flutter 页面嵌入原生AndroidView.的主要内容,如果未能解决你的问题,请参考以下文章

Flutter基础系列之混合开发

如何在flutter中嵌入原生android apis?

Android原生嵌入Flutter模块

Android原生嵌入Flutter模块

Flutter 注册原生广告工厂

flutter跳转原生页面后的穿透问题