由于XML文件而导致类片段膨胀错误

如何解决由于XML文件而导致类片段膨胀错误

我有一个应用程序,我想使用一个活动的多片段方法。因此,为此,我实现了一个主要的活动类,该类应充当片段的容器。在这里,您可以看到它的XML布局文件(称为activity_main2):

<?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:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    tools:ignore="ExtraText">


    <com.google.android.material.bottomnavigation.BottomNavigationView
        android:id="@+id/bottom_navigation"
        app:labelVisibilityMode="labeled"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/colorGreen"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:menu="@menu/bottom_navigation"
        app:itemIconTint="@color/colorPrimaryDark"
        app:itemTextColor="@color/colorAccent"
        />

    <fragment
        android:id="@+id/fragment"
        android:name="androidx.navigation.fragment.NavHostFragment"
        android:layout_width="0dp"
        android:layout_height="0dp"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"
        app:defaultNavHost="true"
        app:navGraph="@navigation/nav_graph"
        tools:layout_editor_absoluteX="1dp"
        tools:layout_editor_absoluteY="1dp"
         />
</androidx.constraintlayout.widget.ConstraintLayout>

在这里您会看到它的Java文件:

package com.example.td.barapp;

import android.content.Intent;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;

import android.os.Bundle;

import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

import com.example.td.barapp.databinding.ActivityMain2Binding;
import com.example.td.barapp.databinding.ActivityMainBinding;


public class MainActivity extends AppCompatActivity  {


    private ActivityMain2Binding binding;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding=ActivityMain2Binding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());



    }

}

不幸的是,当我启动该应用程序时,该应用程序未启动,并且在logcat中,我收到以下错误消息堆栈:

2020-08-26 17:07:47.202 16384-16384/? E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.td.barapp,PID: 16384
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.td.barapp/com.example.td.barapp.MainActivity}: android.view.InflateException: Binary XML file line #25 in com.example.td.barapp:layout/activity_main2: Binary XML file line #25 in com.example.td.barapp:layout/activity_main2: Error inflating class fragment
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3449)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3601)
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)
        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:2066)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:223)
        at android.app.ActivityThread.main(ActivityThread.java:7656)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
     Caused by: android.view.InflateException: Binary XML file line #25 in com.example.td.barapp:layout/activity_main2: Binary XML file line #25 in com.example.td.barapp:layout/activity_main2: Error inflating class fragment
     Caused by: android.view.InflateException: Binary XML file line #25 in com.example.td.barapp:layout/activity_main2: Error inflating class fragment
     Caused by: androidx.fragment.app.Fragment$InstantiationException: Unable to instantiate fragment com.example.td.barapp.Menu_Fragment: could not find Fragment constructor
        at androidx.fragment.app.Fragment.instantiate(Fragment.java:563)
        at androidx.fragment.app.FragmentContainer.instantiate(FragmentContainer.java:57)
        at androidx.fragment.app.FragmentManager$3.instantiate(FragmentManager.java:390)
        at androidx.navigation.fragment.FragmentNavigator.instantiateFragment(FragmentNavigator.java:132)

因此,我在上面发布的activity_main2的XML布局文件据说有问题。我花了很多时间才弄清楚问题到底出在哪里。你能帮我吗?我真的很感谢您的评论,因为我不知道如何进行。感谢您的帮助。

更新:以下是Dev(请参阅下文)要求我发布的其他文件: 这是menu_fragment的Java文件:

package com.example.td.barapp;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.navigation.NavDirections;
import androidx.navigation.Navigation;

import com.example.td.barapp.databinding.FragmentMenuBinding;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link Menu_Fragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class Menu_Fragment extends Fragment implements View.OnClickListener {

    // TODO: Rename parameter arguments,choose names that match
    // the fragment initialization parameters,e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;



    private Menu_Fragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment Menu_Fragment.
     */
    // TODO: Rename and change types and number of parameters
    public static Menu_Fragment newInstance(String param1,String param2) {
        Menu_Fragment fragment = new Menu_Fragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1,param1);
        args.putString(ARG_PARAM2,param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }


    }

    private FragmentMenuBinding binding;
    @Override
    public View onCreateView(LayoutInflater inflater,ViewGroup container,Bundle savedInstanceState) {
        binding = FragmentMenuBinding.inflate(inflater,container,false);
        return binding.getRoot();
    }

    @Override
    public void onViewCreated(@NonNull View view,@Nullable Bundle savedInstanceState) {
        super.onViewCreated(view,savedInstanceState);
        binding.imageButtonCocktailsEn.setOnClickListener(this);
        binding.imageButtonCocktailsAlcfreeEn.setOnClickListener(this);
        binding.imageButtonLongdrinksEn.setOnClickListener(this);
        binding.imageButtonWhiskyEn.setOnClickListener(this);
        binding.imageButtonLiquorEn.setOnClickListener(this);
        binding.imageButtonBeerEn.setOnClickListener(this);
        binding.imageButtonSoftdrinksEn.setOnClickListener(this);
        binding.imageButtonHotDrinksEn.setOnClickListener(this);

    }

    public void onDestroyView() {
        super.onDestroyView();
        binding = null;
    }


    @Override
    public void onClick(View view) {

        if(view.getId() == R.id.imageButton_Softdrinks_en) {

            int amount = 1;
            Menu_FragmentDirections.ActionMenuFragmentToSoftdrinks action = Menu_FragmentDirections
                    .actionMenuFragmentToSoftdrinks(amount);

            Navigation.findNavController(view).navigate(action);



        }

    }
}

