Android标签tabhost常见的一个小错误

02-11 05:31:22.962: E/AndroidRuntime(406): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.txfy.music/com.txfy.music.MainActivity}: java.lang.RuntimeException: Could not create tab content because could not find view with id 2131230721

我们都知道tabhost.newTabSpec设置标签页的布局内容的时候常用的两种方式

第一种:

public TabHost.TabSpec setContent (int viewId)     直接设置layout.xml 注意这里你的参数viewId是layout的R.id.XX 的属性而不是R.layout.XX

第二种:

publicTabHost.TabSpec setContent (Intent intent)  设置它的意图

当我们使用第一种的时候布局文件必须要把根布局必须把各个标签页的布局内容包含在里面

<FrameLayout xmlns:android=http://schemas.android.com/apk/res/android     <!--根布局-->
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
    <LinearLayout           <!--标签页的布局内容-->  
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:id="@+id/tab1">
        <TextView
            android:layout_height="wrap_content"
            android:layout_width="wrap_content"
            android:text="111"/>
    </LinearLayout>
    <LinearLayout 
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:id="@+id/tab2">
        <TextView
            android:layout_height="wrap_content"
            android:layout_width="wrap_content"
            android:text="222"/>
    </LinearLayout>
</FrameLayout>

如果将标签页的布局内容独立出来写在一个新的xml文件中,如tab1.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:id="@+id/tab1"
    >
    <TextView
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:text="111"/>
</LinearLayout>

当我们设置标签页的布局内容的时候就会报上述错误

当我们使用第二种的时候布局文件根布局的内容可以不写,只需要指定跳转的activity就可以了。如果写了的话会在每个标签页的布局内容叠加显示出来

结果如下

posted @ 2014-02-11 14:16  txfyteen  阅读(298)  评论(0编辑  收藏  举报