【问题标题】:Error inflating class fragment from the xml从 xml 膨胀类片段时出错
【发布时间】:2012-08-13 14:48:45
【问题描述】:

我在这里发现了几个类似的问题,但建议的答案不适合我。

所以错误是:

08-13 14:40:10.723: E/AndroidRuntime(630): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.fragments/com.example.fragments.MainActivity}: android.view.InflateException: Binary XML file line #7: Error inflating class fragment

我的 MainActivity 是:

    package com.example.fragments;

import android.os.Bundle;
import android.support.v4.app.FragmentActivity;

public class MainActivity extends FragmentActivity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

}

我的 xml 是:

    <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal" >

    <fragment
        android:id="@+id/listFragment"
        android:layout_width="150dip"
        android:layout_height="match_parent"
        android:layout_marginTop="?android:attr/actionBarSize"
        class="com.example.fragments.ListFragment" >
    </fragment>

    <fragment
        android:id="@+id/detailFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        class="com.example.fragments.DetailFragment" >
    </fragment>

</LinearLayout>

非常感谢您对此问题的任何帮助

xx

【问题讨论】:

  • 是您的应用中存在的 com.example.fragments.ListFragment 、 com.example.fragments.DetailFragment 类吗?
  • 亲爱的 Nandeesh,是的,它们存在于项目文件夹中,并且位于包 com.example.fragments 中

标签: android android-fragments android-xml


【解决方案1】:

所以基本上问题是通过在项目中实现所有与 Fragment 相关的导入来解决的,如下所示:

import android.support.v4.app.FragmentActivity;
import android.support.v4.app.Fragment;
import android.support.v4.app.ListFragment

而不是:

import android.app.Fragment
import android.app.FragmentActivity
import android.app.ListFragment

【讨论】:

  • 我是 Android 新手,但 android.support.v4.app 包中的类不只是新 Android 功能的反向移植,因此您可以在旧版本的 Android 上使用新功能吗?如果更改导入有效,则有效。但是我还是很想知道为什么android.app的实现不能膨胀。
  • 你的问题是 100% 公平的,但老实说 - 我不知道 :) 一种方法对我有用,其他没有。就这么简单:) 那时我没有足够的时间详细介绍。对不起xx
  • 原因是你的activity扩展了android.support.v4.app.FragmentActivity。 android.support.v4.app 和 android.app 是独立的类树,所以一个中的 Fragment 可能看起来像另一个中的 Fragment,但它们是独立的对象。如果您检查它们的继承层次结构,它们会在 Object 之后发散。仅在需要时才使用支持库,这样可以避免此问题。
【解决方案2】:

我认为错误可能是由于

android:layout_marginTop="?android:attr/actionBarSize"

actionBarSize 仅在 api 11 中引入,并且当您使用支持库时,我假设您正在 Android 3.0 之前的设备上进行开发。尝试删除该属性,看看是否是问题所在。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-09-19
    • 2013-05-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多