使用兼容性库在ListFragment的子类上的ClassCastException

时间:2011-05-03 19:18:37

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

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

我收到的错误是我无法确定的。我有一个带有ListFragment和标准片段的Activity。它就像Android Dev Guide的Developers部分中提供的示例一样。

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:引起:java.lang.ClassCastException:org.example.ItemListFragment无法强制转换为android.app.Fragment

2 个答案:

答案 0 :(得分:35)

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

答案 1 :(得分:1)

对我来说问题是我忘了改变清单。根据教程的建议,我将Activity转换为Fragment并创建了一个shell Activity来调用它。我的清单仍然指向Fragment类导致类强制转换异常。