soriak
soriak

Reputation: 672

Replace a fragment which has been added as tab of a tabhost

I got the following problem with my android app:

I have a TabHost containing some Fragments as Tabs. These Fragments have been added programmatically. Now I would like to replace the content of a tab with an other Fragment. And I don't know how to achieve that. I found how to replace a fragment which was added via xml, but that is not what I'm trying to achieve.

Thanks in advance for any suggestions.

EDIT: the requested source (only the relevant parts, if more is needed please tell me)

I have a method to initialize the tabhost and add the tabs/fragments programmatically:

private void initialiseTabHost(Bundle args) {
    mTabHost = (TabHost)findViewById(android.R.id.tabhost);
    mTabHost.setup();

    addUserListTab(args);
    //methods to add other tabs


    mTabHost.setOnTabChangedListener(this);
}

private void addUserListTab(Bundle args){
    TabInfo tabInfo = null;
    LayoutParams tabIconParams = new LayoutParams(200, 110);
    tabIconParams.setMargins(0, 0, 0, 0);
    View userIndicator = LayoutInflater.from(this).inflate(R.layout.tab_indicator,mTabHost, false);
    ImageView userIcon = (ImageView) userIndicator.findViewById(R.id.tab_icon);  
    userIcon.setLayoutParams(tabIconParams);
    TabSpec specUser = mTabHost.newTabSpec("user");
    specUser.setIndicator(userIndicator);
    userIcon.setImageDrawable(getResources().getDrawable(R.drawable.selector_user));
    userIcon.setScaleType(ImageView.ScaleType.FIT_CENTER);

    AddTab(this, this.mTabHost, specUser, ( tabInfo = new TabInfo("user", ListUserFragment.class, args)));
    this.mapTabInfo.put(tabInfo.tag, tabInfo);

}
private static void AddTab(MainActivity activity, TabHost tabHost, TabHost.TabSpec tabSpec, TabInfo tabInfo) {
    // Attach a Tab view factory to the spec
    tabSpec.setContent(activity.new TabFactory(activity));
    tabHost.addTab(tabSpec);
}

The Problem is that I don't understand how I can replace the ListUserFragment which I added programmatically to the tabhost. When I pass the container of the tabhost how can I specify which tab of the currently four should contain the new fragment and of course the old should be removed/hidden.

Upvotes: 3

Views: 2189

Answers (1)

Leandros
Leandros

Reputation: 16825

You need to get the FragmentManager and begin a FragmentTransaction to replace the current Fragment with another one.

 getFragmentManager().beginTransaction().replace(R.id.container, new Fragment()).commit();

Be sure to also read the official fragment guide..

Upvotes: 1

Related Questions