我尝试使用AsyncTask和ProgressDialog从Fragment中的服务器加载数据。 这是PageAdapter代码
public class TabPagerAdapter extends FragmentPagerAdapter {
public TabPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int i) {
switch (i){
case 0: return new Fragment1();
case 1: return new Fragment2();
case 2: return new Fragment3();
}
return null;
}
@Override
public int getCount() {
return 3;
}
}
以下是我如何使用适配器
viewPager = (ViewPager) findViewById(R.id.pager);
actionBar = getActionBar();
mAdapter = new TabPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(mAdapter);
片段中的代码
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
appContext= (SApplication) getActivity().getApplicationContext();
mList.clear();
this.rootView = inflater.inflate(R.layout.fragment_event, container, false);
mListView = (ListView)rootView.findViewById(R.id.events);
this.asycnTask=new HttpRequestTask(getActivity());
return rootView;
}
@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (isVisibleToUser) {
if(asycnTask.getStatus().equals(AsyncTask.Status.PENDING)) {
this.asycnTask.execute();
}
}
}
我遇到的问题是每次刷到片段3时都会执行asyncTask。我只需要执行一次AsyncTask。
答案 0 :(得分:0)
你能设置一个阻止后续运行的标志吗?
private boolean wasAlreadyRunOnce;
.
.
.
if (isVisibleToUser && !wasAlreadyRunOnce) {
if(asycnTask.getStatus().equals(AsyncTask.Status.PENDING)) {
this.asycnTask.execute();
wasAlreadyRunOnce = true;
}
}