Open fragment from a fragment in android - android

I have a Activity extending to FragmentActivity which has 4 fragments. I now want to open fragment2 on button click which is present in fragment1.
In short I want to switch from fragment1 to fragment 2 on button click.
My code is:
public class SampleActivity extends FragmentActivity{
static ViewPager mViewPager;
PagingAdapter TabAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TabAdapter = new PagingAdapter(getSupportFragmentManager(), this);
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(TabAdapter);
}
public class PagingAdapter extends FragmentPagerAdapter {
private Context context;
public PagingAdapter(FragmentManager fm, Context context) {
super(fm);
this.context = context;
}
#Override
public Fragment getItem(int i) {
switch(i){
case 0:
return new Fragment1();
case 1:
return new Fragment2();
case 2:
return new Fragment3();
case 3:
return new Fragment4();
}
return null;
}
#Override
public int getCount() {
return 4;
}
#Override
public CharSequence getPageTitle(int position) {
switch(position){
case 0:
return context.getString(R.string.page_tab_1);
case 1:
return context.getString(R.string.page_tab_2);
case 2:
return context.getString(R.string.page_tab_3);
case 3:
return context.getString(R.string.page_tab_4);
}
return "Fragment " + (position + 1);
}
}
public class Fragment1 extends Fragment{
Button btn_close = (Button) mydeals.findViewById(R.id.btn_close);
btn_all.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Needs to open fragment2 here.
});
}
I have tried shifting using id but fragment4 is opening by the below code
ViewPager viewpager = DealsActivity.mViewPager;
viewpager.setCurrentItem(getId());

In your Fragment1 layout, add the attribute android:onClick="buttonClickMethod" in your Button definition. Then in your activity, add the following method :
public void buttonClickMethod(View v) {
// some code to execute after button click
// ....
// You can open fragment 2 here, like this :
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.LAYOUT_ID_FOR_FRAGMENT2, FRAGMENT2);
ft.commit();
}
Note that the name of that method is the same one defined in android:onClick attribute.

Related

Fragments display getting reset

I have setup a list of fragments using TabLayout and ViewPager on MainActivity as such
public class MainActivity extends AppCompatActivity implements Fragment1.OnFragmentInteractionListener, Fragment2.OnFragmentInteractionListener, Fragment3.OnFragmentInteractionListener, Fragment4.OnFragmentInteractionListener
, Fragment5.OnFragmentInteractionListener{
TabLayout tabLayout;
ViewPager viewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportActionBar().hide();
setContentView(R.layout.activity_main);
viewPager = (ViewPager) findViewById(R.id.viewPager);
viewPager.setAdapter(new CustomAdapater(getSupportFragmentManager(), getApplicationContext()));
tabLayout = (TabLayout) findViewById(R.id.tabLayout);
tabLayout.setupWithViewPager(viewPager);
tabLayout.setSelectedTabIndicatorColor(Color.parseColor("#51ffff"));
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
switch (tab.getPosition()) {
case 0:
tabLayout.setSelectedTabIndicatorColor(Color.parseColor("#ced21f"));
break;
case 1:
tabLayout.setSelectedTabIndicatorColor(Color.parseColor("#51ffff"));
break;
case 2:
tabLayout.setSelectedTabIndicatorColor(Color.parseColor("#FF0000"));
break;
}
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
});
}
#Override
public void onFragmentInteraction(Uri uri) {
}
private class CustomAdapater extends FragmentPagerAdapter {
private String fragments[] = {"Control", "Connection", "Log", "Others", "Others2"};
public CustomAdapater(FragmentManager supportFragmentManager, Context applicationContext) {
super(supportFragmentManager);
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new Fragment1();
case 1:
return new Fragment3();
case 2:
return new Fragment2();
case 3:
return new Fragment4();
case 4:
return new Fragment5();
default:
return null;
}
}
#Override
public int getCount() {
return fragments.length;
}
#Override
public CharSequence getPageTitle(int position) {
return fragments[position];
}
}
}
Somehow when I transit from Fragment1 to Fragment3 and back to Fragment1, the views on Fragment1 gets reset to original state(Like it was just created).
This only happens if I transit 2 fragment away from the current Fragment. For example 2->4 or 3->1.
Everything is fine if the transition is next to each other, for example 2->3 or 1->2.
This is my first android app so do pardon me.
It seems like it is creating a new fragment instead loading of existing ones
Your fragment get destroyed due to the fact that by default viewpager retain only one fragment at a time while moving around so you can simply use
viewPager.setOffscreenPageLimit(no_of_fragment_to_retain);
or
viewPager.setOffscreenPageLimit(3); // in your case
so when you come back from 4->1 or 3->1 you will get the previous stored state of your fragment. link to docs
First :
viewPager.setAdapter(new CustomAdapater(getSupportFragmentManager(), getBaseContext()));
Now see : in get Item method of View pager evrytime when you go to new tab a new instance of fragment is created So the previous view is lost . You should retain state in your fragment class.
or a simple solution is use FragmentstatepagerAdapter instead of FragmentPagerAdapter in your Adapter class.
Let me know if it helps

