简体   繁体   中英

How to call AsyncTask from another fragment while using Tablayout with viewpager?

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?

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

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