I am trying to call the AsyncTask from another fragment rather than the class where i declared the AsyncTask. I used the custom tab layout with viewpager. Tab layout contains four tabs. I want to call a web service when particular tab is selected. So that i wrote the OnTabSelected() in main fragment in which i used tablayout. My AsyncTask is in the second tab. I want to call the webservice when second tab is selected in OnTabSelected() method. I am new in android development. So how can in do this?
Asked
Active
Viewed 418 times
1 Answers
0
use viewpager's addOnPageChangeListener
event like this:
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
@Override
public void onPageSelected(int position) {
if(position == 1){
//call your webservice here
}
}
@Override
public void onPageScrollStateChanged(int state) {
}
});
note that page position start with 0 so your second tab position is 1.
edit: how to get Instance of current fragment
Fragment f = getActivity().getFragmentManager().findFragmentById(R.id.fragment_container);
if (f instanceof SecondFragmentClass) {
f.doSomething();
}
note: you can use findFragmentByTag() in place of findFragmentById, if you have provided tag
update:
if(position == 1){
Fragment page = getSupportFragmentManager().findFragmentByTag("android:switcher:" + R.id.pager + ":" + ViewPager.getCurrentItem());
// based on the current position you can then cast the page to the correct
// class and call the method:
if (page != null) {
((SecondFragmentClass)page).updateList("new item");
}
return true;
}
check this ans for better understandig https://stackoverflow.com/a/18611036/5895830

Community
- 1
- 1

Sagar Chavada
- 5,169
- 7
- 40
- 67
-
How can i take the instance of the current fragment means second fragment to execute the task? – vaibhav May 15 '17 at 05:47