Change Fragment from other Fragment like Navigation links

I have a Navigation Drawer (so I use Fragments):
MainActivity (FragmentActivity)
Fragment A (Fragment with pictures links for Fragment B, C & D)
Fragment B (Fragment)
Fragment C (Fragment)
Fragment D (Fragment)
My navigation drawer works correctely, but I want to my Fragment A to do links like the menu. Right now, in Fragment A, I call the other Fragments like this:
ImageView contact = (ImageView) getView().findViewById(R.id.secondBlock);
contact.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Fragment fragment = new ContactezNous();
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.accueil, fragment);
fragmentTransaction.commit();
}
});
But I don't want to use this way, because I have problems finding tags and ids of other Fragments.
I want to know how to change Fragments frome Fragment A by clicking on the link like if I was clicking on the Navigation Drawer links of the Main Activity.
Main Activity:
public class MainActivity extends AppCompatActivity implements FragmentDrawer.FragmentDrawerListener {
private static String TAG = MainActivity.class.getSimpleName();
private Toolbar mToolbar;
private FragmentDrawer drawerFragment;
//Initialisation de l activite avec les donnees necessaires
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);
getSupportActionBar().setDisplayShowHomeEnabled(true);
drawerFragment = (FragmentDrawer) getSupportFragmentManager().findFragmentById(R.id.fragment_navigation_drawer);
drawerFragment.setUp(R.id.fragment_navigation_drawer, (DrawerLayout) findViewById(R.id.drawer_layout), mToolbar);
drawerFragment.setDrawerListener(this);
// Affichage de la navigation
displayView(0);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
//Ajout des items
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onDrawerItemSelected(View view, int position) {
displayView(position);
}
private void displayView(int position) {
Fragment fragment = null;
String title = getString(R.string.app_name);
switch (position) {
case 0:
fragment = new Accueil();
title = getString(R.string.title_accueil);
break;
case 1:
fragment = new NosOffres();
title = getString(R.string.title_nosoffres);
break;
case 2:
fragment = new DemandeGratuite();
title = getString(R.string.title_demandegratuite);
break;
case 3:
fragment = new ContactezNous();
title = getString(R.string.title_contact);
break;
case 4:
fragment = new Actualites();
title = getString(R.string.title_actu);
break;
case 5:
fragment = new MentionsLegales();
title = getString(R.string.title_mentions);
break;
default:
break;
}
if (fragment != null) {
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.container_body, fragment);
//fragmentTransaction.addToBackStack("name");
fragmentTransaction.commit();
// libelle du toolbar
TextView titlet;
titlet = (TextView) findViewById(R.id.main_toolbar_title);
titlet.setText(title);
titlet.setTypeface(Typeface.createFromAsset(getAssets(), "fonts/GothamBook.ttf"));
}
}
}
You should use the following common Android fragment pattern:
public class Accueil extends Fragment {
// Your code here...
public interface OnFragmentInteractionListener {
void onInteraction(int id);
}
private OnFragmentInteractionListener mListener;
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (OnFragmentInteractionListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString() + " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
// ...more code...
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// ...initialize your View...
ImageView contact = (ImageView) getView().findViewById(R.id.secondBlock);
contact.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// This is how you use the listener
mListener.onInteraction(3);
}
});
// ...more initialization...
}
}
MainActivity.java
public class MainActivity AppCompatActivity
implements FragmentDrawer.FragmentDrawerListener, OnFragmentInteractionListener {
// Your code here...
// Implement OnFragmentInteractionListener
#Override
public void onInteraction(int id) {
// 'id' would be '3' for your 'ContactezNous' fragment
displayView(id);
}
}

