How to get current selected Fragment in FragmentTabHost - android

There are some questions related to this same issue. For example, this one. But it doesn't work.
Let me show what I did in my code.
activity_main.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:id="#+id/container"
android:layout_width="match_parent" android:layout_height="match_parent"
tools:context=".MainActivity" tools:ignore="MergeRootFrame" >
<fragment
android:id="#+id/my_fragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:name="com.example.zhouhao.test.MyFragment"
tools:layout="#layout/fragment_my" />
</FrameLayout>
fragment_my.xml (my main fragment which include a FragmentTabHost)
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.app.FragmentTabHost xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#android:id/tabhost"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:weightSum="100"
android:orientation="horizontal">
<FrameLayout
android:id="#android:id/tabcontent"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_weight="0" />
<LinearLayout
android:layout_width="0dp"
android:layout_weight="95"
android:layout_height="match_parent"
android:orientation="vertical">
<FrameLayout
android:id="#+id/panel_content"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1" />
</LinearLayout>
</LinearLayout>
</android.support.v4.app.FragmentTabHost>
fragment_tab1.xml (for the fragment corresponding to different tab, they are similar so that I only show you one code)
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" tools:context="com.example.zhouhao.test.TabFragment">
<!-- TODO: Update blank fragment layout -->
<TextView android:layout_width="match_parent" android:layout_height="match_parent"
android:text="#string/fragment_tab1" />
</FrameLayout>
MainActivity.java
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
FragmentManager fm = getSupportFragmentManager();
mMyFragment = (MyFragment) fm.findFragmentById(R.id.my_fragment);
}
}
public class MyFragment extends Fragment implements TabHost.OnTabChangeListener {
FragmentTabHost mFragmentTabHost;
public MyFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_my, container, false);
if (rootView != null) {
mFragmentTabHost = (FragmentTabHost) rootView.findViewById(android.R.id.tabhost);
mFragmentTabHost.setup(getActivity(), getActivity().getSupportFragmentManager(), R.id.panel_content);
TabFragment1 tab1Fragment = new TabFragment1();
TabFragment2 tab2Fragment = new TabFragment2();
TabFragment3 tab3Fragment = new TabFragment3();
TabHost.TabSpec spec1 = mFragmentTabHost.newTabSpec("1").setIndicator("");
TabHost.TabSpec spec2 = mFragmentTabHost.newTabSpec("2").setIndicator("");
TabHost.TabSpec spec3 = mFragmentTabHost.newTabSpec("3").setIndicator("");
mFragmentTabHost.addTab(spec1,tab1Fragment.getClass(), null);
mFragmentTabHost.addTab(spec2,tab2Fragment.getClass(), null);
mFragmentTabHost.addTab(spec3,tab3Fragment.getClass(), null);
mFragmentTabHost.setOnTabChangedListener(this);
return rootView;
} else {
return super.onCreateView(inflater, container, savedInstanceState);
}
}
#Override
public void onTabChanged(String tabId) {
BaseFragment f = (BaseFragment)getActivity().getSupportFragmentManager().findFragmentByTag(tabId);
Log.d("Log",tabId);
}
}
My problem is the BaseFragment is always null in my onTabChanged. Can anybody help? Thanks.

