-
系列文章
flutter與原生交互傳值OC/java版(一)
flutter與原生交互傳值OC/java版(二)
四步實(shí)現(xiàn)flutter顯示iOS原生組件OC/java版(三)
四步實(shí)現(xiàn)flutter顯示安卓原生組件OC/java版(三)
本demo的github地址:https://github.com/iBinbro/flutterstudy
四步實(shí)現(xiàn)flutter顯示安卓原生組件
一、安卓端的實(shí)現(xiàn)
1.新建原生組件(我是iOS開發(fā)...)
/// 原生的組件
class NVView extends TextView {
public NVView(Context context, Object arg) {
super(context);
setText("我是安卓原生組件" + arg);
}
}
2.新建一個(gè)繼承PlatformView類 返回具體的原生組件
/// 一個(gè)繼承PlatformView類 返回具體的原生組件
class NVPlatformView implements PlatformView {
Context context;
Object args;
NVPlatformView(Context context, Object args) {
this.context = context;
this.args = args;
}
/// 這里返回原生組件
@Nullable
@Override
public View getView() {
Log.d("args", "args = " + args);
return new NVView(context, args);
}
@Override
public void dispose() {
Log.d("銷毀", "NVPlatformView 銷毀 自動(dòng)釋放的");
}
}
3.新建一個(gè)工廠類 返回 PlatformView 類實(shí)例
/// 新建一個(gè)工廠類 返回 PlatformView 類實(shí)例
class NVPlatformViewFactory extends PlatformViewFactory {
/// 與flutter中 creationParams creationParamsCodec 對(duì)應(yīng) 不實(shí)現(xiàn)此方法args則為null
public NVPlatformViewFactory() {
super(StandardMessageCodec.INSTANCE);
}
@NonNull
@Override
public PlatformView create(Context context, int viewId, @Nullable Object args) {
//args 根據(jù)這個(gè)參數(shù)可以返回不同的view
return new NVPlatformView(context, args);
}
}
4.原生代碼里注冊(cè)插件以及注冊(cè)步驟3中創(chuàng)建的NVPlatformViewFactory
這里比iOS多一步猖毫,需要再創(chuàng)建一個(gè)實(shí)現(xiàn)FlutterPlugin
的類范咨,然后再注冊(cè)NVPlatformViewFactory
/**********flutter顯示原生組件flutter**********/
public class NVPlugin implements FlutterPlugin {
@Override
public void onAttachedToEngine(@NonNull FlutterPluginBinding binding) {
binding.getPlatformViewRegistry().registerViewFactory("nvview", new NVPlatformViewFactory());
}
@Override
public void onDetachedFromEngine(@NonNull FlutterPluginBinding binding) {
}
}
public class MainActivity extends FlutterActivity {
//其他代碼...
//注冊(cè)插件 核心代碼
@Override
public void configureFlutterEngine(@NonNull FlutterEngine flutterEngine) {
super.configureFlutterEngine(flutterEngine);
//添加插件
flutterEngine.getPlugins().add(new NVPlugin());
}
//其他代碼...
}
flutter側(cè)的代碼
Container(
width: 100,
height: 100,
color: Colors.red,
child: AndroidView(
viewType: "nvview",
creationParams: 2,
creationParamsCodec: StandardMessageCodec(),
),
)