添加片段容器视图后 Android 膨胀布局崩溃

2024-01-18

目前我有一个扩展 AppCompatActivity 的自定义抽屉活动,如下所示:

public class DrawerActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener{
    
    ...

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        super.setContentView(R.layout.activity_drawer);

        ...
    }


    @Override
    public void setContentView(int layoutResID) {
        frameLayout = findViewById(R.id.drawer_frame);
        LayoutInflater.from(getApplicationContext()).inflate(layoutResID, frameLayout);
        super.setContentView(drawerLayout);
    }

    ...
}

正如您在此处所看到的,我覆盖了 setContentView 方法,因此扩展此抽屉活动的活动的布局 id 将被传递到此方法中,并在抽屉活动的子视图中膨胀。简而言之,我希望扩展此抽屉活动的所有活动都将具有导航抽屉。它非常适合一般活动。

但现在,我有一个包含片段容器视图并扩展抽屉活动的活动。当我启动此活动时,应用程序崩溃并出现以下错误:

E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.aaa, PID: 10730
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.aaa/com.example.aaa.gym.GymActivity}: android.view.InflateException: Binary XML file line #29 in com.example.aaa:layout/activity_gym: Binary XML file line #29 in com.example.aaa:layout/activity_gym: Error inflating class androidx.fragment.app.FragmentContainerView
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3635)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3792)
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:103)
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2210)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loopOnce(Looper.java:201)
        at android.os.Looper.loop(Looper.java:288)
        at android.app.ActivityThread.main(ActivityThread.java:7839)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:548)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1003)
     Caused by: android.view.InflateException: Binary XML file line #29 in com.example.aaa:layout/activity_gym: Binary XML file line #29 in com.example.aaa:layout/activity_gym: Error inflating class androidx.fragment.app.FragmentContainerView
     Caused by: android.view.InflateException: Binary XML file line #29 in com.example.aaa:layout/activity_gym: Error inflating class androidx.fragment.app.FragmentContainerView
     Caused by: java.lang.reflect.InvocationTargetException
        at java.lang.reflect.Constructor.newInstance0(Native Method)
        at java.lang.reflect.Constructor.newInstance(Constructor.java:343)
        at android.view.LayoutInflater.createView(LayoutInflater.java:858)
        at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:1010)
        at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:965)
        at android.view.LayoutInflater.rInflate(LayoutInflater.java:1127)
        at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:1088)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:686)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:538)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:485)
        at com.example.aaa.DrawerActivity.setContentView(DrawerActivity.java:57)
        at com.example.aaa.gym.GymActivity.onCreate(GymActivity.java:62)
        at android.app.Activity.performCreate(Activity.java:8051)
        at android.app.Activity.performCreate(Activity.java:8031)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1329)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3608)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3792)
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:103)
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2210)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loopOnce(Looper.java:201)
        at android.os.Looper.loop(Looper.java:288)
        at android.app.ActivityThread.main(ActivityThread.java:7839)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:548)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1003)
     Caused by: java.lang.UnsupportedOperationException: FragmentContainerView must be within a FragmentActivity to use android:name="com.example.aaa.gym.PlaceFragment"
E/AndroidRuntime:     at androidx.fragment.app.FragmentContainerView.<init>(FragmentContainerView.java:142)
        at androidx.fragment.app.FragmentContainerView.<init>(FragmentContainerView.java:120)
            ... 28 more

正如您在这里所看到的,根本原因是java.lang.UnsupportedOperationException: FragmentContainerView must be within a FragmentActivity to use android:name="com.example.aaa.gym.PlaceFragment"。但是,该 Activity 应该能够膨胀片段,因为它扩展了 DrawerActivity,并且 DrawerActivity 扩展了 AppCompatActivity,而 AppCompatActivity 又扩展了 Fragment Activity。我对此很困惑。

这是活动代码:

public class GymActivity extends DrawerActivity implements OnMapReadyCallback, GoogleMap.OnMarkerClickListener {

    private ActivityGymBinding binding;
    
    ...

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        markers = new ArrayList<>();

        binding = ActivityGymBinding.inflate(getLayoutInflater());

        // here crashes, the actual crash line is the second line of the drawer activity's setContentView
        setContentView(binding.getRoot().getSourceLayoutResId()); 

        ...

    }
    
    ...
}

这是活动 xml