You cannot get the selected fragment immediately if the fragment has never been instantiated.
#Override
public void onTabChanged(final String tabId) {
Fragment fg = getSupportFragmentManager().findFragmentByTag(tabId);
Log.d(TAG, "onTabChanged(): " + tabId + ", fragment " + fg);
if (fg == null) {
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
Fragment fg = getSupportFragmentManager().findFragmentByTag(tabId);
Log.d(TAG, "onTabChanged() delay 50ms: " + tabId + ", fragment " + fg);
}
}, 50);
}
}
the output:
// cannot get the selected fragment immediately if the fragment has never been instantiated.
onTabChanged(): 1, fragment null
onTabChanged() delay 50ms: 1, fragment HistoryFragment{6f7a9d5 #2 id=0x7f09006e 1}
onTabChanged(): 2, fragment null
onTabChanged() delay 50ms: 2, fragment HistoryFragment{10c59e72 #3 id=0x7f09006e 2}
// can get the selected fragment immediately if the fragment already instantiated.
onTabChanged(): 1, fragment HistoryFragment{6f7a9d5 #2 id=0x7f09006e 1}
onTabChanged(): 2, fragment HistoryFragment{10c59e72 #3 id=0x7f09006e 2}

I think I get the right way to solve this problem, below is my answer.
Create a TabBean
private int imgId;
private int textId;
private Class fragment;
public MainTabBean(int textId, int imgId, Class fragment) {
this.textId = textId;
this.imgId = imgId;
this.fragment = fragment;
}
public int getTextId() {
return textId;
}
public void setTextId(int textId) {
this.textId = textId;
}
public int getImgId() {
return imgId;
}
public void setImgId(int imgId) {
this.imgId = imgId;
}
public Class getFragment() {
return fragment;
}
public void setFragment(Class fragment) {
this.fragment = fragment;
}
Then, get three TabBean instances with three fragments
List<MainTabBean> tabs = new ArrayList<>();
// three TabBean instances
TabBean homeTab = new MainTabBean(R.string.home, R.drawable.tab_home, HomepageFragment.class);
TabBean postcardTab = new MainTabBean(R.string.postcard, R.drawable.tab_postcard, PostcardFragment.class);
Bean notificationTab = new MainTabBean(R.string.notification, R.drawable.tab_notification, NotificationFragment.class);
// put tabs into a list
tabs.add(homeTab);
tabs.add(postcardTab);
tabs.add(notificationTab);
Third, just associate the TabBeans with FragmentTabHost as usual
// Obtain FragmentTabHost
tabHost = findViewById(android.R.id.tabhost);
// Associate fragmentManager with container
tabHost.setup(this, getSupportFragmentManager(), R.id.main_content);
// Create TabSpecs with TabBean and add it on TabHost
for(MainTabBean tab : tabs) {
TabHost.TabSpec spec = tabHost.newTabSpec(String.valueOf(tab.getTextId()))// set a tag
.setIndicator(getTabIndicator(tab));// set an indicator
tabHost.addTab(spec, tab.getFragment(), null);// add a tab
}
Forth, that's the most important step, I didn't get fragment instance with findFragmentByTag() like this
getSupportFragmentManager()
.findFragmentByTag(String.valueOf(tabs.get(1).getTextId()));
Instead, my answer is exactly like this:
tabs.get(0).getFragment().newInstance();
and cast it.
And I finally got the fragment.

Related

Replace fragment in fragment itself in TabActivity

I am sorry on the duplicate question but I didn't get answer for my problem.
I create app with TabActivity and also trying to replace one fragment from fragment itself, I read in https://developer.android.com/training/basics/fragments/fragment-ui.html how to do it and i created interface in my fragment that i want to be replace with another,
I implement the interface in my MainActivity and still when running my app it show me container itself.
here is my code:
Main Activity:
public class MainActivity extends FragmentActivity implements New2.OnReplaceFragment {
private SectionsPagerAdapter mSectionsPagerAdapter;
private ViewPager mViewPager;
public static MainActivity instance = null;
public static MainActivity getInstance(){
return instance;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.frame_container);
mViewPager.setAdapter(mSectionsPagerAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
tabLayout.getTabAt(0).setIcon(R.drawable.icon_info);
tabLayout.getTabAt(1).setIcon(R.drawable.icon_heart_rate_sensor_jpg);
tabLayout.getTabAt(2).setIcon(R.drawable.icon_graph_jpg);
instance = this;
}
#Override
public void onReplaceFragment(Class fragmentClass) {
Fragment fragment = null;
try {
fragment = (Fragment) fragmentClass.newInstance();
} catch (Exception e) {
e.printStackTrace();
}
// Insert the fragment by replacing any existing fragment
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.frame_container,fragment);
// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the back stack so the user can navigate back
transaction.addToBackStack(null);
// Commit the transaction
transaction.commit();
}
public static class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
TextView textView = (TextView) rootView.findViewById(R.id.section_label);
textView.setText(getString(R.string.section_format, getArguments().getInt(ARG_SECTION_NUMBER)));
return rootView;
}
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a PlaceholderFragment (defined as a static inner class below).
switch (position) {
case 0:
// New1 tab1 = new New1();
return New1.newInstance();
case 1:
return New2.newInstance();
case 2:
return New3.newInstance();
default:
return null;
}
}
#Override
public int getCount() {
// Show 3 total pages.
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "SECTION 1";
case 1:
return "SECTION 2";
case 2:
return "SECTION 3";
}
return null;
}
}
}
my fragment that I want to replace
Fragment:
public class New2 extends Fragment {
TextView name;
Button change;
ImageView image1;
Animation anime;
private OnReplaceFragment dataPasser;
public static New2 newInstance(){
New2 fragment = new New2();
return fragment;
}
public New2(){
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_new2, container, false);
name = (TextView) rootView.findViewById(R.id.nameTt);
change = (Button) rootView.findViewById(R.id.changeBtn);
image1 = (ImageView) rootView.findViewById(R.id.image1);
anime = AnimationUtils.loadAnimation(getActivity().getApplicationContext(),R.anim.zoom);
change.setOnClickListener(changeName);
return rootView;
}
View.OnClickListener changeName = new View.OnClickListener() {
#Override
public void onClick(View view) {
image1.startAnimation(anime);
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run(){
dataPasser.onReplaceFragment(Result.class);
}
},1000);
}
};
public interface OnReplaceFragment {
public void onReplaceFragment(Class fragmentClass);
}
#Override
public void onAttach(Activity a) {
super.onAttach(a);
try {
dataPasser = (OnReplaceFragment) a;
} catch (ClassCastException e) {
throw new ClassCastException(a.toString() + " must implement onDataPass");
}
}
}
the fragment that i want to display
public class Result extends Fragment {
TextView textView;
Button btnBack;
public static Result instance = null;
public static Result getInstance(){
return instance;
}
public Result() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_result, container, false);
textView = (TextView) v.findViewById(R.id.text11);
btnBack = (Button) v.findViewById(R.id.btnBack);
textView.setText("working!!");
Toast.makeText(getActivity().getApplicationContext(),"working",Toast.LENGTH_LONG).show();
return v;
}
}
Main Activity XML:
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/main_content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context="com.example.hercules.tadhosttutrial.MainActivity">
<android.support.design.widget.AppBarLayout
android:id="#+id/appbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="#dimen/appbar_padding_top"
android:background="#color/red"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.design.widget.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</android.support.design.widget.AppBarLayout>
<android.support.v4.view.ViewPager
android:id="#+id/frame_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
New2 XML:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.hercules.tadhosttutrial.New2"
android:background="#color/yellow">
<!-- TODO: Update blank fragment layout -->
<Button
android:id="#+id/changeBtn"
android:layout_width="80dp"
android:layout_height="40dp"
android:layout_gravity="center_horizontal"
android:text="change"/>
<ImageView
android:id="#+id/image1"
android:background="#drawable/icon_complete"
android:layout_width="200dp"
android:layout_height="200dp"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
/>
Result XML:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/colorAccent"
tools:context="com.example.hercules.tadhosttutrial.Result">
<!-- TODO: Update blank fragment layout -->
<Button
android:id="#+id/btnBack"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="back"/>
<TextView
android:id="#+id/text11"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="WORKING"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:textSize="70dp"
/>
</RelativeLayout>
What i mean, is making MainActivity as a main container for all fragments, either with tabs or just a regular fragment,
1- Main Activity XML: remove ViewPager, add a FrameLayout instead (use same id)
2- Create new fragment TabsFragment with this XML:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.hercules.tadhosttutrial.New2"
android:background="#color/yellow">
<android.support.v4.view.ViewPager
android:id="#+id/frame_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
</RelativeLayout>
3- Move initializing SectionsPagerAdapter and ViewPager from main activity to TabsFragment:
this part:
private SectionsPagerAdapter mSectionsPagerAdapter;
private ViewPager mViewPager;
and this:
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.frame_container);
mViewPager.setAdapter(mSectionsPagerAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
tabLayout.getTabAt(0).setIcon(R.drawable.icon_info);
tabLayout.getTabAt(1).setIcon(R.drawable.icon_heart_rate_sensor_jpg);
tabLayout.getTabAt(2).setIcon(R.drawable.icon_graph_jpg);
4- I think moving SectionsPagerAdapter class in a new file is better too.
now if you want default view for app to be the tabs, then in MainActivity at onCreate() show TabsFragment by calling your method:
onReplaceFragment(TabsFragment.class);
now every thing should work fine, because the idea here is to replace the fragment displayed in main activity with another one
in this case TabsFragment, Result, and New2
not to replace viewpager fragments (because as i told you this is managed via the adapter) not by calling replace()
you may need to play around this, it's not a final code, just something to give you idea about it.

FragmentPagerAdapter: IllegalStateException Can't change container ID of fragment

First: Sorry for the wall of text/code, but I think most of it is needed to understand the problem.
I am creating an app using Fragments in a ViewPager and a TabHost. The ViewPager has a custom FragmentPagerAdapter that will feed the various pages in the ViewPager. I have ran into a problem where the custom FragmentPagerAdapter starts adding the various Fragments to the BackStack, but it fails at a point where it checks that the container ID (in this case the ID of the ViewPager) against the ID of the Fragments to add. These are different, thus the program fails. I am fairly new to using Fragments, so I am not sure if my code follows best practice. What could be the error in the following?
The Activity, which inflates the main XML layout.
public class MyActivity extends FragmentActivity implements TabHost.OnTabChangeListener, ViewPager.OnPageChangeListener{
private MyViewPager mViewPager;
private FragmentTabHost mFragmentTabHost;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.my_activity);
setupViewPager();
setupFragmentTabHost();
}
private void setupViewPager()
{
mViewPager = (MyViewPager) findViewById(R.id.my_pager);
}
private void setupFragmentTabHost()
{
mFragmentTabHost = (FragmentTabHost) findViewById(android.R.id.tabhost);
mFragmentTabHost.setOnTabChangedListener(this);
mFragmentTabHost.setup(this, getSupportFragmentManager(), android.R.id.tabcontent);
mFragmentTabHost.addTab(mFragmentTabHost.newTabSpec("tab1").setIndicator("Tab 1", null), TabFragment.class, null);
mFragmentTabHost.addTab(mFragmentTabHost.newTabSpec("tab2").setIndicator("Tab 2", null), TabFragment.class, null);
mFragmentTabHost.addTab(mFragmentTabHost.newTabSpec("tab3").setIndicator("Tab 3", null), TabFragment.class, null);
}
#Override
protected void onDestroy()
{
}
public MyViewPager getMyPager()
{
return mViewPager;
}
#Override
public void onTabChanged(String tabId) {
int position = mFragmentTabHost.getCurrentTab();
mViewPager.setCurrentItem(position);
}
#Override
public void onPageSelected(int position)
{
mFragmentTabHost.setCurrentTab(position);
}
#Override
public void onPageScrollStateChanged(int arg0) {}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {}
}
The main XML file, my_activity.xml, containing the ViewPager, the TabHost and the Fragments for the ViewPager:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<android.support.v4.app.FragmentTabHost
android:id="#android:id/tabhost"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<FrameLayout
android:id="#android:id/tabcontent"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_weight="0" />
<com.mycompany.myapp.gui.mypager.MyViewPager
android:id="#+id/my_pager"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1" />
<TabWidget
android:id="#android:id/tabs"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
</android.support.v4.app.FragmentTabHost>
<fragment
android:name="com.mycompany.myapp.gui.mypager.FilteredRecipesFragment"
android:id="#+id/filtered_recipes_fragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:focusable="true" />
<fragment
android:name="com.mycompany.myapp.gui.mypager.SelectedRecipesFragment"
android:id="#+id/selected_recipes_fragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:focusable="true" />
<fragment
android:name="com.mycompany.myapp.gui.mypager.ShoppingListFragment"
android:id="#+id/shopping_list_fragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:focusable="true" />
</LinearLayout>
Note that onCreateView is called for each custom Fragment, they are inflated and the root View of each of them are returned. Here is one example, for FilteredRecipesFragment. The other custom Fragments are similar.
public class FilteredRecipesFragment extends Fragment {
private FilteredRecipesListFragment mFilteredRecipesListFragment;
private Button showRecipeFilterButton;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.filtered_recipes_fragment, container, false);
mFilteredRecipesListFragment = (FilteredRecipesListFragment)
getFragmentManager().findFragmentById(R.id.filtered_recipes_list_fragment);
showRecipeFilterButton = (Button) rootView.findViewById(R.id.show_recipe_filter_dialog_button);
showRecipeFilterButton.setOnClickListener(new RecipeFilterButtonListener());
return rootView;
}
}
Finally, the custom ViewPager and its custom FragmentPagerAdapter, where the program fails.
public class MyViewPager extends ViewPager{
private MyActivity mMyActivity;
private MyPagerAdapter mMyPagerAdapter;
public MyViewPager(Context context, AttributeSet attrs)
{
super(context, attrs);
mMyActivity = (MyActivity) context;
mMyPagerAdapter = new MyPagerAdapter(mMyActivity.getSupportFragmentManager(), mMyActivity);
this.setAdapter(mMyPagerAdapter);
this.setOnPageChangeListener(mMyActivity);
this.setCurrentItem(PagerConstants.PAGE_SHOPPING_LIST); // Page 0
}
}
MyPagerAdapter.java:
public class MyPagerAdapter extends FragmentPagerAdapter{
private MyActivity mMyActivity;
public MyPagerAdapter(FragmentManager fragmentManager, MyActivity myActivity)
{
super(fragmentManager);
mMyActivity = myActivity;
}
#Override
public Fragment getItem(int position)
{
switch (position) {
case PagerConstants.PAGE_FILTER_RECIPES: // 0
return mMyActivity.getSupportFragmentManager().findFragmentById(R.id.filtered_recipes_fragment);
case PagerConstants.PAGE_SELECTED_RECIPES: // 1
return mMyActivity.getSupportFragmentManager().findFragmentById(R.id.selected_recipes_fragment);
case PagerConstants.PAGE_SHOPPING_LIST: // 2
return mMyActivity.getSupportFragmentManager().findFragmentById(R.id.shopping_list_fragment);
default:
return null;
}
}
#Override
public int getCount()
{
return PagerConstants.NUMBER_OF_PAGES; // 3
}
#Override
public CharSequence getPageTitle(int position)
{
return PagerConstants.PAGE_TITLES(position);
}
}
Everything seems to be working ok, but after every custom Fragment is inflated, the custom ViewPager starts to add them too. Here is the stack output from Eclipse:
06-07 15:37:49.815: E/AndroidRuntime(793): java.lang.IllegalStateException: Can't change container ID of fragment FilteredRecipesFragment{4605b0e0 #0 id=0x7f09003f android:switcher:2131296318:0}: was 2131296319 now 2131296318
BackStackRecord.doAddOp(int, Fragment, String, int) line: 407
BackStackRecord.add(int, Fragment, String) line: 389
MyPagerAdapter(FragmentPagerAdapter).instantiateItem(ViewGroup, int) line: 99
MyViewPager(ViewPager).addNewItem(int, int) line: 832
MyViewPager(ViewPager).populate(int) line: 982
MyViewPager(ViewPager).populate() line: 914
MyViewPager(ViewPager).onMeasure(int, int) line: 1436
MyViewPager(View).measure(int, int) line: 8171
LinearLayout(ViewGroup).measureChildWithMargins(View, int, int, int, int) line: 3132
... More calls <snipped>
In BackStackRecord.doAppOp it fails because the container ID (i.e. the ID of the MyViewPager is different from the Fragment ID. Here is the code for that method:
private void doAddOp(int containerViewId, Fragment fragment, String tag, int opcmd) {
fragment.mFragmentManager = mManager;
if (tag != null) {
if (fragment.mTag != null && !tag.equals(fragment.mTag)) {
throw new IllegalStateException("Can't change tag of fragment "
+ fragment + ": was " + fragment.mTag
+ " now " + tag);
}
fragment.mTag = tag;
}
if (containerViewId != 0) {
if (fragment.mFragmentId != 0 && fragment.mFragmentId != containerViewId) {
// IT FAILS HERE!
throw new IllegalStateException("Can't change container ID of fragment "
+ fragment + ": was " + fragment.mFragmentId
+ " now " + containerViewId);
}
fragment.mContainerId = fragment.mFragmentId = containerViewId;
}
Op op = new Op();
op.cmd = opcmd;
op.fragment = fragment;
addOp(op);
}
I know that the container ID is the ID of the custom ViewPager because it is its ID that is passed through in the instantiateItem(ViewGroup, int) call. In my case, the ID of the MyViewPager instance is 2131296319 and the ID of the Fragment is 2131296318, hence it fails.
Where am I taking the wrong turn here? What am I misunderstanding in the whole ViewPager/FragmentPagerAdapter/Fragment concept?
The problem is here:
#Override
public Fragment getItem(int position)
{
switch (position) {
case PagerConstants.PAGE_FILTER_RECIPES: // 0
return mMyActivity.getSupportFragmentManager().findFragmentById(R.id.filtered_recipes_fragment);
case PagerConstants.PAGE_SELECTED_RECIPES: // 1
return mMyActivity.getSupportFragmentManager().findFragmentById(R.id.selected_recipes_fragment);
case PagerConstants.PAGE_SHOPPING_LIST: // 2
return mMyActivity.getSupportFragmentManager().findFragmentById(R.id.shopping_list_fragment);
default:
return null;
}
you have to return a new instance of your Fragments and not an existing one, which has already a parent and, hence, a container assinged. Remove the Fragments you declared in your layout, and change your getItem like
#Override
public Fragment getItem(int position)
{
switch (position) {
case PagerConstants.PAGE_FILTER_RECIPES: // 0
return new FilteredRecipesFragment();
case PagerConstants.PAGE_SELECTED_RECIPES: // 1
return new SelectedRecipesFragment();
case PagerConstants.PAGE_SHOPPING_LIST: // 2
return new ShoppingListFragment()
default:
return null;
}
One of the possible reason for the issue is when you're trying to add the same fragment twice. Illustrated below
public void populateFragments() {
Fragment fragment = new Fragment();
//fragment is added for the first time
addFragment(fragment);
// fragment is added for the second time
// This call will be responsible for the issue. The
addFragment(fragment);
}
public void addFragment(Fragment fragment) {
FrameLayout frameLayout = AppView.createFrameLayout(context);
view.addView(frameLayout);
getSupportFragmentManager().beginTransaction().add(frameLayout.getId(), fragment).commit();
}

How to use same fragment in a viewPager?

I develope currently a small sample app with fragments and a viewPager. The viewPager shows 3 pages. In each page i instantiate a fragment of the same type. The fragment contains a textView and a button. On button click I want to replace the current fragment with another one. Now my problem is, no matter which button I press only the fragment of page 1 gets replaced. I dont know what I have to do in my pageAdapter class but I guess it has to do with using the same fragment and layout. I think I have to make sure, that my pageAdapter updates the correct page, but how do I achieve that?
For a better understanding why I want to achieve that, that I receive a json string within 3 node of type menu and I want to use each of them as a page in my viewPager.
Can someone show me a short and easy example for such a behavior? I think its a basic approach, so it cant be so difficult.
--------Edit---------
Here is the code:
public class FragmentPagerSupport extends FragmentActivity {
static final int NUM_ITEMS = 4;
MyAdapter mAdapter;
ViewPager mPager;
#Override
public void onBackPressed() {
FragmentManager fm = getFragmentManager();
if (fm.getBackStackEntryCount() > 0) {
fm.popBackStack();
} else {
super.onBackPressed();
}
}
public MyAdapter getmAdapter() {
return mAdapter;
}
public ViewPager getmPager() {
return mPager;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_pager);
mAdapter = new MyAdapter(getFragmentManager(), this);
mPager = (ViewPager) findViewById(R.id.pager);
mPager.setOffscreenPageLimit(NUM_ITEMS + 2);
mPager.setAdapter(mAdapter);
Button button = (Button) findViewById(R.id.goto_first);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
mPager.setCurrentItem(0);
}
});
button = (Button) findViewById(R.id.goto_last);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
mPager.setCurrentItem(NUM_ITEMS - 1);
}
});
}
}
MyAdapter:
public MyAdapter(FragmentManager fm, FragmentPagerSupport fragmentPagerSupport) {
super(fm);
this.fragmentPagerSupport = fragmentPagerSupport;
}
#Override
public int getCount() {
return NUM_ITEMS;
}
#Override
public Fragment getItem(int position) {
Fragment newInstance = null;
switch (position) {
case 0:
newInstance = frag1.newInstance(position);
break;
case 1:
newInstance = frag1.newInstance(position);
break;
case 2:
newInstance = frag2.newInstance(position);
break;
case 3:
newInstance = frag2.newInstance(position);
break;
}
return newInstance;
}
Frag1 & Frag2 & ListItemFrag:
public static class frag1 extends ListFragment {
int mNum;
static frag1 newInstance(int num) {
frag1 f = new frag1();
Supply num input as an argument.
Bundle args = new Bundle();
args.putInt("num", num);
f.setArguments(args);
return f;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mNum = getArguments() != null ? getArguments().getInt("num") : 1;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_pager_list, container, false);
v.setId(mNum);
View tv = v.findViewById(R.id.text);
((TextView) tv).setText("Fragment #" + mNum);
return v;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
String[] cheeses = { "Edamer", "Gauda", "Cheddar", "Mozarella", "Maasdamer" };
setListAdapter(new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, cheeses));
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
Log.i("FragmentList", "Item clicked: " + id);
String itemName = (String) l.getItemAtPosition(position);
Fragment listItemFragment = ListItemFragment.newInstance(itemName);
FragmentTransaction trans = getActivity().getFragmentManager().beginTransaction();
trans.replace(R.id.root, listItemFragment, listItemFragment.getClass().getName() + "_" + mNum);
trans.addToBackStack(itemName);
trans.commit();
}
}
public static class frag2 extends ListFragment {
int mNum;
static frag2 newInstance(int num) {
frag2 f = new frag2();
Bundle args = new Bundle();
args.putInt("num", num);
f.setArguments(args);
return f;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mNum = getArguments() != null ? getArguments().getInt("num") : 1;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_pager_list, container, false);
v.setId(mNum);
View tv = v.findViewById(R.id.text);
((TextView) tv).setText("Fragment #" + mNum);
return v;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
String[] cheeses = { "Edamer", "Gauda", "Cheddar", "Mozarella", "Maasdamer" };
setListAdapter(new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, cheeses));
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
Log.i("FragmentList", "Item clicked: " + id);
String itemName = (String) l.getItemAtPosition(position);
Fragment listItemFragment = ListItemFragment.newInstance(itemName);
FragmentTransaction trans = getActivity().getFragmentManager().beginTransaction();
trans.replace(R.id.root, listItemFragment, listItemFragment.getClass().getName() + "_" + mNum);
trans.addToBackStack(itemName);
trans.commit();
}
}
public static class ListItemFragment extends Fragment {
String itemName;
static ListItemFragment newInstance(String itemName) {
ListItemFragment i = new ListItemFragment();
Bundle args = new Bundle();
args.putString("text", itemName);
i.setArguments(args);
return i;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
itemName = getArguments() != null ? getArguments().getString("text") : "NULL";
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_item, container, false);
View tv = v.findViewById(R.id.textView1);
((TextView) tv).setText("Cheese: " + itemName + " selected!");
return v;
}
}
Pager Layout:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:padding="4dip"
android:gravity="center_horizontal"
android:layout_width="match_parent" android:layout_height="match_parent">
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="0px"
android:layout_weight="1">
</android.support.v4.view.ViewPager>
<LinearLayout android:orientation="horizontal"
android:gravity="center" android:measureWithLargestChild="true"
android:layout_width="match_parent" android:layout_height="wrap_content"
android:layout_weight="0">
<Button
android:id="#+id/goto_first"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="first" />
<Button android:id="#+id/goto_last"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="last">
</Button>
</LinearLayout>
Frag1 Layout:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#99EE11"
android:id="#+id/test">
<TextView android:id="#+id/text"
android:layout_width="match_parent" android:layout_height="wrap_content"
android:gravity="center_vertical|center_horizontal"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="#string/hello_world"/>
<FrameLayout
android:layout_width="match_parent"
android:layout_height="0dip"
android:layout_weight="1"
android:id="#+id/root" >
<ListView android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:drawSelectorOnTop="false"/>
</FrameLayout>
Frag2 Layout:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#99EE11"
android:id="#+id/test2">
<TextView android:id="#+id/text"
android:layout_width="match_parent" android:layout_height="wrap_content"
android:gravity="center_vertical|center_horizontal"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="#string/hello_world"/>
<FrameLayout
android:layout_width="match_parent"
android:layout_height="0dip"
android:layout_weight="1"
android:id="#+id/root2" >
<ListView android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:drawSelectorOnTop="false"/>
</FrameLayout>
ListItemFrag Layout:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/ll"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginTop="230dp"
android:background="#AA33EE"
android:orientation="vertical" >
<TextView
android:id="#+id/textView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge" />
</LinearLayout>
Hi I was facing same kind of issue. I fixed the issue by using
getChildFragmentManager().beginTransaction()
instead of
getActivity().getSupportFragmentManager().beginTransaction()
As in this case we are trying to make transaction from within a fragment (one out of the list of fragments which are attached to the ViewPager, thus the Activity holding the ViewPager) so we have to use getChildFragmentManager() here for desired results.
NOTE: I am using android support v4 library and thus corresponding FragmentManager.

