Android学习记录

Flutter调原生View

2020-10-08  本文已影响0人  旺仔_100

之前写过通过MethodChannel来调取原生方法。https://www.jianshu.com/p/6b677ff3350e
但是这次是直接在Flutter里面调用一个android view。

一、Flutter项目中嵌入单个的Android View,步骤如下:

package com.example.flutter_demo

import android.content.Context
import android.view.View
import android.widget.TextView
import io.flutter.plugin.common.BinaryMessenger
import io.flutter.plugin.platform.PlatformView
class MyFlutterView(context: Context,messager : BinaryMessenger,
viewId: Int,argus: Map<String,Any>) : PlatformView{
    var  text : TextView =  TextView(context)
    init {
        text.text = "原生的textvieww"
    }
    override fun getView(): View {
        return text
    }

    override fun dispose() {
    }

}
package com.example.flutter_demo

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

class MyFlutterViewFactory(private val messager : BinaryMessenger) : PlatformViewFactory(StandardMessageCodec.INSTANCE) {
    override fun create(context: Context?, viewId: Int, args: Any?): PlatformView {
        return MyFlutterView(context!!, messager,viewId,args as Map<String,Any>)
    }

}
package com.example.flutter_demo

import io.flutter.embedding.engine.plugins.FlutterPlugin

class MyPlugin : FlutterPlugin{
    override fun onAttachedToEngine(binding: FlutterPlugin.FlutterPluginBinding) {
        var binaryMessenger = binding.binaryMessenger
        binding.platformViewRegistry.registerViewFactory( "plugins.flutter.io/custom_platform_view",
        MyFlutterViewFactory(binaryMessenger))
    }
    companion object{
        @JvmStatic
        fun registerWith(registry: io.flutter.plugin.common.PluginRegistry.Registrar){
            registry.platformViewRegistry().registerViewFactory("plugins.flutter.io/custom_platform_view",
                    MyFlutterViewFactory(registry.messenger()))
        }
    }

    override fun onDetachedFromEngine(binding: FlutterPlugin.FlutterPluginBinding) {
    }

}
package com.example.flutter_demo

import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.engine.FlutterEngine

class MainActivity: FlutterActivity() {
    
    
    override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
        super.configureFlutterEngine(flutterEngine)
        flutterEngine.plugins.add(MyPlugin())
    }
}

到此为止,android端的代码完成。再看下flutter端怎么调用android view

getwidget7(){
  if(defaultTargetPlatform == TargetPlatform.android){
    return AndroidView(viewType: "plugins.flutter.io/custom_platform_view",creationParams: {"ss":333},
    creationParamsCodec: StandardMessageCodec(),);
  }
}

其中viewType和原生里面保持一致,creationParams是给原生传递参数的。
直接运行就可以实现在flutter里面使用android view。tip:注意使用真机,我在使用模拟器的时候跑不起来。

调用原生view可以和调用原生方法一起用。

上一篇下一篇

猜你喜欢

热点阅读