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

时间:2015-03-03 09:16:06

标签: android android-layout android-tabhost

我尝试创建一个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显示错误提示&#34;意外转换为TabHost:布局标记为线性布局&#34;在线

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

运行此应用时,它会退出并显示此错误

FATAL EXCEPTION:main java.lang.RuntimeException:无法启动活动ComponentInfo {com.example.nisfansabith.policia / com.example.nisfansabith.policia.Home}:java.lang.ClassCastException:android.widget.LinearLayout < / p>

3 个答案:

答案 0 :(得分:1)

  

ClassCastException:android.widget.LinearLayout

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

使用tabHost代替homeTabs从xml获取TabHost:

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

答案 1 :(得分:0)

R.id.homeTabs是xml中的LinearLayout

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

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

答案 2 :(得分:0)

更改以下行

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

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