<?xml version="1.0" encoding="utf-8"?>

<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/mapLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".gym.GymActivity">


    <com.google.android.gms.maps.MapView
        android:id="@+id/mapView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:contentDescription="@string/title_activity_gym"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <androidx.fragment.app.FragmentContainerView
        android:id="@+id/place_fragment"
        android:name="com.example.aaa.gym.PlaceFragment"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        tools:layout="@layout/place_fragment" />

</androidx.constraintlayout.widget.ConstraintLayout>

而片段,几乎没有任何改变

public class PlaceFragment extends Fragment {

    private PlaceViewModel mViewModel;
    private PlaceFragmentBinding binding;

    public static PlaceFragment newInstance() {
        return new PlaceFragment();
    }

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {

        mViewModel = new ViewModelProvider(requireActivity()).get(PlaceViewModel.class);

        mViewModel.getName().observe(getViewLifecycleOwner(), s -> binding.name.setText(s));
        mViewModel.getLocation().observe(getViewLifecycleOwner(), s -> binding.location.setText(s));

        return inflater.inflate(R.layout.place_fragment, container, false);
    }
}

fragment.xml,只是一个简单的framelayout

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".gym.PlaceFragment">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/name"
        android:text="Hello" />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/location"
        android:text="Hello" />

</FrameLayout>

谁能明白为什么我的应用程序崩溃了?任何建议将不胜感激。


问题就在这里:

LayoutInflater.from(getApplicationContext()).inflate(layoutResID, frameLayout);

您正在使用应用程序上下文 - 具体来说not您的 Activity,因此不使用 Activity 的主题,您的 Application 类也不扩展FragmentActivity。你会想要使用LayoutInflater.from(this)实际使用您的 Activity 作为布局充气器。

然而,虽然这可以解决你的崩溃问题,但你的GymActivity由于这些行,仍然无法工作:

binding = ActivityGymBinding.inflate(getLayoutInflater());

// here crashes, the actual crash line is the second line of the drawer activity's setContentView
setContentView(binding.getRoot().getSourceLayoutResId()); 

在这里,您创建一个binding对象,但从未真正将其添加到您的 Activity 中。相反,您可以拨打您的setContentView覆盖该视图的全新实例。这意味着您的任何更改binding永远不会反映在您的用户界面中。

相反,您想要提供对您的setContentView这需要一个View并打电话addView在您的 FrameLayout 上将已经膨胀的视图添加到您的布局中。

@Override
public void setContentView(View view) {
    frameLayout = findViewById(R.id.drawer_frame);
    frameLayout.addView(view)
    // Note you should never be calling super.setContentView here.
    // You've already called it in your own onCreate()
}

这可以让你像这样使用它:

binding = ActivityGymBinding.inflate(getLayoutInflater());

setContentView(binding.getRoot()); 
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

添加片段容器视图后 Android 膨胀布局崩溃 的相关文章

