最近在用TabHost,默認但願顯示第2個tab,發現老是加載第三個tab的同時加載第一個,解決方法以下:java
一、首先查看addTab(TabSpec tabSpec)源代碼:this
/** * Add a tab. * @param tabSpec Specifies how to create the indicator and content. */ public void addTab(TabSpec tabSpec) { if (tabSpec.mIndicatorStrategy == null) { throw new IllegalArgumentException("you must specify a way to create the tab indicator."); } if (tabSpec.mContentStrategy == null) { throw new IllegalArgumentException("you must specify a way to create the tab content"); } View tabIndicator = tabSpec.mIndicatorStrategy.createIndicatorView(); tabIndicator.setOnKeyListener(mTabKeyListener); // If this is a custom view, then do not draw the bottom strips for // the tab indicators. if (tabSpec.mIndicatorStrategy instanceof ViewIndicatorStrategy) { mTabWidget.setStripEnabled(false); } mTabWidget.addView(tabIndicator); mTabSpecs.add(tabSpec); if (mCurrentTab == -1) { setCurrentTab(0); } }
發現當咱們進行addTab操做時,默認執行了最後一步,設置了第一個tab,因此咱們須要bamCurrentTab的值設置爲不爲-1的一個數,且大於0。指針
二、再看setCurrentTab(int index)方法源碼:blog
public void setCurrentTab(int index) { if (index < 0 || index >= mTabSpecs.size()) { return; } if (index == mCurrentTab) { return; } // notify old tab content if (mCurrentTab != -1) { mTabSpecs.get(mCurrentTab).mContentStrategy.tabClosed(); } mCurrentTab = index; final TabHost.TabSpec spec = mTabSpecs.get(index); // Call the tab widget's focusCurrentTab(), instead of just // selecting the tab. mTabWidget.focusCurrentTab(mCurrentTab); // tab content mCurrentView = spec.mContentStrategy.getContentView(); if (mCurrentView.getParent() == null) { mTabContent.addView(mCurrentView, new ViewGroup.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)); } if (!mTabWidget.hasFocus()) { // if the tab widget didn't take focus (likely because we're in touch mode) // give the current tab content view a shot mCurrentView.requestFocus(); } //mTabContent.requestFocus(View.FOCUS_FORWARD); invokeOnTabChangeListener(); }
當mCurrentTab不爲-1的時候會執行mTabSpecs.get(mCurrentTab).mContentStrategy.tabClosed()操做,因此在咱們執行setCurrentTab()方法以前,咱們再把mCurrentTab的值恢復爲-1,這樣就不會執行關閉操做致使空指針異常。ip
三、具體方法以下:ci
//取消tabhost默認加載第一個tab。 try { Field current = tabHost.getClass().getDeclaredField("mCurrentTab"); current.setAccessible(true); current.setInt(tabHost, 0); }catch (Exception e){ e.printStackTrace(); } TabHost.TabSpec tSpecCoupon = tabHost.newTabSpec("sth"); tSpecCoupon.setIndicator(tabIndicator1); tSpecCoupon.setContent(new DummyTabContent(getBaseContext())); tabHost.addTab(tSpecCoupon); //mCurrentTab恢復到-1狀態 try { Field current = tabHost.getClass().getDeclaredField("mCurrentTab"); current.setAccessible(true); current.set(tabHost, -1); }catch (Exception e){ e.printStackTrace(); }
到此,咱們屏蔽了默認的setCurrentTab(0)操做,同時恢復爲-1後,又執行了咱們的setCurrentTab(1)操做。get