使用FragmentTabHost时ClassCastException

时间:2013-07-03 14:05:22

标签: java android android-layout android-intent android-fragments

我正在使用FragmentTabHost和android支持库,

我的布局文件 sub_main.xml

<android.support.v4.app.FragmentTabHost 
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@android:id/tabhost"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

   <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="vertical" >

        <TabWidget
            android:id="@android:id/tabs"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_weight="0"
            android:orientation="horizontal" />

        <FrameLayout
            android:id="@+id/tabFrameLayout"
            android:layout_width="fill_parent"
            android:layout_height="0dp"
            android:layout_weight="1" />
    </LinearLayout>

</android.support.v4.app.FragmentTabHost>

以上布局用于我的片段:

   public class MyFragment extends Fragment{
       ...
       private FragmentTabHost mTabHost;
       private View content;

      @Override
      public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
            super.onCreateView(inflater, container, savedInstanceState);

            View content = inflater.inflate(R.layout.sub_main, null); 

            // the following code throw ClassCastException, why?
            mTabHost = (FragmentTabHost) content.findViewById(android.R.id.tabhost);

            return content;
        }
   ...
}

但是,我在上面的代码中得到了 ClassCastException 异常,其中mTabHost在onCreateView()中初始化:

07-03 16:35:09.704: E/AndroidRuntime(25350): java.lang.ClassCastException: android.widget.TabHost cannot be cast to android.support.v4.app.FragmentTabHost

它抱怨TabHost无法投放到FragmentTabHost,为什么&amp;如何摆脱它。感谢。

1 个答案:

答案 0 :(得分:1)

mTabHost = (FragmentTabHost) content.findViewById(android.R.id.tabhost);

应该是

mTabHost = (FragmentTabHost) content.findViewById(R.id.tabhost);

并在xml布局中指定

android:id="@android:id/tabhost"

作为

android:id="@+id/tabhost"