如何避免片段使用AsyncTask重新显示所有内容

时间:2015-01-04 16:25:42

标签: android android-asynctask fragment

当我在Fragment选项卡之间切换时,我的Asynctask再次调用,因为我在 onCreateView 中调用了我的dataRecieving()方法。我知道片段的片段生命周期,但我怎么能避免片段回忆那个方法。我怎么能第二次知道片段显示。

@Override
public View onCreateView(LayoutInflater inflater,
        @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) 
{
    View view = inflater.inflate(R.layout.customer_all_promotion, container,false);

    listView = (ListView)view.findViewById(R.id.list);

    dataRecieving();

    return view;
}

但我怎样才能避免重新调用我的dataRecieving方法。

我尝试了什么

我已将dataRecieving方法放在onCreate中,但没有显示任何内容。

是否有任何委托/方法,我知道该片段第二次显示。

1 个答案:

答案 0 :(得分:0)

创建一个全局变量,并在onCreateView方法中进行检查。在onDestroyView中(当片段从屏幕出来时),您可以将此变量设置为false,然后下次调用onCreateView时,它会显示第二次显示。

public class FragmentRecipes extends Fragment{

   private boolean backstack = false;

   @Override
   public View onCreateView(LayoutInflater inflater,
        @Nullable ViewGroup container, @Nullable Bundle savedInstanceState){
    View view = inflater.inflate(R.layout.customer_all_promotion, container,false);

    listView = (ListView)view.findViewById(R.id.list);

    if(savedInstanceState == null && !backstack){
       // this will run only for first time, when the fragment is created
       dataRecieving();
    }

    return view;
}

@Override
public void onDestroyView(){
   super.onDestroyView();

   backstack = true;
}