首页 文章

android.view.InflateException:二进制XML文件:错误膨胀类片段

提问于
浏览
122

我有一个非常令人沮丧的错误,我无法解释 . 我创建了一个使用 Android AppCompat 的Android应用程序,使其与旧版本兼容 . 这是我的主要活动布局文件:

<android.support.v4.widget.DrawerLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <!-- As the main content view, the view below consumes the entire
         space available using match_parent in both dimensions. -->
    <FrameLayout
        android:id="@+id/container"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <!-- android:layout_gravity="start" tells DrawerLayout to treat
         this as a sliding drawer on the left side for left-to-right
         languages and on the right side for right-to-left languages.
         If you're not building against API 17 or higher, use
         android:layout_gravity="left" instead. -->

    <!-- The drawer is given a fixed width in dp and extends the full height of
         the container. -->
    <fragment android:id="@+id/navigation_drawer"
        android:layout_width="@dimen/navigation_drawer_width"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:name="com.fragment.NavigationDrawerFragment" />

</android.support.v4.widget.DrawerLayout>

这是我活动的主要代码:

public class MainActivity extends ActionBarActivity {
@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
   }
}

这里的主要问题是:上面的代码几乎可以在几乎所有设备上运行(受激设备或某些真实设备) . 但是当我在三星S3上运行时 . 它注意到这个错误:

java.lang.RuntimeException: Unable to start activity ComponentInfo{view.MainActivity}: android.view.InflateException: Binary XML file line #25: Error inflating class fragment
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2081)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2106)
            at android.app.ActivityThread.access$700(ActivityThread.java:134)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1217)
            at android.os.Handler.dispatchMessage(Handler.java:99)
            at android.os.Looper.loop(Looper.java:137)
            at android.app.ActivityThread.main(ActivityThread.java:4856)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:511)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1007)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:774)
            at dalvik.system.NativeStart.main(Native Method)
     Caused by: android.view.InflateException: Binary XML file line #25: Error inflating class fragment
            at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:704)
            at android.view.LayoutInflater.rInflate(LayoutInflater.java:746)
            at android.view.LayoutInflater.inflate(LayoutInflater.java:489)
            at android.view.LayoutInflater.inflate(LayoutInflater.java:396)
            at android.view.LayoutInflater.inflate(LayoutInflater.java:352)
            at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:316)
            at android.app.Activity.setContentView(Activity.java:1901)
            at android.support.v7.app.ActionBarActivity.superSetContentView(ActionBarActivity.java:208)
            at android.support.v7.app.ActionBarActivityDelegateICS.setContentView(ActionBarActivityDelegateICS.java:111)
            at android.support.v7.app.ActionBarActivity.setContentView(ActionBarActivity.java:76)

请告诉我如何修复错误,谢谢:)

