由于半透明背景,androidx.mediarouter.app.MediaRouteButton抛出android.view.InflateException

问题描述

最近几天我一直在开发Flutter插件。我正在尝试将现有的媒体播放器实现为颤动的小部件。但是,由于媒体播放器的SDK在播放器视图中使用MediaRouteButtons,所以在尝试对其进行充气时会得到android.view.InflateException

核心原因是因为背景不能半透明。我尝试通过自定义主题或使用具有不透明背景的内置主题来设置主要活动的colorPrimary。这没有效果,并且该错误持续存在。

我怀疑Flutter在混音中添加了自己的主题,这是造成问题的原因,但是我找不到任何有用的信息。

SDK本身不是问题,因为我正在使用仅MediaRouteButton的空视图测试相同的功能。 这是我的布局:

<androidx.mediarouter.app.MediaRouteButton
        android:id="@+id/media_route_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>

我正在创建一个PlatformView,并且在构造函数中,我试图使视图膨胀。这是构造函数,而LayoutInflater是引发异常的那个。

FlutterPlayerView(Context context,BinaryMessenger messenger,int id) {
        this.channel = new MethodChannel(messenger,CHANNEL + id);
        this.channel.setMethodCallHandler(this);
        View view = LayoutInflater.from(context).inflate(R.layout.button_view,null);
        this.buttonView = view.findViewById(R.id.media_route_button);
    }

这是我尝试使用的自定义主题

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
        <item name="android:colorPrimary">#FFFFFFFF</item>
    </style>
</resources>

我通过使用MainActivity.java插件清单和应用清单中甚至在生成setTheme()活动中对其进行了设置。

似乎没有任何帮助,因此任何线索都将是巨大的。如果有人了解Flutter如何设置插件Activity主题,将不胜感激。

解决方法

我通过设置context传递给我的PlatforView构造函数的活动的主题来解决了这个问题

之前

FlutterPlayerView(Context context,BinaryMessenger messenger,int id) {
    this.channel = new MethodChannel(messenger,CHANNEL + id);
    this.channel.setMethodCallHandler(this);
    View view = LayoutInflater.from(context).inflate(R.layout.button_view,null);
    this.buttonView = view.findViewById(R.id.media_route_button);
}

之后

FlutterPlayerView(Context context,CHANNEL + id);
    this.channel.setMethodCallHandler(this);
        
    // android:colorPrimary is opaque in AppTheme
    context.setTheme(R.style.AppTheme); 
    View view = LayoutInflater.from(context).inflate(R.layout.button_view,null);
    this.buttonView = view.findViewById(R.id.media_route_button);
}

还有一种方法可以通过在Flutter插件中实现ActivityAware接口并覆盖onAttachedToActivityonRettachedToActivity方法来实现。

例如:

public class YourFlutterPlugin implements FlutterPlugin,ActivityAware{
    //...

    @Override
    public void onAttachedToActivity(@NonNull ActivityPluginBinding binding) {
        Context context = binding.getActivity();
        // Your code for sending the context to the view
        // Example:  platformView.setContext(context);
    }

    @Override
    public void onReattachedToActivity(@NonNull ActivityPluginBinding binding) {
        Context context = binding.getActivity();
        // Your code for sending the context to the view
        // Example:  platformView.setContext(context);
    }

  // ...
}