【问题标题】:Stop page refreshing in NavigationUI, Android Studio在 NavigationUI、Android Studio 中停止页面刷新
【发布时间】:2022-01-19 18:33:18
【问题描述】:

我是 Android 开发新手。有一个奇怪的错误,每当我尝试更改片段时,每次都会加载内容。我正在从第一个片段发出 API 请求,并且每次都会发出请求。

我不确定错误在哪里


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

        binding = ActivityBottomTabBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        BottomNavigationView navView = findViewById(R.id.nav_view);
        AppBarConfiguration appBarConfiguration = new AppBarConfiguration.Builder(
                R.id.navigation_home, R.id.navigation_dashboard, R.id.navigation_notifications)
                .build();
        NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment_activity_bottom_tab);
        NavigationUI.setupActionBarWithNavController(this, navController, appBarConfiguration);
        NavigationUI.setupWithNavController(binding.navView, navController);
    }

上面是底部标签的代码。

    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        binding = FragmentHomeBinding.inflate(inflater, container, false);
        View root = binding.getRoot();
        listView = binding.mobileList;
        cryptoList = new ArrayList<String>();
        loadCoinList();
        return root;
    }

这是first fragment的代码。

【问题讨论】:

  • 所以你的意思是每当你返回到第一个片段时,内容就会再次加载?
  • 没错,有什么办法可以恢复以前的状态吗?

标签: android android-studio


【解决方案1】:

发生这种情况是因为每次切换片段时,片段都会被销毁并重新创建,再次调用 onCreateView 中的方法。这就是 bottomNavigation 的工作原理。

如果你想保留数据,你可以使用 viewModels。 这里看看:ViewModel

Viewmodel 易于使用,您还可以保留有关配置更改的数据,例如屏幕旋转

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-11-14
    • 1970-01-01
    • 1970-01-01
    • 2019-05-26
    • 2021-04-01
    • 1970-01-01
    • 2013-02-11
    • 1970-01-01
    相关资源
    最近更新 更多