【问题标题】:ClassCastException on a subclass of ListFragment using compatibility library使用兼容性库的 ListFragment 子类上的 ClassCastException
【发布时间】:2011-05-03 19:18:36
【问题描述】:

只有在使用 3.0 之前的设备的兼容性库时才会发生这种情况

我收到一个我无法确定的错误。我有一个带有 ListFragment 和标准 Fragment 的 Activity。就像 Android 开发指南的开发者部分提供的示例一样。

ListFragment 子类(没有重写函数)

public class ItemListFragment extends ListFragment

MainActivity

public class ItemViewerActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.item_viewer);
    }
}

MainActivity 的 Xml 布局

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  android:orientation="horizontal">
  <fragment class="org.example.ItemListFragment"
    android:id="@+id/item_list_fragment"
    android:layout_width="0dp"
    android:layout_height="fill_parent"
    android:layout_weight="1" />
  <FrameLayout
    android:id="@+id/item_info_frame"
    android:layout_width="0dp"
    android:layout_height="fill_parent"
    android:layout_weight="1" />
</LinearLayout>

来自 LogCat 的错误消息

ERROR/AndroidRuntime: Caused by: java.lang.ClassCastException: org.example.ItemListFragment cannot be cast to android.app.Fragment

【问题讨论】:

    标签: android android-fragments android-1.6-donut android-support-library


    【解决方案1】:

    经过一番认真的谷歌搜索,我发现一篇文章指出了一个不错的小花絮。使用兼容性库时,使用 Fragment 的活动必须扩展 FragmentActivity。一旦我这样做了,错误就不会再次出现。

    【讨论】:

    • 当我正确使用FragmentActivity但忘记使用getSupportFragmentManager()而不是getFragmentManager()时,我也遇到了这个错误。
    • 此外,如果 Activity 上缺少 super.onCreate(savedInstanceState);,则会出现相同的错误,而不是通常的 SuperNotCalledException
    • 我想知道如何同时扩展 ActionBarActivity 和 FragmentActivity,但后来我发现扩展 ActionBar 活动可以解决问题!
    【解决方案2】:

    对我来说,问题是我忘记更改清单。按照教程的建议,我将我的 Activity 转换为 Fragment 并制作了一个 shell Activity 来调用它。我的清单仍然指向导致 Class Cast Exception 的 Fragment 类。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-10-17
      • 2022-09-22
      • 2014-03-12
      • 2013-02-13
      • 1970-01-01
      • 2020-12-05
      • 1970-01-01
      • 2011-06-09
      相关资源
      最近更新 更多