如何在Flutter插件中使用Android Fragment?

6
我需要将原生代码iOS/Android创建的SDK包装到Flutter中。在Android端,如果要实现自定义视图,则我的Fragment或Activity需要扩展SDK Fragment或Activity上的一些功能。 我的问题是如何将SDK Fragment或Activity包装在Flutter插件中,并使用我的插件在flutter项目侧扩展它?换句话说,我想要一个小部件,可以使用我的插件扩展Fragment或Activity,以在SDK中显示小部件UI。
在插件中使用FlutterFragment、FlutterActivity是正确的方式吗?
我的意思是: Flutter项目(小部件)< - > Flutter插件(附加到本机SDK Fragment或Activity的FlutterFragment或FlutterActivity)
如果不是,有什么可能的解决方案?

如果您认为 @pddthinh 的回答对您有帮助,请接受它。 - Lucas van Dongen
嗨,@piczaj,你能帮我吗?如果你有办法做到这一点,请告诉我。 - Mostafa Mahmoud
请查看此答案,它可能会有所帮助:https://dev59.com/X1MI5IYBdhLWcg3w0fB7#76133974 - Mostafa Mahmoud
1个回答

4

我曾经遇到过同样的问题,这是我的解决方案:

  • Implement a FlutterPlugin that supports ActivityAware, refer to this FlutterPlugin with ActivityAware on how to cache the Activity, as well as MethodCallHandler (to communicate with the FlutterWidget app).

  • Implement a MethodCall e.g. SHOW_NATIVE_FRAGMENT in which it will attach the native fragment. Note: need to dynamically add a View as a container for the fragment

         int id = 0x123456;
         ViewGroup.LayoutParams vParams = new FrameLayout.LayoutParams(
                 ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT
         );
         FrameLayout container = new FrameLayout(context);
         container.setLayoutParams(vParams);
         container.setId(id);
         activity.addContentView(container, vParams);
    
  • Then attach the Fragment to the Activity

        FragmentManager fm = ((FragmentActivity) activity).getSupportFragmentManager();
        fm.beginTransaction()
            .replace(id, nativeFragment)
            .commitAllowingStateLoss();
  • 当你完成 Fragment 的操作后,记得用 success() 或者 error() 调用 MethodChannel.Result,否则 FlutterWidget 将永远被阻塞。
  • 在 FlutterWidget 方面,使用 MethodChannel 进行调用。
        static Future<void> showNativeFragment() async {
            await _channel.invokeMethod("SHOW_NATIVE_FRAGMENT");
        }

同时,确保你的FlutterWidget应用程序Activity继承自FlutterFragmentActivity

当将其转换为FragmentActivity时,我遇到了一个错误:“MainActivity无法转换为androidx.appcompat.app.AppCompatActivity”。 - Derek Hannah
@DerekHannah,也许你之所以会出现那个错误是因为你的MainActivity基类是其他东西,而不是FragmentActivity。在我的情况下,MainActivityFlutterFragmentActivity的子类。 - pddthinh
我有一个相似的问题,我正在使用Flutter平台视图,在其中我想显示一个片段。问题是,如果我使用activity.addContentView(container, vParams),它会成为整个应用程序的主要布局,我无法看到Flutter UI。如果我不执行addContentView,则不会触发一些片段的生命周期,并且片段UI无法正常工作。 - Afzal Ali

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接