检测何时在同一个应用程序启动中加载 Fragment
Detect when a Fragment is loaded withing the same app launch
我在加载片段时为卡片触发动画。但是每当用户导航到另一个片段并返回时,该动画就会再次触发。
我希望能够在应用程序启动时仅第一次制作动画。我尝试了以下几种方法,但无法实现。
- 在片段的 onPause() 中设置一个标志 - 似乎没有被触发
- 在 Bundle onPause() 中存储一个值
我想问一下每次加载片段时播放动画是否也是好的用户体验。
向您的片段添加一个静态布尔变量。当动画显示一次时,将其设置为 true。随后检查其值,如果为真,则不 运行 动画。像这样:
private class My Fragment extends Fragment {
private static boolean hasAnimationRun;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Some code
if (!hasAnimationRun) {
// Run your animation here.
hasAnimationRun = true;
}
// Some code
}
如果您只想在用户设备上首次启动应用程序时播放动画,您将使用 SharedPreferences。使用@androholic 解决方案,但在这种情况下布尔值不能是静态的。在onCreateView中每次都要确定,像这样:
...
SharedPreferences preferences = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
hasAnimationRun = preferences.getBoolean (FIRST_TIME_BOOLEAN_NAME, false);
if (!hasAnimationRun) {
//Run your animation here.
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean(FIRST_TIME_BOOLEAN_NAME, true);
editor.apply();
}
我在加载片段时为卡片触发动画。但是每当用户导航到另一个片段并返回时,该动画就会再次触发。
我希望能够在应用程序启动时仅第一次制作动画。我尝试了以下几种方法,但无法实现。
- 在片段的 onPause() 中设置一个标志 - 似乎没有被触发
- 在 Bundle onPause() 中存储一个值
我想问一下每次加载片段时播放动画是否也是好的用户体验。
向您的片段添加一个静态布尔变量。当动画显示一次时,将其设置为 true。随后检查其值,如果为真,则不 运行 动画。像这样:
private class My Fragment extends Fragment {
private static boolean hasAnimationRun;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Some code
if (!hasAnimationRun) {
// Run your animation here.
hasAnimationRun = true;
}
// Some code
}
如果您只想在用户设备上首次启动应用程序时播放动画,您将使用 SharedPreferences。使用@androholic 解决方案,但在这种情况下布尔值不能是静态的。在onCreateView中每次都要确定,像这样:
...
SharedPreferences preferences = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
hasAnimationRun = preferences.getBoolean (FIRST_TIME_BOOLEAN_NAME, false);
if (!hasAnimationRun) {
//Run your animation here.
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean(FIRST_TIME_BOOLEAN_NAME, true);
editor.apply();
}