Reload or refresh list fragment when swiped or when tab is selected?

i am unable to reload/refresh Listfragment (CfFragment(),PfFragment(),IfFragment() in my below code) when tab is selected or swiped, can any one tell me where i am going wrong.My code is working well when it is created for the first time but it doesn't reload/refresh when swiped or selected.If i change anything in the 1st listfragment it should affect in the 2nd list fragment and so on...
Please can any one help me out.it would be much appreciated.
Thank you.
public class busy extends FragmentActivity implements
ActionBar.TabListener {
SessionManager session;
AppSectionsPagerAdapter mAppSectionsPagerAdapter;
static ServiceURL URL;
static AlertDialogManager alert = new AlertDialogManager();
ViewPager mViewPager;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.busy);
session = new SessionManager(getApplicationContext());
mAppSectionsPagerAdapter = new AppSectionsPagerAdapter(getSupportFragmentManager());
final ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mAppSectionsPagerAdapter);
mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
});
for (int i = 0; i < mAppSectionsPagerAdapter.getCount(); i++) {
actionBar.addTab(actionBar.newTab().setText(mAppSectionsPagerAdapter.getPageTitle(i)).setTabListener(this));
}
}
#Override
public void onTabUnselected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
}
#Override
public void onTabSelected(ActionBar.Tab tab,FragmentTransaction fragmentTransaction) {
mViewPager.setCurrentItem(tab.getPosition());
//mViewPager.setAdapter(mAppSectionsPagerAdapter);
}
#Override
public void onTabReselected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
}
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
public static class AppSectionsPagerAdapter extends FragmentPagerAdapter {
public AppSectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int i) {
switch (i) {
case 0:
return new CfFragment();
case 1:
return new PfFragment();
case 2:
return new IfFragment();
}
return null;
}
#Override
public int getCount() {
return 3;
}
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "Confy";
case 1:
return "Peny";
case 2:
return "Incy";
default:
break;
}
return null;
}
}
}
Derive your AppSectionsPagerAdapter class as
public static class AppSectionsPagerAdapter extends FragmentStatePagerAdapter
instead of
public static class AppSectionsPagerAdapter extends FragmentPagerAdapter
Basically, FragmentPagerAdapter keeps the created Fragments in memory, while FragmentStatePagerAdapter destroys and creates them anew as they are shifted in and out of view.
Two more things:
1. Make sure you are not calling setRetainInstance(true) in any of your Fragments, else they won't be recreated.
2. Add
viewPager.setOffscreenPageLimit(0);
to your code.
EDIT:
Instead of
Activity -> ViewPager -> Fragments
create the structure as
Activity -> Fragment -> ViewPager -> Nested Fragments
This will ensure that each Fragment is refreshed on tab change. See this post for the implementation.

Show fragment inside viewpager from another fragment

