2015-03-03 78 views
-1

我尝试创建一个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示出了错误提示 “意外浇铸到TabHost:布局标签是线性布局” 上线

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

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

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

+0

TabHost选项卡=(TabHost)findViewById(R.id.tabHost);改变这一行 – 2015-03-03 09:19:31

回答

1

ClassCastException异常:android.widget.LinearLayout

因为homeTabs是ID为的LinearLayout,但尝试投放TabHost

使用tabHost代替homeTabs用于从XML获得TabHost:

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

什么是TabHost ..的ID? – Nisfan 2015-03-03 09:36:02

+0

@NisfanSabith:你在xml中使用'R.id.tabHost' – 2015-03-03 09:39:02

+0

什么是TabHost和LinearLayout的id – Nisfan 2015-03-04 08:02:55

0

R.id.homeTabs是你的xml中的LinearLayout

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

tabHost是在布局XML中的TabHost组件的ID。

0

更改以下行

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

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