美文网首页
Flutter plugin 如何在插件中获取FragmentA

Flutter plugin 如何在插件中获取FragmentA

作者: Pino | 来源:发表于2024-09-19 11:48 被阅读0次

    插件类继承 ActivityAware,重写onAttachedToActivity、onDetachedFromActivityForConfigChanges、onReattachedToActivityForConfigChanges、onDetachedFromActivity四个方法,其中在onAttachedToActivity、onReattachedToActivityForConfigChanges可以获取到getActivity

    public class MyFfPlugin implements FlutterPlugin, MethodCallHandler, ActivityAware {}
    
    @Override
      public void onAttachedToActivity(@NonNull ActivityPluginBinding binding) {
         activity =  binding.getActivity();
      }
    

    那么如何获取FragmentActivity呢?现在很多插件库都是需要用到FragmentActivity,如果传入activity 是不行的
    答案:找到 MainActivity


    image.png
    public class MainActivity extends FlutterActivity {
    
    }
    

    这里的FlutterActivity 显然是继承了Activity,所以你在插件onAttachedToActivity中拿到的就是Activity


    image.png

    如果你想拿到FragmentActivity,MainActivity就不能继承FlutterActivity ,而是继承FlutterFragmentActivity
    修改后

    import io.flutter.embedding.android.FlutterFragmentActivity;
    public class MainActivity extends FlutterFragmentActivity {
    
    }
    

    然后回到插件类中,把fragmentActivity 保存到顶部,方便其他方法使用

      @Override
      public void onAttachedToActivity(@NonNull ActivityPluginBinding binding) {
        if (binding.getActivity() instanceof FragmentActivity) {
          fragmentActivity = (FragmentActivity) binding.getActivity();
        }
      }
    

    相关文章

      网友评论

          本文标题:Flutter plugin 如何在插件中获取FragmentA

          本文链接:https://www.haomeiwen.com/subject/rhmoljtx.html