自学内容网 自学内容网

【Flutter 内嵌 android 原生 View以及相互跳转】

Flutter 内嵌 android 原生 View以及相互跳转

一. 内嵌android 原生View

  1. 在android 工程的包名下,也可在MainActivity创建 android 原生view ,继承PlatformView
    // 1.自定义textview
    public static class MyTextView implements PlatformView{

     private TextView textView ;
    
     /**
      *
      * @param context
      * @param messenger 用于消息传递
      * @param id 生成时会分配一个唯一 ID
      * @param maps Flutter 传递的初始化参数。
      */
     public MyTextView(Context context ,BinaryMessenger messenger,int id,Map<String,Object> maps) {
         textView = new TextView(context);
         textView.setText("我是来自android原生的textView");
         if (maps != null){
             String text = maps.get("text").toString();
             textView.setText(text);
         }
    
         textView.setTextColor(Color.RED);
     }
    
     // 返回要嵌入 Flutter 层次结构的Android View
     @Nullable
     @Override
     public View getView() {
         return textView;
     }
    
     //释放此View时调用,此方法调用后 View 不可用,此方法需要清除所有对象引用,否则会造成内存泄漏。
     @Override
     public void dispose() {
    
     }
    

    }

  2. 新建MyViewFactory.java注册PlatformView

public class MyViewFactory extends PlatformViewFactory {
    private final BinaryMessenger messenger;

    public MyViewFactory(BinaryMessenger messenger) {
        super(StandardMessageCodec.INSTANCE);
        this.messenger = messenger;
    }

    @SuppressWarnings("unchecked")
    @Override
    public PlatformView create(Context context, int id, Object args) {
        Map<String, Object> params = (Map<String, Object>) args;
        return new MainActivity.MyTextView(context, messenger, id, params);
    }

}
  1. 创建plugin
public class MyViewFlutterPlugin implements FlutterPlugin {



    @Override
    public void onAttachedToEngine(@NonNull FlutterPluginBinding binding) {
        BinaryMessenger binaryMessenger = binding.getBinaryMessenger();
        binding.getPlatformViewRegistry().registerViewFactory(
                "plugins.nightfarmer.top/myview",
                new MyViewFactory(binaryMessenger));
    }

    @Override
    public void onDetachedFromEngine(@NonNull FlutterPluginBinding binding) {

    }
}
  1. 在MainActivy 中注册
    @Override
    public void configureFlutterEngine(@NonNull FlutterEngine flutterEngine) {
        super.configureFlutterEngine(flutterEngine);
        flutterEngine.getPlugins().add(new MyViewFlutterPlugin());
    }
  1. 在flutter 中使用

              Container(
                width: 100,
                height: 100,
                child:  AndroidView(
                  viewType: "plugins.nightfarmer.top/myview",
                  creationParams: {'text':'Flutter传给AndroidTextView的参数'},
                  creationParamsCodec: StandardMessageCodec(),
                ),
              ),

二、android 与 flutter 相互跳转

  1. flutter 挑战到 原生Activity
  var platform = MethodChannel('com.example.flutter/native_channel');

  void goToNativeActivity() {
    platform.invokeMethod('goToNative');
  }

在MainActivty 中注册通道跳转到TestActivity

 private static final String CHANNEL = "com.example.flutter/native_channel";

    @Override
    public void configureFlutterEngine(@NonNull FlutterEngine flutterEngine) {
        super.configureFlutterEngine(flutterEngine);
        flutterEngine.getPlugins().add(new MyViewFlutterPlugin());

        //注册通道
        new MethodChannel(flutterEngine.getDartExecutor().getBinaryMessenger(), CHANNEL).setMethodCallHandler(
                (call, result) -> {
                    // 接收来自Flutter的方法调用
                    if (call.method.equals("goToNative")) {
                        Intent intent = new Intent(MainActivity.this, TestActivity.class);
                        startActivity(intent);
                        result.success(true);
                    } else {
                        result.notImplemented();
                    }
                }
        );
    }
  1. Activity 中跳转Flutter页面
    在Manifest.xml 中注册
<activity
  android:name="io.flutter.embedding.android.FlutterActivity"
  android:theme="@style/LaunchTheme"
  android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
  android:hardwareAccelerated="true"
  android:windowSoftInputMode="adjustResize"
  />

根据路由跳转到Flutter 页面

        startActivity(
                   FlutterActivity
                       .withNewEngine()
                      .initialRoute("/my_route")
//        .withCachedEngine("engine_id")
                        .build(currentActivity)
       );

跳转会与 2s的黑屏情况,在MyApp中

public class MyApp extends Application {

    private FlutterEngine fe ;

    @Override
    public void onCreate() {
        super.onCreate();

        // 解决原生挑战到 flutter 会有2s 黑屏 的问题
        fe = new FlutterEngine(this);
        fe.getDartExecutor().executeDartEntrypoint(DartExecutor.DartEntrypoint.createDefault());
        FlutterEngineCache.getInstance().put("engine_id",fe);
    }

    //当application 销毁的时候调用
    @Override
    public void onTerminate() {
        //销毁flutter引擎
        fe.destroy();
        super.onTerminate();
    }
}

在清单文件中注册 MyApp

 <application
        android:name="com.qxx.ai_score_manager_flutter.MyApp">

原文地址:https://blog.csdn.net/baidu_38477614/article/details/143574566

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!