Replacing fragments within viewpager

I am currently having an issue with replacing a certain fragment within ViewPager with another. The fragment id like to replace is my "Departments" which has an Imagebutton id like to use to begin the replacement. I've tried to apply some suggestions from other similar questions (most of which were old and prior to the new api release which allows for nested fragments) and have had no success. Would using nested fragments be easier? I am new to android app development so any help would be great. Thanks in advance.
here is my FragmentAcitivty
public class ViewPagerStyle extends FragmentActivity {
private ViewPager mViewPager;
private ViewPagerAdapter adapter;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
setUpView();
setTab();
}
private void setUpView(){
mViewPager = (ViewPager) findViewById(R.id.viewPager);
adapter = new ViewPagerAdapter(getApplicationContext(),getSupportFragmentManager());
mViewPager.setAdapter(adapter);
mViewPager.setCurrentItem(0);
}
private void setTab(){
mViewPager.setOnPageChangeListener(new OnPageChangeListener(){
#Override
public void onPageScrollStateChanged(int position) {}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {}
#Override
public void onPageSelected(int position) {
// TODO Auto-generated method stub
switch(position){
case 0:
findViewById(R.id.first_tab).setVisibility(View.VISIBLE);
findViewById(R.id.second_tab).setVisibility(View.INVISIBLE);
findViewById(R.id.third_tab).setVisibility(View.INVISIBLE);
break;
case 1:
findViewById(R.id.first_tab).setVisibility(View.INVISIBLE);
findViewById(R.id.second_tab).setVisibility(View.VISIBLE);
findViewById(R.id.third_tab).setVisibility(View.INVISIBLE);
break;
case 2:
findViewById(R.id.first_tab).setVisibility(View.INVISIBLE);
findViewById(R.id.second_tab).setVisibility(View.INVISIBLE);
findViewById(R.id.third_tab).setVisibility(View.VISIBLE);
break;
}
}
});
}
}
FragmentPagerAdapter
public class ViewPagerAdapter extends FragmentPagerAdapter {
private Context _context;
public ViewPagerAdapter(Context context, FragmentManager fm) {
super(fm);
_context = context;
}
#Override
public Fragment getItem(int position) {
Fragment f = new Fragment();
switch(position){
case 0:
f=PubView.newInstance(_context);
break;
case 1:
f=MyView.newInstance(_context);
break;
case 2:
f=Departments.newInstance(_context);
break;
}
return f;
}
#Override
public int getCount() {
return 3;
}
}
Departments Fragment with button
public class Departments extends Fragment {
public static Fragment newInstance(Context context) {
Departments f = new Departments();
return f;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
View root = (View) inflater.inflate(R.layout.activity_departments, null);
ImageButton engineeringButton = (ImageButton)root.findViewById(R.id.engineeringButton);
engineeringButton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
Fragment newFragment = Engineering.newInstance(null);
FragmentTransaction transaction = getChildFragmentManager().beginTransaction();
transaction.addToBackStack(null);
transaction.replace(R.id.viewPager, newFragment).commit();
}
});
return root;
}
}
Also, here is my main.xml file which hosts the viewpager
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#color/purple"
android:orientation="vertical" >
<TableLayout
style="#style/layout_f_w"
android:stretchColumns="*" >
<TableRow
android:id="#+id/tableRow1"
style="#style/layout_wrap"
android:background="#color/white" >
<!-- First Tab -->
<LinearLayout
android:id="#+id/first_text"
style="#style/layout_f_w"
android:orientation="vertical" >
<TextView
android:id="#+id/textView1"
style="#style/text_title"
android:text="pubView"
android:textColor="#color/purple" />
</LinearLayout>
<!-- Second Tab -->
<LinearLayout
android:id="#+id/second_text"
style="#style/layout_f_w"
android:orientation="vertical" >
<TextView
android:id="#+id/textView1"
style="#style/text_title"
android:gravity="center"
android:text="myView"
android:textColor="#color/purple" />
</LinearLayout>
<!-- Third Tab -->
<LinearLayout
android:id="#+id/third_text"
style="#style/layout_f_w"
android:orientation="vertical" >
<TextView
android:id="#+id/textView1"
style="#style/text_title"
android:text="Dept."
android:textColor="#color/purple" />
</LinearLayout>
</TableRow>
</TableLayout>
<!-- Include Tab Indicator -->
<include
android:layout_width="fill_parent"
android:layout_height="wrap_content"
layout="#layout/indicator" />
<android.support.v4.view.ViewPager
android:id="#+id/viewPager"
android:layout_width="fill_parent"
android:layout_height="450dp" />
<ImageButton
android:id="#+id/settingsButton"
android:layout_width="wrap_content"
android:layout_height="30dp"
android:layout_marginLeft="50dp"
android:background="#drawable/settings_button"
android:src="#drawable/settings_button" />
</LinearLayout>
One thing i am confused on is that I don't know which id to put into the first argument of transaction.replace(r.id.viewPager, newfragment)...Ive read that it needs the id of the container but when I use this I receive the runtime error from logcat:
04-13 21:41:48.680: E/AndroidRuntime(960): java.lang.IllegalArgumentException: No view found for id 0x7f0a0029 (com.pvcalendar:id/viewPager) for fragment Engineering{4089a730 #0 id=0x7f0a0029}
I think the point is to use a fragment as a container.
In your ViewPagerAdapter:
#Override
public Fragment getItem(int position) {
/*
* IMPORTANT: This is the point. We create a RootFragment acting as
* a container for other fragments
*/
if (position == 0)
return new RootFragment();
else
return new StaticFragment();
}
RootFragment layout should look like:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/root_frame" >
</FrameLayout>
And directly, you fill it with your first "real" fragment:
public class RootFragment extends Fragment {
private static final String TAG = "RootFragment";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
/* Inflate the layout for this fragment */
View view = inflater.inflate(R.layout.root_fragment, container, false);
FragmentTransaction transaction = getFragmentManager()
.beginTransaction();
/*
* When this container fragment is created, we fill it with our first
* "real" fragment
*/
transaction.replace(R.id.root_frame, new FirstFragment());
transaction.commit();
return view;
}
}
Finally, you can replace fragments. For instance, inside your "real" fragment you could have a button:
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
FragmentTransaction trans = getFragmentManager()
.beginTransaction();
/*
* IMPORTANT: We use the "root frame" defined in
* "root_fragment.xml" as the reference to replace fragment
*/
trans.replace(R.id.root_frame, new SecondFragment());
/*
* IMPORTANT: The following lines allow us to add the fragment
* to the stack and return to it later, by pressing back
*/
trans.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
trans.addToBackStack(null);
trans.commit();
}
});
I've developed an example application that shows a similar concept. You could replace a fragment inside a ViewPager without changing to a new Activity. The code is available in:
https://github.com/danilao/fragments-viewpager-example
I'm assuming you want the Engineering fragment to be on a completely new page, because you aren't using it in your ViewPagerAdapter. If that's the case, create a new Activity, with your Engineering fragment in the layout, and launch the Activity from the engineeringButton click.
The problem is you are trying to shove your Engineering fragment into the View hierarchy of R.layout.activity_departments, and there is (hopefully) no ViewPager in there, hence the error.

