You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

MvvmCross中Fragment修改Activity主题时Inflate异常求助

解决MvvmCross Fragment修改主题时MvxSpinner绑定上下文为空的异常

这个异常的核心原因很明确:你使用原生ContextThemeWrapper创建的上下文没有携带MvvmCross所需的绑定上下文(BindingContext),而MvxSpinner在初始化时依赖从当前上下文中获取绑定上下文,找不到就会抛出这个错误。

下面给你两个可行的解决方案:

方案一:使用MvvmCross自带的MvxContextThemeWrapper

MvvmCross专门提供了MvxContextThemeWrapper类,它会自动继承并传递原上下文的绑定上下文,完美适配MvvmCross控件的初始化需求。修改你的代码如下:

public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) 
{ 
    View view = null; 
    if(FragmentId == Resource.Layout.my_form) 
    { 
        // 替换原生ContextThemeWrapper为MvxContextThemeWrapper
        var contextThemeWrapper = new MvxContextThemeWrapper(Activity, Resource.Style.MyTheme_IntakeForm); 
        LayoutInflater localInflater = inflater.CloneInContext(contextThemeWrapper); 
        view = localInflater.Inflate(Resource.Layout.my_form, container, false); 
    }
    return view;
}

方案二:手动注入绑定上下文

如果方案一不符合你的场景(比如你需要自定义上下文包装逻辑),可以手动将Fragment的绑定上下文附加到新的上下文环境中:

public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) 
{ 
    View view = null; 
    if(FragmentId == Resource.Layout.my_form) 
    { 
        var contextThemeWrapper = new ContextThemeWrapper(Activity, Resource.Style.MyTheme_IntakeForm); 
        // 将当前Fragment的绑定上下文设置为当前上下文的活跃绑定上下文
        MvxAndroidBindingContextHelpers.CurrentBindingContext = this.BindingContext;
        LayoutInflater localInflater = inflater.CloneInContext(contextThemeWrapper); 
        view = localInflater.Inflate(Resource.Layout.my_form, container, false); 
    }
    return view;
}

额外注意事项

  • 确保你的Fragment继承自MvxFragment(而非原生Android Fragment),这样才能拥有BindingContext属性并自动管理绑定上下文生命周期。
  • 如果你是在自定义Fragment中使用,需要确保绑定上下文已经被正确初始化并推入栈中。

内容的提问来源于stack exchange,提问作者Chanki

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 07:00:55