我将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,为什么以及如何摆脱它。谢谢。

最佳答案

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"

08-18 02:46