简体   繁体   中英

android how to add same fragments with different activities

Activity A

  SectionPagerAdapter pageradapter = new SectionPagerAdapter(getSupportFragmentManager());
                pageradapter.addFragment(ContactsFragment.newInstance(), "PHONE CONTACTS");
                pageradapter.addFragment(CustomersFragment.newInstance(), "CUSTOMERS");
               viewPager.setAdapter(pageradapter);

Activity B

 SectionPagerAdapter pageradapter = new SectionPagerAdapter(getSupportFragmentManager());
                    pageradapter.addFragment(ContactsFragment.newInstance(), "PHONE CONTACTS");
                    pageradapter.addFragment(CustomersFragment.newInstance(), "CUSTOMERS");
                   viewPager.setAdapter(pageradapter);

I am using fragments and viewpager in my android application.In activity A i have added one fragment with viewpager it is working fine.Now the issue is i want to use the same fragment in Activity B also.

Note: when i add the same fragment in viewpager its throwing error like

java.lang.ClassCastException: app.com.Contacts.ContactsActivity cannot be cast to app.com.Contacts.Activity.CustomersActivity

In your Fragment 's code you cast the activity to ContactsActivity . This is why you can not reuse it. So, you have to remove this cast from your Fragment 's code.

If you would like to call an Activity function which the Fragment is attached. You can do it with interfaces. If your activities implements the same interface. It is enough to cast the Activity to the interface in your Fragment 's code.

class FragmentA {
   private void myMehod() {
      ((MyInterface)getActivity()).callMethodOnActivity()
   }
}

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