这里是菜单片段的XML布局文件:

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout 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:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".Menu_Fragment">

    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <androidx.appcompat.widget.Toolbar
            android:id="@+id/toolbar_mainActivity"
            android:layout_width="432dp"
            android:layout_height="135dp"
            android:background="#435cb53f"
            android:theme="@style/ThemeOverlay.AppCompat.ActionBar"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintVertical_bias="0.0"
            app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
            app:titleTextColor="@android:color/holo_green_light">

            <TextView
                android:id="@+id/textView_ToolBar_CocktailSelectionActivity"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginBottom="8dp"
                android:layout_marginEnd="8dp"
                android:layout_marginLeft="8dp"
                android:layout_marginRight="8dp"
                android:layout_marginStart="8dp"
                android:layout_marginTop="8dp"
                android:gravity="center"
                android:layout_gravity="center"
                android:textColor="@android:color/white"
                android:textSize="24sp"
                android:text="Drinks" />
        </androidx.appcompat.widget.Toolbar>

        <ScrollView
            android:layout_width="0dp"
            android:layout_height="0dp"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@id/toolbar_mainActivity">

            <androidx.constraintlayout.widget.ConstraintLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                tools:context=".MainActivity"
                tools:ignore="ExtraText">


                <ImageButton
                    android:id="@+id/imageButton_Cocktails_en"
                    android:layout_width="0dp"
                    android:layout_height="128dp"
                    android:layout_marginTop="12dp"
                    android:background="#00000000"
                    android:scaleType="fitCenter"
                    app:layout_constraintEnd_toStartOf="@id/imageButton_Cocktails_alcfree_en"
                    app:layout_constraintHorizontal_chainStyle="spread"
                    app:layout_constraintHorizontal_weight="1"
                    app:layout_constraintStart_toStartOf="parent"
                    app:layout_constraintTop_toTopOf="parent"
                    app:srcCompat="@drawable/menu_cocktails" />

                <ImageButton
                    android:id="@+id/imageButton_Cocktails_alcfree_en"
                    android:layout_width="0dp"
                    android:layout_height="128dp"
                    android:layout_marginTop="12dp"
                    android:background="#00000000"
                    android:scaleType="fitCenter"
                    app:layout_constraintEnd_toEndOf="parent"
                    app:layout_constraintHorizontal_weight="1"
                    app:layout_constraintStart_toEndOf="@id/imageButton_Cocktails_en"
                    app:layout_constraintTop_toTopOf="parent"
                    app:srcCompat="@drawable/menu_cocktails_acoholfree" />

                <ImageButton
                    android:id="@+id/imageButton_Longdrinks_en"
                    android:layout_width="0dp"
                    android:layout_height="128dp"
                    android:layout_marginTop="12dp"
                    android:background="#00000000"
                    android:scaleType="fitCenter"
                    app:layout_constraintEnd_toStartOf="@id/imageButton_Whisky_en"
                    app:layout_constraintStart_toStartOf="parent"
                    app:layout_constraintTop_toBottomOf="@id/imageButton_Cocktails_en"
                    app:layout_constraintVertical_chainStyle="packed"
                    app:srcCompat="@drawable/menu_longdrinks" />

                <ImageButton
                    android:id="@+id/imageButton_Whisky_en"
                    android:layout_width="0dp"
                    android:layout_height="128dp"
                    android:layout_marginTop="12dp"
                    android:background="#00000000"
                    android:scaleType="fitCenter"
                    app:layout_constraintEnd_toEndOf="parent"
                    app:layout_constraintStart_toEndOf="@id/imageButton_Longdrinks_en"
                    app:layout_constraintTop_toBottomOf="@id/imageButton_Cocktails_en"
                    app:srcCompat="@drawable/menu_whisky" />

                <ImageButton
                    android:id="@+id/imageButton_Liquor_en"
                    android:layout_width="0dp"
                    android:layout_height="128dp"
                    android:layout_marginTop="12dp"
                    android:background="#00000000"
                    android:scaleType="fitCenter"
                    app:layout_constraintEnd_toStartOf="@id/imageButton_Beer_en"
                    app:layout_constraintStart_toStartOf="parent"
                    app:layout_constraintTop_toBottomOf="@id/imageButton_Longdrinks_en"
                    app:layout_constraintVertical_chainStyle="packed"
                    app:srcCompat="@drawable/menu_liquor" />

                <ImageButton
                    android:id="@+id/imageButton_Beer_en"
                    android:layout_width="0dp"
                    android:layout_height="128dp"
                    android:layout_marginTop="12dp"
                    android:background="#00000000"
                    android:scaleType="fitCenter"
                    app:layout_constraintEnd_toEndOf="parent"
                    app:layout_constraintStart_toEndOf="@id/imageButton_Liquor_en"
                    app:layout_constraintTop_toBottomOf="@id/imageButton_Longdrinks_en"
                    app:srcCompat="@drawable/menu_beer" />


                <ImageButton
                    android:id="@+id/imageButton_Softdrinks_en"
                    android:layout_width="0dp"
                    android:layout_height="128dp"
                    android:layout_marginTop="12dp"
                    android:background="#00000000"
                    android:scaleType="fitCenter"
                    app:layout_constraintEnd_toStartOf="@id/imageButton_HotDrinks_en"
                    app:layout_constraintStart_toStartOf="parent"
                    app:layout_constraintTop_toBottomOf="@id/imageButton_Liquor_en"
                    app:layout_constraintVertical_chainStyle="packed"
                    app:srcCompat="@drawable/menu_softdrinks" />

                <ImageButton
                    android:id="@+id/imageButton_HotDrinks_en"
                    android:layout_width="0dp"
                    android:layout_height="128dp"
                    android:layout_marginTop="12dp"
                    android:background="#00000000"
                    android:scaleType="fitCenter"
                    app:layout_constraintEnd_toEndOf="parent"
                    app:layout_constraintStart_toEndOf="@id/imageButton_Softdrinks_en"
                    app:layout_constraintTop_toBottomOf="@id/imageButton_Liquor_en"
                    app:srcCompat="@drawable/menu_hot_drinks" />


            </androidx.constraintlayout.widget.ConstraintLayout>
        </ScrollView>


        <com.google.android.material.bottomnavigation.BottomNavigationView
            android:id="@+id/bottom_navigation"
            app:labelVisibilityMode="labeled"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@color/colorGreen"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:menu="@menu/bottom_navigation"
            app:itemIconTint="@color/colorPrimaryDark"
            app:itemTextColor="@color/colorAccent"
            />

    </androidx.constraintlayout.widget.ConstraintLayout>

