Android TabHost

13年前
今天学习Android的TabHost组件,自己做了个例子,含有两个Tab页,第一个是一个模拟时钟,第二个显示一个button按钮,当点击button按钮的时候动态的新增一个tab页,java代码里我使用这个方法来获得button按钮:
        final TabHost tab=(TabHost)findViewById(R.id.tabHost);
        tab.setup();
        TabHost.TabSpec spec=tab.newTabSpec("tag1");
        spec.setContent(R.id.tab1);
        spec.setIndicator("Clock");
        tab.addTab(spec);
        spec=tab.newTabSpec("tag2");
        spec.setContent(R.id.tab2);
        spec.setIndicator("Button");
        tab.addTab(spec);
       注意这一句:
       Button btn=(Button)tab.getCurrentView().findViewById(R.id.tab2);
       当我运行这个程序的时候,报空指针错误,指示当前button按钮没有找到,调试一番,才发现:
       tab.getCurrentView()返回的是tab容器当前显示的tab页,而当程序初始显示的时候默认显示的是第一个tab页,也就是我的模拟时钟,而button按钮是在第二个tab页签中,所以会报空指针错误,解决的办法可以让程序默认显示含有button按钮的tab页,使用方法:tab.setCurrentTab(1);也可以使用tab.findViewById()方法在整个tab容器里寻找button按钮,而不使用tab.getCurrentView().findViewById(),但是在整个tab容器里寻找button效率肯定会比在某个tab页签里寻找低喽!!!