Hello I'm developing an android app using 3 Fragments (Fragment A, B, C) inside viewpager and tabs, the viewpager works fine. The fragment A contains a List View, when the user clicks a item, the app open a Fragment Dialog with information about the item selected. This dialog has a button called "Add to favorites". Now I want to do this when user press button:
close the fragment dialog
show the fragment B inside the view pager
send the information from dialog fragment to fragment B
How can I do this?
This is part of my code:
* MainFragmentActivity * (This works fine)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tube);
// Set up the action bar.
final ActionBar actionBar = getSupportActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
// When swiping between different sections, select the corresponding
// tab. We can also use ActionBar.Tab#select() to do this if we have
// a reference to the Tab.
mViewPager
.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
});
for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
actionBar.addTab(actionBar.newTab()
.setText(mSectionsPagerAdapter.getPageTitle(i))
.setTabListener(this));
}
}
#Override
public void onTabSelected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
// When the given tab is selected, switch to the corresponding page in
// the ViewPager.
mViewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
}
#Override
public void onTabReselected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
FragmentA a = new FragmentA();
Bundle args1 = new Bundle();
args1.putInt(FragmentA.ARG_SECTION_NAME , position + 1);
a.setArguments(args1);
return a;
case 1:
FragmentB b= new FragmentB();
Bundle args2 = new Bundle();
args2.putInt(FragmentB.ARG_SECTION_NAME , position + 2);
b.setArguments(args2);
return b;
case 2:
FragmentC c= new FragmentC();
Bundle args3 = new Bundle();
args3.putInt(FragmentC.ARG_SECTION_NAME , position + 3);
c.setArguments(args3);
return c;
default:
return null;
}
}
This is the Fragment Dialog
* FragmentDialogView *
public class FragmentDialogView extends DialogFragment implements OnClickListener {
private static final int REAUTH_ACTIVITY_CODE = 0;
private String videoId;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Bundle mArgs = getArguments();
View view = (View) inflater.inflate(R.layout.fragment_dialog_view, container, false);
//Buttons
Button button = (Button) view.findViewById(R.id.button_one);
button.setOnClickListener(this);
buttonDownload.setOnClickListener(this);
return view;
}
#Override
public void onSaveInstanceState(Bundle bundle) {
super.onSaveInstanceState(bundle);
}
#Override
public void onResume() {
super.onResume();
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REAUTH_ACTIVITY_CODE) {
}
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.button_one:
//Here it should show the fragment B inside the viewpager
break;
default:
break;
}
}
}
To dismiss the Dialog include the following in your DialogFragment's class
private Dialog dialog;
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
dialog = new Dialog(getActivity());
return dialog;
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.button_one:
dismiss();
break;
default:
break;
}
}
And create a interface
Create the following Communicator.java
public interface Communicator {
public void respond(int i);
}
Implement this Communicator in your MainAcitvity
And create a instance of this Communicator in your fragment like this
public class FragmentDialogView extends DialogFragment implements OnClickListener {
private Communicator com;
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
com = (Communicator) getActivity();
btn.setOnClickListener(this);
}
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.btn:
com.respond(1);
break;
}
}
Whenever you click that button it sends the int to the method which is residing inside the MainActivity
which will look like following
#Override
public void respond(int i) {
// Receive a bundle here
// and pass the corresponding information to the FragmentB
// here i'm receving an int and pass it to the FragmentB as a String
FragmentManager fm = getFragmentManager();
FragmentB fragment = (FragmentB) fm.findFragmentByTag("FragmentB");
fragment.fromMainActivity(""+i);
// If the above the one doesn't work keep the instance as Static and then try
viewPager.invalidate();
pagerAdapter.notifyDataSetChanged();
viewPager.setCurrentItem(1, true);
// Inside the setCuttentItem() method 0 first tab
// 1 second tab
// 2 third tab and so on
}
Here I'm receiving an int . You can use a bundle to pass the corresponding information. This will change the viewPager to show the next tab as well
and keep any simple method insdie the FragmentB like the following
public void fromMainActivity(String sample) {
Toast.makeText(getActivity(), sample, duration).show();
}
I hope this would help :) Happy coding
1.Try this : getDialog().dismiss();
2.As I understood correctly, create a method like this in your fragment ,
public static FirstFragment newInstance(String text){
FirstFragment f= new FirstFragment();
return f;
}
Call it in your button onClick() such as FirstFragment.newInstance("Fragment, Instance 1");
3.Create Interface with the method in your DialogFragment can call to pass any data you want back to Fragment that created said DialogFragment. Also set your Fragment as target such as myFragmentDialog.setTargetFragment(this, 0). Then in dialog, get your target fragment object with getTargetFragment() and cast to interface you created. Now you can pass the data using ((MyInterface)getTargetFragment()).methodToPassData(data).
For more info : link

How to handle AsyncTask's in ActionBarActivity Fragments when ViewPager is used?

