Android AsyncTask使用ViewPager在错误的ActionBar选项卡中执行

时间:2014-09-29 09:45:49

标签: android android-fragments android-asynctask tabs android-viewpager

我已使用ActionBar实施了ViewPager标签。我有三个标签。在第三个标签中,我执行了一个AsyncTask来获取List。如果我调试应用程序,我发现当我在默认选项卡(Tab 1)之后首先单击任何选项卡时,AsyncTask会被执行。这意味着即使单击第一个选项卡后单击第二个选项卡,AsyncTask也会执行。我希望它仅在选择第三个选项卡时执行。

这是我的代码:

StatusUpdate.java

public class StatusUpdate extends FragmentActivity implements ActionBar.TabListener {
    private String accesstoken, refreshToken;       
    private StorageHelper helper;    
    private ViewPager viewPager;    
    private ActionBar actionBar;    
    private TabsPagerAdapter mAdapter;    
    private String[] tabs = { "Tab1", "Tab2", "Tab3"};
    private int[] icons ={R.drawable.running,R.drawable.color_icons_green_home, R.drawable.report};    
    protected boolean canContinue = true;    
    protected ProgressDialog pd;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.statusupdate);
        viewPager = (ViewPager) findViewById(R.id.pager);
        actionBar = getActionBar();
        mAdapter = new TabsPagerAdapter(getSupportFragmentManager());     
        viewPager.setAdapter(mAdapter);
        actionBar.setHomeButtonEnabled(false);
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);                 
        ConnectionDetector cd = new ConnectionDetector(getApplicationContext());
        if (cd.isConnectingToInternet()== false) {
            new AlertDialog.Builder(this)
                .setTitle("Network error")
                .setMessage("Please check your internet connection")
                .setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {    
                public void onClick(DialogInterface dialog, int which) { 
                    canContinue  = false;
                    finish();
                }
            })
            .show();
        } else if (canContinue) {   
            // Adding Tabs
            for (int i= 0; i< tabs.length && i< icons.length; i++) {
            actionBar.addTab(actionBar.newTab().setText(tabs[i]).setIcon(icons[i]).setTabListener(this));
       }

       /**
        * on swiping the viewpager make respective tab selected
       **/
       viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {    
           @Override
           public void onPageSelected(int position) {
               // on changing the page
               // make respected tab selected
               actionBar.setSelectedNavigationItem(position);                
           }

           @Override
           public void onPageScrolled(int arg0, float arg1, int arg2) {
           }

           @Override
           public void onPageScrollStateChanged(int arg0) {
           }
       });    
    }

TabPagerAdapter.java

public class TabsPagerAdapter extends FragmentPagerAdapter {
    public TabsPagerAdapter(FragmentManager fm) {
        super(fm);
    }     
    @Override
    public Fragment getItem(int index) {     
        switch (index) {
            case 0:
                // Running late fragment
                return new Tab1();
            case 1:
               // WFH fragment
               return new Tab2();
            case 2:
               // Report fragment
               return new Tab3();               
        }     
        return null;
    }

    @Override
    public int getCount() {
        // get item count - equal to number of tabs
        return 3;
    }     
}

Tab3.java

public class Tab3 extends Fragment {
    public static List<StatusResponse> mResponseList = new ArrayList<StatusResponse>();
    private ListView statusList;
    private RelativeLayout rlLoading;
    public ArrayList<StatusResponse> rowItems;
    private ExpandableListView expListView;
    private ExpandableListAdapter listAdapter;
    List<String> listDataHeader;
    HashMap<String, List<StatusResponse>> listDataChild;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        View v = inflater.inflate(R.layout.reportlayout, null);
        statusList = (ListView)v.findViewById(android.R.id.list);
        rlLoading = (RelativeLayout)v.findViewById(R.id.loadingPanel);          
        expListView = (ExpandableListView)v.findViewById(R.id.lvExpStatus);
        new GetStatusTask().execute();
        return v;
    }

    private class GetStatusTask extends AsyncTask<Void, Void, List<StatusResponse>> {
    }
}

1 个答案:

答案 0 :(得分:2)

new GetStatusTask().execute();移除onCreateView并将其放在以下代码中:

viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {    
           @Override
           public void onPageSelected(int position) {
               // on changing the page
               // make respected tab selected
               actionBar.setSelectedNavigationItem(position); 
               if(position == 2) {
                  new GetStatusTask().execute();
               }              
           }

           @Override
           public void onPageScrolled(int arg0, float arg1, int arg2) {
           }

           @Override
           public void onPageScrollStateChanged(int arg0) {
           }
       });   

或者您可以在onResume()而不是onCreateView调用它。

<强>更新

你的片段类中的

使用下面的代码:

 @Override
public void setUserVisibleHint(boolean isVisibleToUser) {
    super.setUserVisibleHint(isVisibleToUser);
    if(isVisible()){
        if(isVisibleToUser){
            Log.d("MyTag","My Fragment is visible");
        }else{
            Log.d("MyTag","My Fragment is not visible");
        }
    }
}