Search code examples
androidandroid-layoutandroid-tabhost

Unexpected cast to TabHost: Layout tag was Linear Layout


I try to create a tabHost as in the following code.

    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);

and its xml code is

<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 shows the error tip "Unexpected cast to TabHost: Layout tag was Linear Layout" on the line

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

While running this app, it quits and shows this error

FATAL EXCEPTION: main java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.nisfansabith.policia/com.example.nisfansabith.policia.Home}: java.lang.ClassCastException: android.widget.LinearLayout


Solution

  • ClassCastException: android.widget.LinearLayout

    Because homeTabs is id for LinearLayout but trying to cast TabHost.

    Use tabHost instead of homeTabs for getting TabHost from xml:

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