gpt4 book ai didi

android - 确定 fragment 重启是由于屏幕旋转还是 Viewpager 滑动?

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:14:09 26 4
gpt4 key购买 nike

我有一个带有 ViewPagerActivityViewPager 有很多页,就像一本书。每个 fragment 都有包含很多内容的RecyclerViews。以下是我的用例

1 - 当我滑动页面时,RecyclerView 必须从列表的开头开始。2. 如果我旋转我的设备,它应该从旋转前我离开的位置的确切最后位置开始读取。

如果我不使用任何逻辑,第二个场景就可以完美运行。即旋转。但不是第一种情况。

如果我像下面那样做一些逻辑。有助于实现第一种情况,但不是第二种情况。

  @Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
if (savedInstanceState==null) {
mIsFirstTime = true;
}
}

@Override
public void onResume() {
super.onResume();
try {
getActivity().invalidateOptionsMenu();
if (!mIsFirstTime) {
mListView.scrollToPosition(0);
}
} catch (Exception e) {
e.printStackTrace();
}

}

所以我的问题是

How can I determine a fragment restart is due to screen rotation or Viewpager swipe?

我已经尝试过 onConfigurationChanged(Configuration newConfig) 。但这对我没有帮助。你能帮帮我吗

最佳答案

来自 a comment of OP :

My question is how I know that onSaveInstanceState() is called due to screen orientation change and not fragment restart

您可以通过 Activity#isChangingConfigurations() 做到这一点API。


@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);

if (isChangingConfigurations()) {
// this callback is executed as a result of a configuration change (e.g. orientation change)
} else {
// no configuration change happens (e.g. a click on a home button would end up here)
}
}

现在您可以将 bool 值保存到 Bundle outState 和重新创建后的适当设置 UI 中:


@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putBoolean("isConfigurationChange", isChangingConfigurations());
}

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

// initialization logics here

if (savedInstanceState != null) {
boolean isConfigurationChange = savedInstanceState.getBoolean("isConfigurationChange");

// if `onCreate` is called as a result of configuration change
if (isConfigurationChange) {
// view hierarchy is not yet laid out, have to post an action
listView.post(new Runnable() {
@Override
public void run() {
// we are guaranteed, that `listView` is already laid out
listView.scrollToPosition(0);
}
});
}
}
}

请注意,在 onResume() 中执行 bool 值检查逻辑是一个错误(按下主页按钮并导航回应用程序会导致再次滚动到顶部,这是不需要的)。相反,应选择 onCreate() 作为正确的回调。

关于android - 确定 fragment 重启是由于屏幕旋转还是 Viewpager 滑动?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48495197/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com