</FrameLayout>

解决方法

首先,将activity_main2.xml文件中的<fragment标记更改为FrameLayout,因为在片段之间进行切换必须使用FrameLayout。然后在MainActivity Java类中使用以下代码:

public class MainActivity extends AppCompatActivity  {

   //This will be used to switch between Fragments
   private static FragmentManager fragmentManager;
   private BottomNavigationView bottomNavView;
    

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

        //Initialize the FragmentManager
        fragmentManager = getSupportFragmentManager();

        //Initialize the BottomNavigationView and add listener to it
        bottomNavView = findViewById(R.id.bottom_navigation);
        bottomNavView.setOnNavigationItemSelectedListener(bottomNavListener);     
    }

    private BottomNavigationView.OnNavigationItemSelectedListener bottomNavListener = 
new BottomNavigationView.OnNavigationItemSelectedListener(){

       @Override
       public boolean OnNavigationItemSelected(@NonNull MenuItem item){
       
           Fragment selectedFragment = null;

           switch(item.getItemId()){

                 case R.id.{first fragment}:
                     selectedFragment = new {first fragment}();
                     break;

                 case R.id.{second fragment}:
                     selectedFragment = new {second fragment}();
                     break;
                 
                  .
                  .
                  .

                 {Make a case for each of your fragments}
           }

           fragmentManager.beginTransaction().replace(R.id.{id of your FrameLayout},selectedFragment).commit();

       }
     }; 
}

现在应该可以使用。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-