Search code examples
javaandroidandroid-fragmentsandroid-tabhost

Get fragment in Tabhost is null


I have made a tab container with TabHost, the layout xml file is like below:

<TabHost
    android:id="@android:id/tabhost"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <TabWidget
        android:id="@android:id/tabs"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >
    </TabWidget>

    <FrameLayout
        android:id="@android:id/tabcontent"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginTop="60dip" >

        <fragment
            android:id="@+id/tab1"
            android:name="com.test.Tab1Fragment"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />

        <fragment
            android:id="@+id/tab5"
            android:name="com.test.Tab5Fragment"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />
    </FrameLayout>
</TabHost>

In MainActivity, I init and add tab into activity in onCreate callback like this,

tabHost = (TabHost) findViewById(android.R.id.tabhost);
tabHost.setup(); 
tabHost.addTab(tabHost.newTabSpec("tab1").setIndicator(mRes.getString(R.string.tab1)).setContent(R.id.tab1));
tabHost.addTab(tabHost.newTabSpec("tab5").setIndicator(mRes.getString(R.string.tab5)).setContent(R.id.tab5));

On the tab changed, I want to find the current fragment, and do some init while current fragment is showing.

private OnTabChangeListener tabChangedListener = new OnTabChangeListener() {
        public void onTabChanged(String tabid) {
            Log.d(TAG, "tab changed " + tabid);
            currentTab = tabid;
            TabChangeCallback currentFragment = (TabChangeCallback) getFragmentManager().findFragmentByTag(currentTab);
            if(currentFragment != null) {
                currentFragment.onTabChanged(currentTabIndex);
            } else {
                Log.d(TAG, "get fragment null ");
            }   
        }
    };

Question is why getFragmentManager().findFragmentByTag(currentTab) is return null, and I couldn't call the fragment init code. thanks for your help.


Solution

  • I think if you are dealing with only fragment in the Tabhost then you better use FragmentTabHost. It will be more optimized and easy.

    Example

    And getting child fragment by Tag - link