Android TabHost
今天學習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);
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頁簽里尋找低嘍!!!
本文由用戶 tomivy 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!