28 回答

  • 0

    我不知道这是否会有所帮助 .

    我有一个TextView我有这个问题我在布局中试图膨胀( android.view.InflateException: Binary XML file line #45: Error inflating class TextView ) .

    我设置了以下XML属性 android:textSize="?android:attr/textAppearanceLarge" ,它不允许布局膨胀 .

    不知道究竟为什么,(我对Android仍然有点新 - 不到一年的经验),可能与调用系统属性有关,idk,我所知道的只要我使用普通的旧 @dimen/md_text_16sp (这是我的习惯),问题解决了:)

    希望这可以帮助...

  • 11

    经过长时间的调试,我已经解决了这个问题 . (虽然我还是无法解释原因) . 我将属性 android:name 更改为 class . (虽然在Android Document上,他们说这些属性是相同的,但它有效!)

    所以,它应该改变:

    android:name="com.fragment.NavigationDrawerFragment"
    

    class = "com.fragment.NavigationDrawerFragment"
    

    所以,新的布局应该是:

    <!-- As the main content view, the view below consumes the entire
         space available using match_parent in both dimensions. -->
    <FrameLayout
        android:id="@+id/container"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
    
    <!-- android:layout_gravity="start" tells DrawerLayout to treat
         this as a sliding drawer on the left side for left-to-right
         languages and on the right side for right-to-left languages.
         If you're not building against API 17 or higher, use
         android:layout_gravity="left" instead. -->
    
    <!-- The drawer is given a fixed width in dp and extends the full height of
         the container. -->
    <fragment android:id="@+id/navigation_drawer"
        android:layout_width="@dimen/navigation_drawer_width"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        class = "com.fragment.NavigationDrawerFragment" />
    

    希望这有帮助:)

  • 107

    我无法使用提供的答案解决我的问题 . 最后我改变了这个:

    <fragment
    android:id="@+id/fragment_food_image_gallery"
    android:name="ir.smartrestaurant.ui.fragment.ImageGalleryFragment"
    android:layout_width="match_parent"
    android:layout_height="200dp"
    android:layout="@layout/fragment_image_gallery"
    tools:layout="@layout/fragment_image_gallery" />
    

    对此:

    <FrameLayout
    android:id="@+id/fragment_container"
    android:layout_width="match_parent"
    android:layout_height="200dp" />
    

    private void showGallery() {
        ImageGalleryFragment fragment = new ImageGalleryFragment()
        getSupportFragmentManager().beginTransaction()
                    .replace(R.id.fragment_container, fragment)
                    .commit();
        }
    

    它的工作原理 .
    如果您在片段内使用它,请使用 getChildFragmentManager 而不是 getSupportFragmentManager .

  • 6

    我有同样的问题,问题,尝试了这个线程中的所有答案无济于事 . 我的解决方案是,我没有在Activity XML中添加ID . 我认为这不重要,但确实如此 .

    所以在Activity XML中我有:

    <fragment
        android:name="com.covle.hellocarson.SomeFragment"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>
    

    但应该有:

    <fragment
        android:id="@+id/some_fragment"
        android:name="com.covle.hellocarson.SomeFragment"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>
    

    如果有人愿意评论为什么会这样,我会全神贯注,对其他人,我希望这会有所帮助 .

  • 0

    您可能不再需要它,但如果进一步的读者发现它有用 . 我完全相同 android.view.InflateException:...Error inflating class fragment . 我有所有正确的库包括在内 . 通过在 AndroidManifest.xml 文件中添加一个用户权限来解决,即 <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

    顺便说一句,我跑了 Android Studio 0.8.9 on Ubuntu 12.04.

  • 12

    我有同样的问题因为我没有实现监听器 . 请使用 /*Add This!*/ 查看以下代码 .

    public class SomeActivity extends AppCompatActivity
            implements BlankFragment.OnFragmentInteractionListener /*Add this!*/ 
    {
        @Override                                                  /*Add This!*/
        public void onFragmentInteraction(Uri uri){                /*Add This!*/
        }                                                          /*Add This!*/
    }
    

    仅供参考,我的片段类如下:

    public class SomeFragment extends Fragment {
    
        private OnFragmentInteractionListener mListener;
    
        @Override
        public void onAttach(Activity activity) {
            super.onAttach(activity);
            try {
                mListener = (OnFragmentInteractionListener) activity;
            } catch (ClassCastException e) {
                throw new ClassCastException(activity.toString()
                        + " must implement OnFragmentInteractionListener");
            }
        }
    
        public interface OnFragmentInteractionListener {
            public void onFragmentInteraction(Uri uri);
        }
    }
    

    编辑:

    FragmentonCreate 函数中存在异常时,我也会在另一种情况下注意到同样的错误消息 . 我有以下内容:

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_main, container, false);
    
        int ID = getArguments().getInt("val");
    
        return rootView;
    }
    

    因为我重用了这个片段,所以我总忘了设置参数 . 然后 getArguments() 的结果是 null . 显然,我在这里得到一个 null 指针异常 . 我建议你也要关注这样的错误 .

  • 13

    你的NavigationDrawerFragment是否扩展了android.support.v4.app.Fragment?换句话说,你导入正确的包吗?

    import android.support.v4.app.Fragment;
    
  • 2

    我也有这个问题 . 我通过替换 MainActivityNavigationDrawerFragment 中的导入来解决它

    import android.app.Activity;
    import android.app.ActionBar;
    

    import android.support.v7.app.ActionBar;
    import android.support.v7.app.ActionBarActivity;
    

    我更新 MainActivity 以扩展 ActionBarActivity 而不是活动

    public class MainActivity extends ActionBarActivity implements NavigationDrawerFragment.NavigationDrawerCallbacks
    

    也可以使用 ActionBar actionBar = getSupportActionBar(); 来获取ActionBar

    我在 NavigationDrawerFragment 更新了以下功能

    private ActionBar getActionBar()
    {
        return ((ActionBarActivity)getActivity()).getSupportActionBar();
    }
    
  • 0

    TL/DR :从更高级别的布局XML引用的 during the creation of a fragment 发生异常 . 此异常导致更高级别的布局通胀失败,但 the initial exception was not reported ;只有较高级别的通胀故障才会出现在堆栈跟踪中 . 要找到根本原因,您必须 catch and log the initial exception .


    错误的最初原因可能是各种各样的事情,这就是为什么这里有很多不同的答案,解决了每个人的问题 . 对于某些人来说,它与 idclassname 属性有关 . 对于其他人来说,这是由于权限问题或构建设置 . 对我来说,那些没有解决问题;相反,有一个可绘制的资源只存在于 drawable-ldrtl-xhdpi 中,而不是像 drawable 这样适用的地方 .

    但这些只是细节 . 大图片的问题是,在logcat中显示的错误消息不会被调用 . [1522965_ s onCreateView() ] . 当 exception occurs in a fragment's onCreateView() (例如在给片段充气的时候's layout XML), it causes the inflation of the higher-level layout XML to fail. This higher-level inflation failure is what gets reported as an exception in the error logs. But the initial exception doesn' t似乎在链条上向上移动到足以报告 .

    鉴于这种情况,问题是如何在错误日志中没有显示初始异常时公开它 .

    解决方案非常简单:在片段 onCreateView() 的内容周围放置 try / catch 块,并在 catch 子句中记录异常:

    public View onCreateView(LayoutInflater inflater, ViewGroup contnr, Bundle savedInstSt) {
        try {
            mContentView = inflater.inflate(R.layout.device_detail_frag, null);
            // ... rest of body of onCreateView() ...
        } catch (Exception e) {
            Log.e(TAG, "onCreateView", e);
            throw e;
        }
    }
    

    可能不是很明显哪个片段类的 onCreateView() 这样做,在这种情况下,对每个片段类执行此操作,发生异常的应用程序代码是

    at android.app.Activity.setContentView(Activity.java:1901)
    

    是的

    setContentView(R.layout.activity_main);
    

    那么你需要捕获布局 activity_main 中引用的任何片段的 onCreateView() 中的异常 .

    在我的情况下,根本原因异常结果是

    Caused by: android.content.res.Resources$NotFoundException: Resource
       "com.example.myapp:drawable/details_view" (7f02006f)  is not a
       Drawable (color or path): TypedValue{t=0x1/d=0x7f02006f a=-1
       r=0x7f02006f}
    

    在我在 onCreateView() 中捕获并明确记录之前,此异常未显示在错误日志中 . 一旦记录,问题很容易诊断和修复(由于某种原因, details_view.xml 仅存在于 ldrtl-xhdpi 文件夹下) . 关键是捕获作为问题根源的异常并暴露它 .

    在你的所有片段' onCreateView() 方法中做这个样板并没有什么坏处 . 如果那里存在未捕获的异常,则无论如何都会使活动崩溃 . 唯一的区别是,如果你在 onCreateView() 中捕获并记录异常,你就不会知道它为什么会发生 .

    附:我刚刚意识到这个答案与@ DaveHubbard有关,但是使用不同的方法来查找根本原因(日志与调试器) .

  • 0

    我一直有类似的问题 . 无论实际原因如何,错误消息通常都会提供非常少的细节 . 但我找到了获得更多有用信息的方法 . 事实证明,内部的android类'LayoutInflater.java'(在android.view包中)有一个'inflate'方法重新抛出一个异常,但是没有提取细节,所以你丢失了原因信息 .

    我使用了AndroidStudio,并在LayoutInflator第539行(在我正在使用的版本中)设置了一个断点,这是'inflate'方法中泛型异常的catch块的第一行:

    } catch (Exception e) {
                InflateException ex = new InflateException(
                        parser.getPositionDescription()
                                + ": " + e.getMessage());
                ex.initCause(e);
                throw ex;
    

    如果您在调试器中查看“e”,您将看到“原因”字段 . 它可以帮助您提供有关真实情况的提示 . 例如,我发现包含的片段的父元素必须具有id,即使代码中没有使用它也是如此 . 或者TextView存在维度问题 .

  • 8

    以防有人需要这个 . 假设:设备电话连接到USB电缆和IDE读取以启动应用程序 . 转到命令提示符以确定问题:输入adb logcat

    然后从IDE启动您的应用程序 . 你会例外 .

    就我而言:我正在将2.3版的Android应用程序部署到不支持小部件“Space”的移动设备上

  • 3

    如果您有一个自定义类来扩展另一个类(在本例中是一个视图)并且不导入该类所需的所有构造函数,则会出现此问题 .

    例如:public class CustomTextView扩展TextView {}

    这个类有4个构造函数,如果你错过任何一个,它会崩溃 . 事实上我错过了Lollipop使用的最后一个添加了构造函数并且工作正常 .

  • 0

    我遇到了这个问题并通过使用以下代码解决了它 . 我正在使用childfragment manager开始片段事务 .

    布局:

    <fragment
                        class="com.google.android.youtube.player.YouTubePlayerSupportFragment"
                        android:id="@+id/youtube_fragment"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"/>
    

    这就是我开始片段交易的方式:

    youTubePlayerFragment = (YouTubePlayerSupportFragment) getChildFragmentManager().findFragmentById(R.id.youtube_fragment);
    

    以下代码解释了我如何删除使用childfragmentmanger添加的片段 .

    @Override
        public void onDestroyView() {
            super.onDestroyView();
    
            youTubePlayerFragment = (YouTubePlayerSupportFragment) getChildFragmentManager().findFragmentById(R.id.youtube_fragment);
    
            if (youTubePlayerFragment != null)
            {
                getChildFragmentManager().beginTransaction().remove(youTubePlayerFragment).commitAllowingStateLoss();
            }
    
            youTubePlayer = null;
        }
    
  • 0

    我们还必须在build.gradle(app)中添加以下内容

    compile 'com.android.support:appcompat-v7:23.1.1'
    compile 'com.android.support:design:23.1.1'
    

    每当我们使用新的布局或新的设计功能 . 希望这能帮助你 .

  • 6

    在这里没有任何答案帮助我之后,我选择在调试模式下运行app,在我的片段中移动onCreateView的每一行(在你的情况下为NavigationDrawerFragment) . 并注意到由于NullPointerException,该片段难以充气 . 例如 .

    mySeekBar = (SeekBar) getActivity().findViewById(R.id.mySeekBar);
    mySeekBar.setOnSeekBarChangeListener(this);
    

    这里mySeekBar被设置为null(因为我错过了在适当的布局中添加控件)并且下一行进入NPE,它出现为InflateException . 另外,如上所述,将android:name重命名为class .

    出于上述各种原因可能出现此问题 . 我会建议逐行调试流程来了解错误 .

  • 3

    我参加聚会有点晚了,但这些答案中没有一个对我有帮助 . 我在我的片段中使用Google Map 作为 SupportMapFragmentPlaceAutocompleteFragment . 正如所有答案都指出了这一事实问题是SupportMapFragment是要重新创建和重绘的 Map .

    但我也有PlaceAutocompleteFragment的问题 . 所以这是因为 SupportMapFragmentSupportMapFragment 而面临这个问题的人的工作解决方案

    mapFragment = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.mapFragment);
        FragmentManager fm = getChildFragmentManager();
    
        if (mapFragment == null) {
            mapFragment = SupportMapFragment.newInstance();
            fm.beginTransaction().replace(R.id.mapFragment, mapFragment).commit();
            fm.executePendingTransactions();
        }
    
        mapFragment.getMapAsync(this);
    
        //Global PlaceAutocompleteFragment autocompleteFragment;
    
    
        if (autocompleteFragment == null) {
            autocompleteFragment = (PlaceAutocompleteFragment) getActivity().getFragmentManager().findFragmentById(R.id.place_autoCompleteFragment);
    
        }
    

    在onDestroyView中清除SupportMapFragment和SupportMapFragment

    @Override
    public void onDestroyView() {
        super.onDestroyView();
    
    
        if (getActivity() != null) {
            Log.e("res","place dlted");
            android.app.FragmentManager fragmentManager = getActivity().getFragmentManager();
            android.app.FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
            fragmentTransaction.remove(autocompleteFragment);
            fragmentTransaction.commit();
    
            autocompleteFragment = null;
        }
    
    
    }
    
  • 3

    我认为基本问题是在AndroidManifest.xml中定义的“android:targetSdkVersion” . 就我而言,我定义的初始值为:

    android:targetSdkVersion=16

    我改成了:

    android:targetSdkVersion=22

    这解决了我所有的错误 . 因此,在构建Android应用程序之前,设置正确的“targetSdkVersion”也很重要 .

  • 1

    如果其他人来到这里并且答案无法解决问题,还有一件事要尝试 .

    正如其他人所提到的,这通常是由嵌入在XML本身的问题引起的,而不是你在Java中做错的问题 . 就我而言,这是一个非常容易(和愚蠢)的错误 .

    我有这样的代码:

    <view
        android:layout_width="fill_parent"
        android:layout_height="1dip"
        android:id="@+id/view44"
        android:background="@color/gray"
        />
    

    当我所要做的就是在“查看”中将v大写,以便系统重新识别它 . 检查您的自定义视图(或片段,recyclerviews等)是否都预先具有适当的大写声明,以便XML自动完成将其与相应的视图匹配 .

  • 0

    对于一些仍然没有找到解决方案的人,在我的情况下,它发生了,因为我有一个OOM(内存不足)问题 . 当您长时间使用应用程序时,如果您的应用程序中存在内存泄漏,则可能会发生这种情况 . 在我的堆栈跟踪中,这是主要原因 .

  • 0

    我在4.4.2设备上有这个,但是5很好 . 原因:在自定义视图的初始化中,我创建了一个 TextView(Context context, AttributeSet attrs, @AttrRes int defStyleAttr, @StyleRes int defStyleRes) ,即API 21 .

    即使注释 TargetApi(21) ,Android Studio 2.1也不会抱怨它 . 显然,Android Studio 2.2将更正此问题并将其正确显示为错误 .

    希望这有助于某人 .

  • 24

    我也遇到了这个错误,经过很长时间的调试,问题就是我的MainClass扩展了Activity而不是FrameActivity,在我的例子中,xml不是问题 . 希望能帮到你 .

  • 4

    如前一篇文章所述,
    改名

    android:name="com.fragment.NavigationDrawerFragment"
    

    class = "com.fragment.NavigationDrawerFragment"
    

    不过,它对我不起作用 . 然后,我只使用了没有com.fragment部分的类名,瞧它工作了 . 所以最后改变它

    class = "NavigationDrawerFragment"
    
  • 0

    就我而言 .

    我试图膨胀的布局了

    <include 
     layout  = "...."
    />
    

    标记,删除它修复它 .

    我试图将为Actvity设计的先前布局扩展到view-pager适配器 .

  • 2

    我的错误是由不同的问题引起的 .

    我正在将一个来自Activity的包传递给它的片段 . 当我评论在片段中接收束的代码时,错误消失了 . 事实证明,我的错误是由于下面的“getArguments();”返回null的部分 .

    Bundle args = getArguments();
    

    检查活动发送代码后,我意识到我在下面有一个愚蠢的错误;

    Bundle bundle =new Bundle();
     bundle.putInt("recipeID", recipe_position);
     Fragment mainFragment = new MainActivityFragment();
     mainFragment.setArguments(bundle);
     FragmentManager fragmentManager = getSupportFragmentManager();
     --> fragmentManager.beginTransaction()
                            .replace(R.id.container, new  MainActivityFragment(),
                                    DetailRecipeActivityFragment.TAG)
                            .commit();
    

    我正在用箭头创建一个新片段 . 而我应该使用已经拥有我的捆绑包的预先实例化的片段 . 所以应该是:

    Bundle bundle =new Bundle();
     bundle.putInt("recipeID", recipe_position);
     Fragment mainFragment = new MainActivityFragment();
     mainFragment.setArguments(bundle);
     Fragment mainFragment = new MainActivityFragment();
     FragmentManager fragmentManager = getSupportFragmentManager();
     -->fragmentManager.beginTransaction()
                            .replace(R.id.container, mainFragment,
                                    DetailRecipeActivityFragment.TAG)
                            .commit();
    

    我不知道为什么它会抛出这个错误而不是NPE,但这解决了我的错误以防有人有相同的情况

  • 0

    我有同样的问题,在我的情况下包名称是错误的,修复它解决了问题 .

  • 1

    经过长时间的尝试,这就是我在上述答案都无法解决之后的问题 .

    • 为您的 Main 活动而不是 Activity 延长 AppCompatActivity .

    • AndroidManifest.xml 中将 android:theme="@style/Theme.AppCompat.Light" 添加到 <Activity..../>

    • NavigationDrawerFragment 类中,将 ActionBar 实例更改为

    ActionBar mActionBar=((AppCompatActivity)getActivity()).getSupportActionBar();
    

    EDIT

    它应该是 ActivityLayout 之间的一致性 . 如果 LayoutAppCompat Theme 之一,如 Theme.AppCompat.Light ,则 Activity 应为 extends AppCompatActivity .

    我想要汉堡图标和看起来像 Android Gmail App 的导航抽屉,但我最终得到了一个丑陋的导航抽屉 . 所有这些因为我的所有类 extends Activity 而不是 AppCompatActivity .

    我重新考虑整个项目延伸 AppCompatActivity ,然后右键单击 Layout Folder ,选择 new - > Activity 然后 Navigation Drawer Activity 和Boom,一切都为我完成!

  • 0

    打开gradle.properties并添加以下行:

    android.enableAapt2=false
    

    参考:https://github.com/chrisjenx/Calligraphy/issues/417#issuecomment-365177808

  • 0

    当我在我的RecyclerView上时,我遇到了这个错误我的fragment.xml的根,

    但当我用ViewGroup包装它时,应用程序运行正常 .

相关问题