I'm using ActionBarActivity to create 5 tabs. I have used ViewPager to swipe between the 5 tabs using SectionsPagerAdapter which extends FragmentPagerAdapter. Each tab has a fragment with an asynctask called in oncreateview method. When I'm in one fragment, asynctask in other fragment is being called.
I tried using toast messages in oncreateview method is each fragment instead of asynctask. But wrong toast messages are being fired in wrong fragment.
Oncreate method code:
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.pager_exp);
mViewPager.setAdapter(mSectionsPagerAdapter);
mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position)
{
actionBar.setSelectedNavigationItem(position);
actionBar.setTitle(getHomePageTitle(position));
}
});
for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++)
{
// Create a tab with text corresponding to the page title defined by
// the adapter. Also specify this Activity object, which implements
// the TabListener interface, as the callback (listener) for when
// this tab is selected.
actionBar.addTab(actionBar.newTab()
.setIcon(getPagedrawable(i))
.setTabListener(this));
}
// Adapter class code:
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm)
{
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position)
{
case 0:
Fragment1 f1 = new Fragment1();
return f1;
case 1:
Fragment2 f2 = new Fragment2();
return f2;
case 2:
Fragment3 f3 = new Fragment3();
return f3;
case 3:
Fragment4 f4 = new Fragment4();
return f4;
case 4:
Fragment5 f5 = new Fragment5();
return f5;
}
return null;
}
#Override
public int getCount() {
// Show 5 total pages.
return 5;
}
}
Fragemnt class code :
public class F1 extends Fragment
{
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
}
#SuppressLint("NewApi")
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.f1,container, false);
Toast.makeText(getActivity(), "F1", Toast.LENGTH_SHORT).show();
return view;
}
}
The FragmentPagerAdapter keeps additional fragments, besides the one shown, in resumed state. The solution is to implement a custom OnPageChangeListener and create a new method for when the fragment is shown.
1) Create LifecycleManager Interface
The interface will have two methods and each ViewPager’s Fragment will implement it. These methods Are as follows:
public interface FragmentLifecycle {
public void onPauseFragment();
public void onResumeFragment();
}
2) Let each Fragment implement the interface
Add iplements statement for each class declaration:
public class FragmentBlue extends Fragment implements FragmentLifecycle
public class FragmentGreen extends Fragment implements FragmentLifecycle
public class FragmentPink extends Fragment implements FragmentLifecycle
3) Implement interface methods in each fragment
In order to check that it really works as expected, I will just log the method call and show Toast:
#Override
public void onPauseFragment() {
Log.i(TAG, "onPauseFragment()");
Toast.makeText(getActivity(), "onPauseFragment():" + TAG, Toast.LENGTH_SHORT).show();
}
#Override
public void onResumeFragment() {
Log.i(TAG, "onResumeFragment()");
Toast.makeText(getActivity(), "onResumeFragment():" + TAG, Toast.LENGTH_SHORT).show();
}
4) Call interface methods on ViewPager page change
You can set OnPageChangeListener on ViewPager and get callback each time when ViewPager shows another page:
pager.setOnPageChangeListener(pageChangeListener);
5) Implement OnPageChangeListener to call your custom Lifecycle methods
Listener knows the new position and can call the interface method on new Fragment with the help of PagerAdapter. I can here call onResumeFragment() for new fragment and onPauseFragment() on the current one.
I need to store also the current fragment’s position (initially the current position is equal to 0), since I don’t know whether the user scrolled from left to right or from right to left. See what I mean in code:
private OnPageChangeListener pageChangeListener = new OnPageChangeListener() {
int currentPosition = 0;
#Override
public void onPageSelected(int newPosition) {
FragmentLifecycle fragmentToShow = (FragmentLifecycle)pageAdapter.getItem(newPosition);
fragmentToShow.onResumeFragment();
FragmentLifecycle fragmentToHide = (FragmentLifecycle)pageAdapter.getItem(currentPosition);
fragmentToHide.onPauseFragment();
currentPosition = newPosition;
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) { }
public void onPageScrollStateChanged(int arg0) { }
};
I didn't write the code. Full tutorial here: http://looksok.wordpress.com/2013/11/02/viewpager-with-detailed-fragment-lifecycle-onresumefragment-including-source-code/
Use this
viewPager.setOffscreenPageLimit(1); // the number of pages you want to load in background
and also a ProgressDialogue.
ViewPager creates views for fragments adjacent to your current page. This also gives you an opportunity to load any data required for the adjacent fragments. If you are using AsyncTasks to load data, using this feature will result in a better user experience. But if you need an event when a particular page is opened by the viewpager, LordRaydenMK's solution will work.
See my post on the following thread for using AsyncTasks in a ViewPager:
AsyncTask runs on each page of the ViewPager
Hi You can try by using tag of each fragment and call method of each fragment on Page Changed
mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
actionBar.setTitle(getHomePageTitle(position));
Fragment f = getFragrmentManager().findFragmentByTag(
"" + position);
if (f != null)
f.refresh();
}
});
and on
#Override
public Fragment getItem(int position) {
Fragment f=null;
switch (position)
{
case 0:
f = new Fragment1();
break;
case 1:
f = new Fragment2();
break;
case 2:
f = new Fragment3();
break;
case 3:
f = new Fragment4();
break;
case 4:
f = new Fragment5();
break;
}
f.setTag(""+position);
return f;
}

Categories

Resources