简体   繁体   中英

How to run fragment inside Android screen with tabs?

I have a screen with two tabs and for each tab I'm trying to run different fragment with different layout.

I currently have the following:

  • MainFragmentActivity - activitiy which extends FragmentActivity
  • mainFraggment_screen - XML for MaiFragmentActivity
  • Fragment1 - activity when user clicks on Tab1
  • fragmnet1_screen - XML for that
  • Fragment2 - activity when user clicks on Tab2
  • fragment2_screen - XML for that

Everything is working but the problem is that when application starts there in just an empty screen with tabs Tab1 and Tab2. Fragment of certain activity only appears when user clicks on Tab2 for example. And when he clicks back on Tab1, fragment for Tab1 appears normally.

I would like for that fragment of Tab1 to start immediately when application starts but I don't know how to accomplish that.

Any ideas? :D

It sounds like Fragment transaction issues. but I would need to see the code of the MainActivity.

I am assuming you are using the FragmentTransactions.add and FragmentTransaction.replace to move them in and out.

The solution is after adding all the tabs, this needs to be done in onCreate():

TabInfo activeTab = (TabInfo) this.hashMapTab.get("Tab1");
    FragmentTransaction ft = this.getSupportFragmentManager().beginTransaction();
    activeTab.fragment = Fragment.instantiate(this,activeTab.className.getName(), activeTab.args);
    ft.add(R.id.tab1, activeTab.fragment, activeTab.tag);
    ft.attach(activeTab.fragment);
    lastTab = activeTab;
    ft.commit();

hashMapTab is a hash map of TabInfo of all tabs. TabInfo is a container of all Tab data, like class name and tag of the tab.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM