意外转换为 TabHost:布局标记为线性布局

Unexpected cast to TabHost: Layout tag was Linear Layout

我尝试按照以下代码创建一个 tabHost。

    TabHost tabs = (TabHost) findViewById(R.id.homeTabs);
    tabs.setup();

    // Search
    TabHost.TabSpec tabSearch = tabs.newTabSpec("search");
    tabSearch.setContent(R.id.tabSearch);
    tabSearch.setIndicator("Search");
    tabs.addTab(tabSearch);

    // Notification
    TabHost.TabSpec tabNotification = tabs.newTabSpec("notification");
    tabNotification.setContent(R.id.tabNotification);
    tabNotification.setIndicator("Notification");
    tabs.addTab(tabNotification);

它的xml代码是

<TabHost
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:id="@+id/tabHost"
    android:layout_alignParentTop="true"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true">

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="vertical"
        android:id="@+id/homeTabs">

        <FrameLayout
            android:id="@android:id/tabcontent"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent">

            <LinearLayout
                android:id="@+id/tabNotification"
                android:layout_width="fill_parent"
                android:layout_height="fill_parent"
                android:orientation="vertical"></LinearLayout>

            <LinearLayout
                android:id="@+id/tabSearch"
                android:layout_width="fill_parent"
                android:layout_height="fill_parent"
                android:orientation="vertical"
                android:layout_gravity="center">

            </LinearLayout>

        </FrameLayout>
    </LinearLayout>
</TabHost>

AndroidStudio 在线显示错误提示"Unexpected cast to TabHost: Layout tag was Linear Layout"

TabHost tabs = (TabHost) findViewById(R.id.homeTabs);

当 运行 这个应用程序时,它退出并显示这个错误

致命异常:main java.lang.RuntimeException:无法启动 activity ComponentInfo{com.example.nisfansabith.policia/com.example.nisfansabith.policia.Home}:java.lang.ClassCastException: android.widget.LinearLayout

R.id.homeTabs 是您 xml 中的 LinearLayout

TabHost tabs = (TabHost) findViewById(R.id.homeTabs);  

tabHost 是布局中 TabHost 组件的 ID xml。

更改以下行

TabHost tabs = (TabHost) findViewById(R.id.homeTabs);

TabHost tabs = (TabHost) findViewById(R.id.tabHost);

ClassCastException: android.widget.LinearLayout

因为 homeTabs 是 LinearLayout 的 id 但试图投射 TabHost

使用 tabHost 而不是 homeTabs 从 xml 获取 TabHost:

TabHost tabs = (TabHost) findViewById(R.id.tabHost);