我的主要活动中有3个标签。在第二个选项卡中,我有一个包含列表的片段,我正在使用Retrofit从我的服务器获取数据并将其显示在列表中。
在我的第二个片段中,我有:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.fragment_recents, container, false);
mRecyclerView = (RecyclerView) view.findViewById(R.id.recyclerView);
return view;
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
mRecyclerView.setHasFixedSize(true);
mLayoutManager = new LinearLayoutManager(getActivity());
mRecyclerView.setLayoutManager(mLayoutManager);
mRecyclerView.setItemAnimator(new DefaultItemAnimator());
getBooks();
}
private void getBooks(){
final ProgressDialog loading = ProgressDialog.show(getContext(), "Fetching Data", "Please wait...", false, false);
/* Retrofit code: */
//Creating a rest adapter
RestAdapter adapter = new RestAdapter.Builder()
.setEndpoint(ROOT_URL)
.build();
//Creating an object of our api interface
MyAPI api = adapter.create(MyAPI.class);
//Defining the method
api.getBooks(new Callback<List<MyPojo>>() {
@Override
public void success(List<MyPojo> list, Response response) {
//Dismissing the loading progressbar
loading.dismiss();
//Storing the data in our list
pojos = list;
mAdapter = new MyAdapter(getContext(), pojos);
mRecyclerView.setAdapter(mAdapter);
}
@Override
public void failure(RetrofitError error) {
//you can handle the errors here
loading.dismiss();
Log.v("Error: ", "" + error);
}
});
}
我的问题是,只要应用程序在第一个选项卡中启动,就会显示进度对话框。我希望它仅在第二个选项卡打开时才能获取数据。
答案 0 :(得分:0)
根据developer guide for fragments,片段的生命周期(参见链接中的图2)仅在onResume()
和onPause()
之间有效(即显示且用户可以与之交互) android回调。
如果您希望仅在显示片段时发生某些事情,请将代码放在onResume()
回调中。如果您愿意,可以在其他回调中预取或执行其他设置。
答案 1 :(得分:0)
将网络代码放入您的第二个Fragment
onResume()
@Override
public void onResume() {
super.onResume();
final ProgressDialog loading = ProgressDialog.show(getContext(), "Fetching Data", "Please wait...", false, false);
(and the rest is the Retrofit code)
}