【问题标题】:Error inflating class fragment because of an XML file由于 XML 文件,膨胀类片段时出错
【发布时间】:2020-08-27 06:39:20
【问题描述】:

我有一个应用程序,我想使用一个活动多个片段的方法。所以为此我实现了一个主要的活动类,它应该作为片段的容器。在这里您可以看到它的 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 布局文件有问题。我只是无法弄清楚问题是什么,尽管花了相当长的时间。你能帮我解决这个问题吗?我真的很感谢您的 cmets,因为我不知道如何进行。非常感谢您的帮助。

更新:以下是 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>

【问题讨论】:

    标签: android android-layout android-fragments


    【解决方案1】:

    首先,将activity_main2.xml 文件中的&lt;fragment 标签更改为FrameLayout,因为在Fragment 之间切换需要使用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();
    
           }
         }; 
    }
    

    现在应该可以了。

    【讨论】:

    • 感谢开发者的回答。我添加了你的代码。现在我收到一个新错误: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Class java.lang.Object.getClass()' on an null object reference at androidx.fragment.app.FragmentTransaction.doAddOp( FragmentTransaction.java:161) 在 androidx.fragment.app.BackStackRecord.doAddOp(BackStackRecord.java:179) 在 androidx.fragment.app.FragmentTransaction.replace(FragmentTransaction.java:225) 在 androidx.fragment.app.FragmentTransaction.replace (FragmentTransaction.java:200)
    • 在 com.example.td.barapp.Selection_Softdrinks_Activity$1.onNavigationItemSelected(Selection_Softdrinks_Activity.java:49) 在 com.google.android.material.bottomnavigation.BottomNavigationView$1.onMenuItemSelected(BottomNavigationView.java:243)在 androidx.appcompat.view.menu.MenuBuilder.dispatchMenuItemSelected(MenuBuilder.java:840) 在 androidx.appcompat.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:158) 在 androidx.appcompat.view.menu.MenuBuilder.performItemAction (MenuBuilder.java:991)
    • 在 com.google.android.material.bottomnavigation.BottomNavigationMenuView$1.onClick(BottomNavigationMenuView.java:127)
    • 所以我有一个 BottomNavigationBar(可以在布局文件中看到)并且不知何故存在错误。但基本上我之前可以使用 BottomNavigatonBar 所以我不知道错误在哪里
    • 我已经发布了 XML 布局文件和 Java 文件。你可以在上面看到它们
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-21
    • 1970-01-01
    • 2011-09-19
    • 2013-05-28
    相关资源
    最近更新 更多