Android - Multiple fragments in ONE tab

I searched a lot in the web about the possibility to have multiple fragments in one action bar tab.
This question comes closest to my needs but the code is not working.
Is there another possibility to include multiple fragments in one tab?
This is the StartActivity
public class StartActivity extends FragmentActivity implements ActionBar.TabListener {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_start);
// Set up the action bar.
final ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
actionBar.addTab(
actionBar.newTab()
.setText("Karte")
.setTabListener(new MapFragmentListener(this)));
}
The corresponding layout acticity_start contains two frame layouts for the two fragments that will be placed in the tab.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<FrameLayout
android:id="#+id/fragment_map"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
<FrameLayout
android:id="#+id/fragment_realtime"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
The TabListener looks like this:
private class TabListener implements ActionBar.TabListener {
private static final String fragment1_tag = "fragment1_tag";
private static final String fragment2_tag = "fragment2_tag";
private FragmentActivity activity;
private RealtimeFragment fragment1;
private RealtimeFragment fragment2;
public TabListener(FragmentActivity activity) {
this.activity = activity;
android.support.v4.app.FragmentTransaction ft = activity.getSupportFragmentManager().beginTransaction();
fragment1 = (RealtimeFragment) activity.getSupportFragmentManager().findFragmentByTag(fragment1_tag);
if (fragment1 != null && !fragment1.isDetached()) {
ft.detach(fragment1);
}
fragment2 = (RealtimeFragment) activity.getSupportFragmentManager().findFragmentByTag(fragment2_tag);
if (fragment2 != null && !fragment2.isDetached()) {
ft.detach(fragment2);
}
ft.commit();
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
}
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
android.support.v4.app.FragmentTransaction fragmentTransaction = activity.getSupportFragmentManager().beginTransaction();
if(fragment1 == null) {
fragment1 = new RealtimeFragment();
fragmentTransaction.add(R.id.fragment_map, fragment1, fragment1_tag);
} else {
fragmentTransaction.attach(fragment1);
}
if(fragment2 == null) {
fragment2 = new RealtimeFragment();
fragmentTransaction.add(R.id.fragment_realtime, fragment2, fragment2_tag);
} else {
fragmentTransaction.attach(fragment2);
}
fragmentTransaction.commit();
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
android.support.v4.app.FragmentTransaction fragementTransaction = activity.getSupportFragmentManager().beginTransaction();
if(fragment1_tag != null)
fragementTransaction.detach(fragment1);
if(fragment2 != null)
fragementTransaction.detach(fragment2);
fragementTransaction.commit();
}
}
The class RealtimeFragment and the corresponding layout fragment_realtime looks like this:
public class RealtimeFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_realtime, container, false);
return view;
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button" />
</LinearLayout>
In one tab now two fragments of the class RealtimeFragment should be displayed. The fragments just show one button but NOTHING is displayed! Why?
I was looking for a solution to the same Topic, and found this, which comes in quite handy.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent">
<fragment android:name="com.example.news.ArticleListFragment"
android:id="#+id/list"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="match_parent" />
<fragment android:name="com.example.news.ArticleReaderFragment"
android:id="#+id/viewer"
android:layout_weight="2"
android:layout_width="0dp"
android:layout_height="match_parent" />
</LinearLayout>
so Reference your Fragments and inflate it, just like a normal Fragment

Categories

Resources