1

我正在使用带有 android 支持库的FragmentTabHost ,

我的布局文件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;
        }
   ...
}

但是,我在上面的代码中得到了ClassCastExceptionmTabHost异常,该异常是在 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,为什么以及如何摆脱它。谢谢。

4

1 回答 1

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"
于 2013-07-03T14:19:31.717 回答