),
// 新建显示
Container(
padding: EdgeInsets.symmetric(vertical: 5.0, horizontal: 10),
width: 130.0,
height: 100.0,
child: NativeViewExample(),
)
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: ‘Increment’,
child: Icon(Icons.add),
), // This trailing comma makes auto-formatting nicer for build methods.
);
}
到了这里,flutter代码基本上修改完毕
再来看看原生工程的修改。
在flutter_module_composition/.android/Flutter下,新建NativeView,实现PlatformView接口,如:
package com.hb.flutter;
//省略各种导包…
public class NativeView implements PlatformView {
@NonNull
private final TextView textView;
NativeView(@NonNull Context context, int id, @Nullable Map<String, Object> creationParams) {
textView = new TextView(context);
textView.setTextSize(25);
textView.setGravity(Gravity.CENTER);
textView.setBackgroundColor(Color.rgb(100,200,200));
textView.setText(“native view”);
}
@NonNull
@Override
public View getView() {
return textView;
}
@Override
public void dispose() {
}
}
还需要创建一个工厂类来创建之前创建的实例 NativeView
package com.hb.flutter;
//省略各种导包…
public class NativeViewFactory extends PlatformViewFactory {
@NonNull
private final BinaryMessenger messenger;
@NonNull private final View containerView;
public NativeViewFactory(@NonNull BinaryMessenger messenger, @NonNull View containerView) {
super(StandardMessageCodec.INSTANCE);
this.messenger = messenger;
this.containerView = containerView;
}
@NonNull
@Override
public PlatformView create(@NonNull Context context, int id, @Nullable Object args) {
final Map<String, Object> creationParams = (Map<String, Object>) args;
return new NativeView(context, id, creationParams);
}
}
最后,注册平台视图。这可以在应用程序或插件中完成。
在宿主工程里面新建平台视图,修改MainActivity方法如下
public class MainActivity extends FlutterActivity {
@Override
public void configureFlutterEngine(@NonNull FlutterEngine flutterEngine) {
flutterEngine
.getPlatformViewsController()
.getRegistry()
.registerViewFactory(“platform-view-type”, new NativeViewFactory(null, null));
}
}
最后效果如图:
大功告成,中间显示的’Rendered on a native Android view’就是来着Android的平台视图。
我们来看一下