总结flutter玩转之-fluuter 调用安卓原生view(使用AndroidView)
1.假设你已经熟悉fluuter 开发熟悉dart 语言 android 原生开发技能
1、在安卓原生项目添加代码
1.创建一个原生view 比如说TextView 继承自flutterSdk 中的PlatformView(io.flutter.plugin.platform.PlatformView)
package com.example.flutter_demo2022;
import android.content.Context;
import android.graphics.Color;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import androidx.annotation.Nullable;
import java.util.Map;
import io.flutter.plugin.platform.PlatformView;
public class MyView implements PlatformView {
Context context;
int viewId;
Map<String, Object> params;
TextView textView;
public MyView(Context context, int viewId, Map<String, Object> params) {
this.context = context;
this.viewId = viewId;
this.params = params;
textView = new TextView(context);
Log.d("gsc", "得到的参数=》" + params + textView.getLayoutParams());
textView.setText("我是安卓原生的TextView" + params.get("ss"));
}
@Nullable
@Override
public View getView() {
return textView;
}
@Override
public void dispose() {
//销毁view
}
}
2.创建一个viewFactory 类继承PlatformViewFactory(io.flutter.plugin.platform.PlatformViewFactory)
public class MyViewFactory extends PlatformViewFactory {
BinaryMessenger messenger;
public MyViewFactory(BinaryMessenger messenger) {
super(StandardMessageCodec.INSTANCE);
this.messenger = messenger;
}
@NonNull
@Override
public PlatformView create(@Nullable Context context, int viewId, @Nullable Object args) {
Map<String, Object> params = (Map<String, Object>) args;
return new MyView(context, viewId, params);
}
}
3.创建一个 FlutterPlugin 实现 io.flutter.embedding.engine.plugins.FlutterPlugin
public class FlutterPlugin implements io.flutter.embedding.engine.plugins.FlutterPlugin {
@Override
public void onAttachedToEngine(@NonNull FlutterPluginBinding binding) {
BinaryMessenger binaryMessenger = binding.getBinaryMessenger();
//你注册的原生组件名字plugins.flutter.io/custom_platform_view 在flutter 代码会用到要一致才能调用到这个view
binding.getPlatformViewRegistry().registerViewFactory("plugins.flutter.io/custom_platform_view", new MyViewFactory(binaryMessenger));
}
@Override
public void onDetachedFromEngine(@NonNull FlutterPluginBinding binding) {
}
}
4.在宿主的app中注册(也就是fluuter页面的主页面activity中)
class MainActivity : FlutterActivity() {
override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
super.configureFlutterEngine(flutterEngine)
flutterEngine.plugins.add(FlutterPlugin())
}
}
5.在flutter中dart 代码中添加此view
AndroidView(
viewType: "plugins.flutter.io/custom_platform_view", //和你注册的名字一致
creationParams: {"ss": 333}, //传递参数
creationParamsCodec: StandardMessageCodec(),
);
下期将介绍安卓view 承载flutter 的页面姿势O(∩_∩)O哈哈~