3 回答
TA贡献1828条经验 获得超13个赞
// create boolean for fetching data
private boolean isViewShown = false;
@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (getView() != null) {
isViewShown = true;
// fetchdata() contains logic to show data when page is selected mostly asynctask to fill the data
fetchData();
} else {
isViewShown = false;
}
}
使用isViewShown实例变量来决定要在中onCreateView()还是在中获取数据setUserVisibleHint()。
下面的代码包含以下逻辑onCreateView():
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.main_layout, container, false);
// view initialization steps.......
if (!isViewShown) {
fetchData();
}
// do other stuff
}
此代码将解决您的问题。因为它解决了我的问题。:)
这个技巧将获取数据,onCreateView()以便直接从一页跳转到另一页,而当您滑动视图时,它将从setUserVisibleHint()方法中获取数据。:)
TA贡献1828条经验 获得超4个赞
您可以使用此逻辑,也可以viewDidAppear通过设置随时关闭isVisible = false
public class MyFragment extends Fragment {
private Boolean isStarted = false;
private Boolean isVisible = false;
@Override
public void onStart() {
super.onStart();
isStarted = true;
if (isVisible && isStarted){
viewDidAppear();
}
}
@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
isVisible = isVisibleToUser;
if (isStarted && isVisible) {
viewDidAppear();
}
}
public void viewDidAppear() {
// your logic
}
}
TA贡献1850条经验 获得超11个赞
我找到了最好的解决方案
private boolean isVisible;
private boolean isStarted;
@Override
public void onStart() {
super.onStart();
isStarted = true;
if (isVisible)
sendRequest(); //your request method
}
@Override
public void onStop() {
super.onStop();
isStarted = false;
}
@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
isVisible = isVisibleToUser;
if (isVisible && isStarted)
sendRequest(); //your request method
}
它是票价namrouti的答案的改进版本。我在许多条件下进行了测试。它是安全的。
- 3 回答
- 0 关注
- 969 浏览
添加回答
举报