随机推荐

  • 带有 React Hooks 的 HoC

    我正在尝试从class component to react hooks with Context API 我无法弄清楚出现错误的具体原因是什么 首先 我的代码 contexts sample jsx import React create
  • OWL/XML 读取问题

    我在使用 Jena 从 Java 读取 OWL XML 文件时遇到问题 我读取 RDF XML 文件没有问题 但每当我从 Protege 创建 OWL XML 文件并尝试读取它时 Java 都会给出以下错误 警告 主要 RDFDefault
  • 如何在 Ruby 中关闭和删除文件?

    假设我在 Ruby 中打开一个文件 如下所示 f File open diagram txt r 现在 为了关闭并删除该文件 我有以下代码 begin f File open diagram txt r ensure if f nil Fi
  • 如何在插件中访问 Maven 的依赖关系层次结构

    在我的插件中 我需要处理依赖关系层次结构并获取有关每个依赖关系以及是否已排除的信息 groupId artifactId 版本等 做这个的最好方式是什么 依赖插件有树目标 http maven apache org plugins mave
  • 如何列出Excel中三列中值的所有可能组合?

    我有三列 每一列都有不同类型的主数据 如下所示 现在 我想要这三个单元格的所有可能组合 就像 aa kk jj aa kk ff aa ll jj aa ll ff aa mm jj 这可以用公式来完成吗 我发现一个公式有 2 列 但我无法
  • Typescript - 基于另一个属性的条件属性

    定义类型时 我们可以根据另一个属性来使一个属性成为必需的吗 一个例子是 type Parent children Child childrenIdSequence string Only make this required when ch
  • 当键盘出现时向上移动视图

    问题 我有一个ViewController有一个子类UIScrollView in it 在scrollView中有3个UITextFields 其中 2 个带有数字键盘 1 个带有UIPickerView键盘 问题是当键盘出现时 它会隐藏
  • 如何退出 win32com 上的 Outlook?

    我有一个检查我的 Outlook 文件夹的脚本 不便的是 我的 Outlook 可能已经打开 或者如果没有打开 脚本将在后台为我打开 Outlook 我想简化它 以便如果我的 Outlook 已打开 则保留它 如果它是由脚本调度的 请随后退
  • DAG 在 RDD 中是如何工作的?

    The 火花研究论文 http www cs berkeley edu matei papers 2012 nsdi spark pdf提出了一种基于经典 Hadoop MapReduce 的新分布式编程模型 声称在许多情况下 特别是在机器
  • “git pull --all”可以更新我所有的本地分支吗?

    我经常有至少 3 个远程分支 master staging 和 production 我有 3 个本地分支来跟踪这些远程分支 更新我所有的本地分支机构很乏味 git fetch all git rebase origin master gi
  • 如何使用应用程序工厂正确设置 Flask-admin 视图?

    我正在尝试设置使用 SQLAlchemy 进行 Flask admin 模型视图 https flask admin readthedocs org en v1 0 9 quickstart model views反对 用户 和 角色 模型
  • 新的 JS SDK 与 OAuth 2.0 在 fbsr_ cookie 中保存子域?

    编辑 此错误已记录 并确认为脸书错误 https developers facebook com bugs 256155664428653 browse search 4e843e6d89a232275456793 现在已经修复了 我正在测
  • Robot Framework 使用 Robot Framework/selenium 获取后台调用

    我正在使用 selenium 测试一个 Web 应用程序 我想检查的是是否有在后台完成的调用 post get 例如我加载 google com 在开发人员选项中我可以看到它执行了一些请求 我调查了文档 https github com r
  • 如何检测ftp文件名是一个目录?

    在 Java 中 我试图删除 ftp 目录 但如果它不为空 我需要通过调用删除其中的所有文件和子目录files ftp dir 我可以从目录中获取列表 但如何判断列表中的项目之一是文件还是子目录 有没有files i IsDirectory
  • 在匿名函数内的公式中使用定额

    我尝试使用定额在自定义函数中传递变量名称以进行数据处理并在公式中使用 但我在公式中使用定额不正确 有没有更好的方法来取消引用公式中的参数 library dplyr library broom library purrr library t
  • 永久关闭 Eclipse 中的拼写检查

    每次在 Eclipse 中创建新工作区时 我都必须通过首选项关闭拼写检查 首选项 gt 常规 gt 编辑器 gt 文本编辑器 gt 拼写 gt 启用拼写检查 这非常令人恼火 如何永久关闭拼写检查 IE 当我创建新工作区时 拼写检查器被禁用
  • Python 3:我们可以在调用实例的多个方法时避免重复实例名称吗?

    我现在 或者我已经读到 它在 Python 2 x 中是不可能的 并且在 Python 3 中也找不到它 但也许我不知道如何搜索它 用一个简单的 Python 示例更容易解释它 for i in range 11 one turtle pe
  • 代理后面的 PyQt + QtWebkit

    我正在编写一个 PyQt 功能强大的 Qt 库的 Python 绑定 应用程序 并且我的应用程序的一小部分需要 Web 浏览器 提示 OAuth 所以我开始使用 QtWebkit 顺便说一下 它非常棒 唯一的问题是我想允许代理后面的用户使用
  • C# 通过多级数组仅根据Key名称查找JSON值

    我有各种输入 JSON 格式的数据 它们都包含特定的键名terminalSize 这是我唯一知道的作品 JSON 树的总数或确切深度terminalSizeJSON 树内部将永远是未知的并且可能会发生变化 我正在寻找一个 C 解决方案来循环
  • 添加片段容器视图后 Android 膨胀布局崩溃

    目前我有一个扩展 AppCompatActivity 的自定义抽屉活动 如下所示 public class DrawerActivity extends AppCompatActivity implements NavigationView